问:
How to reset PipeReader to be able to re-read request body in ASP.NET Core
I have some ASP.NET Core middleware (an AuthorizationHandler) that needs to access the body of the request to perform an authorization check. I use the new pipelines APIs to access the request body. The code looks like this:

```<code>PipeReader bodyReader = httpContext.Request.BodyReader;

ReadResult readResult = await bodyReader.ReadAsync();
ReadOnlySequence<byte> readResultBuffer = readResult.Buffer;

var utf8JsonReader = new Utf8JsonReader(bytes);
while (utf8JsonReader.Read()) { ... }
</code>```

When this code has run, the body stream is read. The controller that I want to call throws a validation error because it doesn't see a request body because it was already read.

So how do I reset the PipeReader so that the request body can be re-read?

I know that when you do not use BodyReader but Body, you can use EnableBuffering to enable request re-reads. However, when using pipelines, this no longer works (or I'm doing something else wrong).

答:
I create an issue yesterday. See jkotalik's comment :

By passing in readResult.Buffer.Start for consumed, you are saying that you haven't consumed any of the ReadResult. By passing in readResult.Buffer.End, you are saying you have examined everything, which tells the Pipe to not free any buffers and the next time ReadAsync returns, more data would be in the buffer

This inspires me to invoke bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.Start); to reset the examined position.

For example, your middleware can be written as below :

```
async Task IMiddleware.InvokeAsync(HttpContext httpContext, RequestDelegate next)
{
    if(httpContext.Request.Method != HttpMethods.Post){
        return;
    }
    var bodyReader = httpContext.Request.BodyReader; // don't get it by `PipeReader.Create(httpContext.Request.Body);`

    // demo:  read all the body without consuming it
    ReadResult readResult;
    while(true){
        readResult = await bodyReader.ReadAsync();
        if(readResult.IsCompleted) { break; }
        // don't consume them, but examine them
        <b>bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);</b>
    }
    // now all the body payload has been read into buffer
    var buffer = readResult.Buffer;
    Process(ref buffer);              // process the payload (ReadOnlySequence)

    // Finally, <b>reset the EXAMINED POSITION</b> here
    <b>bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.Start);</b>
    await next(httpContext);
}

void Process(ref ReadOnlySequence<byte> buffer){
    var utf8JsonReader = new Utf8JsonReader(buffer);
    while (utf8JsonReader.Read()) {
        Console.WriteLine($"{utf8JsonReader.TokenType}");
        ...
    }
}
```

(The Key is the AdvanceTo() can not only forward the consumed position, but also can change the examined position)

Body:
I have some ASP.NET Core middleware (an AuthorizationHandler) that needs to access the body of the request to perform an authorization check. I use the new pipelines APIs to access the request body. The code looks like this:

PipeReader bodyReader = httpContext.Request.BodyReader;

ReadResult readResult = await bodyReader.ReadAsync();
ReadOnlySequence<byte> readResultBuffer = readResult.Buffer;

var utf8JsonReader = new Utf8JsonReader(bytes);
while (utf8JsonReader.Read()) { ... }

When this code has run, the body stream is read. The controller that I want to call throws a validation error because it doesn't see a request body because it was already read.

So how do I reset the PipeReader so that the request body can be re-read?

I know that when you do not use BodyReader but Body, you can use EnableBuffering to enable request re-reads. However, when using pipelines, this no longer works (or I'm doing something else wrong).

Body:
I create an issue yesterday. See jkotalik's comment :

By passing in readResult.Buffer.Start for consumed, you are saying that you haven't consumed any of the ReadResult. By passing in readResult.Buffer.End, you are saying you have examined everything, which tells the Pipe to not free any buffers and the next time ReadAsync returns, more data would be in the buffer

This inspires me to invoke bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.Start); to reset the examined position.

For example, your middleware can be written as below :

async Task IMiddleware.InvokeAsync(HttpContext httpContext, RequestDelegate next)
{
    if(httpContext.Request.Method != HttpMethods.Post){
        return;
    }
    var bodyReader = httpContext.Request.BodyReader; // don't get it by `PipeReader.Create(httpContext.Request.Body);`

    // demo:  read all the body without consuming it
    ReadResult readResult;
    while(true){
        readResult = await bodyReader.ReadAsync();
        if(readResult.IsCompleted) { break; }
        // don't consume them, but examine them
        bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
    }
    // now all the body payload has been read into buffer
    var buffer = readResult.Buffer;
    Process(ref buffer);              // process the payload (ReadOnlySequence)

    // Finally, reset the EXAMINED POSITION here
    bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.Start);
    await next(httpContext);
}

void Process(ref ReadOnlySequence<byte> buffer){
    var utf8JsonReader = new Utf8JsonReader(buffer);
    while (utf8JsonReader.Read()) {
        Console.WriteLine($"{utf8JsonReader.TokenType}");
        ...
    }
}

(The Key is the AdvanceTo() can not only forward the consumed position, but also can change the examined position)


来源: stackexchange

问:
How do i use MMX mulH and mulL for two 64 bit integers to get one 128 bit integer
Hello, I'm working on yet another arbitrary precision integer library. I wanted to implement multiplication but I got stuck when _m_pmulhw in <mmintrin.h> just didn't work. there is very little documentation on MMX instructions. When I test it out, it just gives me gibberish when I multiply two UINT64_MAXs.

```<code>uint_fast64_t mulH(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmulhw((__m64)a,(__m64)b);
}
uint_fast64_t mulL(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmullw((__m64)a,(__m64)b);
}
int main() {
    uint64_t a = UINT64_MAX;
    uint64_t b = UINT64_MAX;
    std::cout <<  std::bitset<64>(mulH(a,b)) << std::bitset<64>(mulL(a,b));
}

output: 00000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001
</code>```

I don't know why it's not working i have an A6-4400M APU...

coreinfo's output:MMX             *       Supports MMX instruction set

So I think I can say, it isn't unsupported. If anyone can give me some tips on how to make this work thanks.

Compiler: gcc

IDE: visual studio code

答:
I think you misunderstood what _m_pmulhw does. It's actually very clearly documented on Intel's Intrinsics Guide: https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_m_pmulhw&expand=4340. The corresponding instruction is pmulhw, which is also clearly documented on e.g. Felix Cloutier's x86 instructions guide: https://www.felixcloutier.com/x86/pmulhw

It multiplies four pairs of 16-bit integers which are packed inside the two operands, and then produces the high half of all four multiplies (Packed Multiply High - Word). This means that, for inputs 0x12345678abcdef01, 0x9876543210fedcba, it would multiply 0x1234 * 0x9876, 0x5678 * 0x5432, 0xabcd * 0x10fe, 0xef01 * 0xdcba, and pack the high 16 bits of each result into the output.

For your example, you're multiplying 0xffff * 0xffff four times, producing the 32-bit result 0x00000001 (-1 * -1, since this is a signed 16-bit multiply), and therefore get 0x0000000000000000 in the high half and 0x0001000100010001 in the low half - which is exactly what you see in the bitset output.

If you're looking for a 128-bit multiply, there isn't actually an intrinsic for that (except _mulx_u64, but that uses the new mulx instruction which isn't that widespread). Microsoft has the non-standard _mul128 intrinsic, but on other platforms you can just use a __int128 type (or the local equivalent) to get a 64x64=>128 bit multiply.

Also, I'd seriously recommend using the SSE instruction set rather than the older MMX set; the SSE instructions are faster in most cases and enable you to operate on much wider vector types (256-bit is standard now, with AVX512 now available), which can provide a significant speed boost.

ContentLicense: CC BY-SA 4.0

Body:
Hello, I'm working on yet another arbitrary precision integer library. I wanted to implement multiplication but I got stuck when _m_pmulhw in <mmintrin.h> just didn't work. there is very little documentation on MMX instructions. When I test it out, it just gives me gibberish when I multiply two UINT64_MAXs.

uint_fast64_t mulH(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmulhw((__m64)a,(__m64)b);
}
uint_fast64_t mulL(const uint_fast64_t &a, const uint_fast64_t &b)  {
    return (uint_fast64_t)_m_pmullw((__m64)a,(__m64)b);
}
int main() {
    uint64_t a = UINT64_MAX;
    uint64_t b = UINT64_MAX;
    std::cout <<  std::bitset<64>(mulH(a,b)) << std::bitset<64>(mulL(a,b));
}

output: 00000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001

I don't know why it's not working i have an A6-4400M APU...

coreinfo's output:MMX             *       Supports MMX instruction set

So I think I can say, it isn't unsupported. If anyone can give me some tips on how to make this work thanks.

Compiler: gcc

IDE: visual studio code


问:
How to invoke didChange on textView in TableView
I have a textView embedded in a cell in a tableView and am trying to determine whether the text has been changed when the user presses done.

When a user taps on a note, it loads the note from the database, they can make edits, and press done. When they press done I need to invoke didChange to make sure that they changed something to avoid writing the same information back to the database. I've set my cell as a UITextFieldDelegate and tried setting didChange.

```<code>import UIKit

class NoteEditTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var editorView: UITextView!
    var origionalContent = ""

    var didContentChange = false

    func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<NoteEditTableViewCell, Value>) {
        debugPrint("Content Changed")
    }
}
</code>```

I can't get didChange to invoke though. No matter what I change in that field, it never prints the debug message.

答:
You can use callback function here. You can also use callback function like this for button tap action in tableViewCell. That will respond in tableview.

1)Declare callback function in your tableViewCell file. Here this callback function pass String, you can use any type you want or you can leave it empty[()->()] if you just want to detect this function call in tableview.

```<code>var textViewTextChangeCallback:((String) -> Void)?
</code>```

2) use UITextViewDelegate with textViewDidChange in your tableViewCell file. Put this extension into your tableViewCell file. call the callback function here & pass anything you want.

```<code>extension NoteEditTableViewCell: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        textViewTextChangeCallback?(textView.text)
    }
 }
</code>```

3)Define your callback closure in cellForRawAt of UITableViewDataSource in your ViewController file.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifire") as! NoteEditTableViewCell

        cell.textViewTextChangeCallback = { [unowned self] text in
            print(text)
            // if you want to save text on buttonClick when textViewDidChange call, create callback function for buttonClick & call its's closure here. i already show you how to define callback function follow as abov for any click you want from tableViewCell ;)
        }
    }
    return cell

}
</code>```

Body:
I have a textView embedded in a cell in a tableView and am trying to determine whether the text has been changed when the user presses done.

When a user taps on a note, it loads the note from the database, they can make edits, and press done. When they press done I need to invoke didChange to make sure that they changed something to avoid writing the same information back to the database. I've set my cell as a UITextFieldDelegate and tried setting didChange.

import UIKit

class NoteEditTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var editorView: UITextView!
    var origionalContent = ""

    var didContentChange = false

    func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<NoteEditTableViewCell, Value>) {
        debugPrint("Content Changed")
    }
}

I can't get didChange to invoke though. No matter what I change in that field, it never prints the debug message.

Body:
You can use callback function here. You can also use callback function like this for button tap action in tableViewCell. That will respond in tableview.

1)Declare callback function in your tableViewCell file. Here this callback function pass String, you can use any type you want or you can leave it empty[()->()] if you just want to detect this function call in tableview.

var textViewTextChangeCallback:((String) -> Void)?

2) use UITextViewDelegate with textViewDidChange in your tableViewCell file. Put this extension into your tableViewCell file. call the callback function here & pass anything you want.

extension NoteEditTableViewCell: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        textViewTextChangeCallback?(textView.text)
    }
 }

3)Define your callback closure in cellForRawAt of UITableViewDataSource in your ViewController file.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifire") as! NoteEditTableViewCell

        cell.textViewTextChangeCallback = { [unowned self] text in
            print(text)
            // if you want to save text on buttonClick when textViewDidChange call, create callback function for buttonClick & call its's closure here. i already show you how to define callback function follow as abov for any click you want from tableViewCell ;)
        }
    }
    return cell

}


问:
How can i center a <mat-card> in the middle of the screen in Angular 9
* I have a <mat-card> that i want to center in the middle of the screen I tried but it didn't center. It should looks good in toggle-device-toolbar because its for phones, i need some help with this.Im using angular-material and ng-bootstrap*

This is the code of the <mat-card>

    <mat-card>
    <mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
        <mat-radio-button  [value]="true" >Admin</mat-radio-button>
        <mat-radio-button [value]="false">User</mat-radio-button>
    </mat-radio-group>

            <form class="example-form " [formGroup]="loginForm" (ngSubmit)="send()">
                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Identifier" placeholder="User" >
                </mat-form-field>

Introduce an email

                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Password" placeholder="Password" type="password">
                </mat-form-field>

Introduce the correctly password

                <button mat-raised-button [disabled]="loginForm.invalid" class="colour_button " type="submit">Login 1</button>
            </form>

</mat-card>

```

This is how it looks like right now

答:
You can do it with Flexbox

In the style of the component you have to add:

```<code>.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
</code>```

Also, if you change grid for flex it should work too.

```<code>.container {
  display: grid;
  align-items: center;
  justify-content: center;
}
</code>```

Body:
* I have a <mat-card> that i want to center in the middle of the screen I tried but it didn't center. It should looks good in toggle-device-toolbar because its for phones, i need some help with this.Im using angular-material and ng-bootstrap*

This is the code of the <mat-card>

    <mat-card>
    <mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
        <mat-radio-button  [value]="true" >Admin</mat-radio-button>
        <mat-radio-button [value]="false">User</mat-radio-button>
    </mat-radio-group>

            <form class="example-form " [formGroup]="loginForm" (ngSubmit)="send()">
                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Identifier" placeholder="User" >
                </mat-form-field>

Introduce an email

                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Password" placeholder="Password" type="password">
                </mat-form-field>

Introduce the correctly password

                <button mat-raised-button [disabled]="loginForm.invalid" class="colour_button " type="submit">Login 1</button>
            </form>

</mat-card>

This is how it looks like right now

Body:
You can do it with Flexbox

In the style of the component you have to add:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

Also, if you change grid for flex it should work too.

.container {
  display: grid;
  align-items: center;
  justify-content: center;
}


问:
Need help setting up this MongoDB query
I am using MongoDB with the Node.JS driver.

My DB is arranged like this -

```<code> {
    _id: ...,
    nfoo: ...,
    nbar: ...,
    nbaz: ...,
    items: [
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>},
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>}, ... ]
    <other properties>
    }
    {
    _id: ...,
    nfoo: ...,
    nbar: ...,
    nbaz: ...,
    items: [
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>},
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>}, ... ]
    <other properties>
    }
</code>```

What I want to do is arrange this as a table with the headers like this

```<code>nfoo    nbar    nbaz    i_foobar    i_barbaz
</code>```

Where nfoo, nbar and nbaz are all available at the top level document and i_xxxxxx will be calculated by iterating over the array of subdocs like this

```<code>i_foobar = (ifoo/ibar if completed=true) for item 1 + (ifoo/ibar if completed=true) for item 2 + ...
i_barbaz = (ibar/ibaz) for item 1 + (ibar/ibaz) for item2 + ...
</code>```

So far I have figured out how to get just nfoo/bar/baz out of the documents

```<code>collection.find({},
        {
            projection: {
                _id: 0,
                nfoo: 1,
                nbar: 1,
                nbaz: 1
            }
        }).toArray((err, res) => {
        all_data = res
        // At this point my all_data is arranged like so [{nfoo: , nbar: , nbaz: }, {nfoo: , nbar: , nbaz: }] which makes it easy to make the table by just iterating over the data and separating the keys from the values
        let heads = Object.keys(all_data[0])
        generateTableHead(table, heads);
        generateTable(table, all_data);
    })
</code>```

generateTableHead() and generateTable() are from here

My question is how do I modify the collection.find statement to get i_foobar and i_barbaz items?

edit: Some simplification

items is an array of subdocuments

i_foobar = sum of (ifoo/ibar) over all items where completed=true

i_barbaz = sum of (ibar/ibaz) over all items

For example,

```<code>{
    _id: ...,
    nfoo: "foo",
    nbar: "bar",
    nbaz: "baz",
    items: [
    { completed:  true, ifoo: 20, ibar: 10, ibaz: 300},
    { completed:  false, ifoo: 50, ibar: 300, ibaz: 24},
    { completed:  true, ifoo: 40, ibar: 90, ibaz: 20} ]
    <other properties>
    }
</code>```

For this document,

i_foobar = 20/10 (because completed=true for item 1) + 0 (completed = false for item 2) + 40/90 (completed=true for item 3)

i_barbaz = 10/300 + 300/24 + 90/20

答:
I think you can get what you are looking for with aggregation.  First unwind the items array, then group by the top level fields and use $cond with $sum for each item.

db.collection.aggregate([
    {$unwind:"$items"},
    {$group:{
        _id:"$_id",
        nfoo:{$first:"$nfoo"},
        nbar:{$first:"$nbar"},
        nbaz:{$first:"$nbaz"),
        i_foobar:{$sum:{$cond:["$completed",{$divide:["$ifoo","$ibar"]},0]}},
        i_barbaz:{$sum:{$cond:["$completed",{$divide:["$ibar","$ibaz"]},0]}}
    }}
])
```

Title: Need help setting up this MongoDB query

Body:
I am using MongoDB with the Node.JS driver.

My DB is arranged like this -

 {
    _id: ...,
    nfoo: ...,
    nbar: ...,
    nbaz: ...,
    items: [
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>},
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>}, ... ]
    <other properties>
    }
    {
    _id: ...,
    nfoo: ...,
    nbar: ...,
    nbaz: ...,
    items: [
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>},
    { completed:  true/false, ifoo: <number>, ibar: <number>, ibaz: <number>}, ... ]
    <other properties>
    }

What I want to do is arrange this as a table with the headers like this

nfoo    nbar    nbaz    i_foobar    i_barbaz

Where nfoo, nbar and nbaz are all available at the top level document and i_xxxxxx will be calculated by iterating over the array of subdocs like this

i_foobar = (ifoo/ibar if completed=true) for item 1 + (ifoo/ibar if completed=true) for item 2 + ...
i_barbaz = (ibar/ibaz) for item 1 + (ibar/ibaz) for item2 + ...

So far I have figured out how to get just nfoo/bar/baz out of the documents

collection.find({},
        {
            projection: {
                _id: 0,
                nfoo: 1,
                nbar: 1,
                nbaz: 1
            }
        }).toArray((err, res) => {
        all_data = res
        // At this point my all_data is arranged like so [{nfoo: , nbar: , nbaz: }, {nfoo: , nbar: , nbaz: }] which makes it easy to make the table by just iterating over the data and separating the keys from the values
        let heads = Object.keys(all_data[0])
        generateTableHead(table, heads);
        generateTable(table, all_data);
    })

generateTableHead() and generateTable() are from here

My question is how do I modify the collection.find statement to get i_foobar and i_barbaz items?

edit: Some simplification

items is an array of subdocuments

i_foobar = sum of (ifoo/ibar) over all items where completed=true

i_barbaz = sum of (ibar/ibaz) over all items

For example,

{
    _id: ...,
    nfoo: "foo",
    nbar: "bar",
    nbaz: "baz",
    items: [
    { completed:  true, ifoo: 20, ibar: 10, ibaz: 300},
    { completed:  false, ifoo: 50, ibar: 300, ibaz: 24},
    { completed:  true, ifoo: 40, ibar: 90, ibaz: 20} ]
    <other properties>
    }

For this document,

i_foobar = 20/10 (because completed=true for item 1) + 0 (completed = false for item 2) + 40/90 (completed=true for item 3)

i_barbaz = 10/300 + 300/24 + 90/20


问:
How can i loop the textview based on array that i have in android?
i have a response of JSONArray that look like this:

```<code>[
   {
      "sub_directory_name":"Directory 1",
      "address":"Address 1",
      "email":[
         {
            "key":0,
            "value":"Directory 1 Email"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 1 Contact Num"
         }
      ],
      "description":""
   },
   {
      "sub_directory_name":"Directory 2",
      "address":"Directory 2 Address",
      "email":[
         {
            "key":0,
            "value":"Directory 2 Email"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 2 Contact"
         }
      ],
      "description":""
   },
   {
      "sub_directory_name":"Directory 3",
      "address":"Directory 3 Address",
      "email":[
         {
            "key":0,
            "value":"Directory 3 Email 3.1"
         },
         {
            "key":1,
            "value":"Directory 3 Email 3.2"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 3 Contact 3.1"
         },
         {
            "key":1,
            "value":"Directory 3 Contact 3.2"
         }
      ],
      "description":""
   },
   {
      "sub_directory_name":"Directory 4",
      "address":"Directory 4 Address",
      "email":[
         {
            "key":0,
            "value":"Directory 4 Email 4.1"
         },
         {
            "key":1,
            "value":"Directory 4 Email 4.2"
         },
         {
            "key":2,
            "value":"Directory 4 Email 4.3"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 4 Contact 4.1"
         },
         {
            "key":1,
            "value":"Directory 4 Contact 4.1"
         }
      ],
      "description":""
   }
]
</code>```

How can i make my view to be like this using textview?

```<code>Directory 1
Address: Address 1
Email: Directory 1 Email
Contact: Directory 1 Contact Num

Directory 2
Address: Directory 2 Address
Email: Director 2 Email
Contact: Directory 2 Contact

Directory 3
Address: Directory 3 Address
Email: Directory 3 Email 3.1
       Directory 3 Email 3.2
Contact: Directory 3 Contact 3.1
         Directory 3 Contact 3.2

Directory 4
Address: Directory 4 Address
Email:Directory 4 Email 4.1
      Directory 4 Email 4.2
      Directory 4 Email 4.3
Contact:Directory 4 Contact 4.1
        Directory 4 Contact 4.2

</code>```

My current code is look this:

```<code>DirectoryCustomListAdapter

 public class DirectoryCustomListAdapter extends BaseAdapter {
    private ArrayList<DirectoryDetailsModel> listData;
    private LayoutInflater layoutInflater;

    public DirectoryCustomListAdapter(Context aContext, ArrayList<DirectoryDetailsModel> listData) {
        this.listData = listData;
        layoutInflater = LayoutInflater.from(aContext);
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.activity_detail_directories, null);
            holder = new ViewHolder();
            holder.tvSubDirectory = (TextView) convertView.findViewById(R.id.tvSubDirectory);
            holder.tvDirectoryAddress = (TextView) convertView.findViewById(R.id.tvDirectoryAddress);
            holder.tvDirectoryEmail = (TextView) convertView.findViewById(R.id.tvDirectoryEmail);
            holder.tvDirectoryContact = (TextView) convertView.findViewById(R.id.tvDirectoryContact);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tvSubDirectory.setText(listData.get(position).getSub_directory_name());
        holder.tvDirectoryAddress.setText(listData.get(position).getSub_address());
        holder.tvDirectoryEmail.setText(listData.get(position).getSub_email().toString());
        holder.tvDirectoryContact.setText(listData.get(position).getSub_contact().toString());

        return convertView;
    }

    static class ViewHolder {
        TextView tvSubDirectory,tvDirectoryAddress,tvDirectoryEmail,tvDirectoryContact;
    }
}
</code>```

```<code>MyModel

public class DirectoryDetailsModel {

    public String sub_directory_name;
    public String sub_address;
    private JSONArray sub_email;
    private JSONArray sub_contact;

    public String getSub_directory_name() {
        return sub_directory_name;
    }

    public void setSub_directory_name(String sub_directory_name) {
        this.sub_directory_name = sub_directory_name;
    }

    public String getSub_address() {
        return sub_address;
    }

    public void setSub_address(String sub_address) {
        this.sub_address = sub_address;
    }

    public JSONArray getSub_email() {
        return sub_email;
    }

    public void setSub_email(JSONArray sub_email) {
        this.sub_email = sub_email;
    }

    public JSONArray getSub_contact() {
        return sub_contact;
    }

    public void setSub_contact(JSONArray sub_contact) {
        this.sub_contact = sub_contact;
    }

}
</code>```

```<code>MainActivity

public class DirectoryDetailActivity extends AppCompatActivity {

    JSONArray subdirectory_details;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_directories);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        // add back arrow to toolbar
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        ArrayList details = getListData();
        final ListView listViewDirectory = (ListView) findViewById(R.id.custom_list);
        listViewDirectory.setAdapter(new DirectoryCustomListAdapter(this, details));

    }

    private ArrayList getListData() {
        ArrayList<DirectoryDetailsModel> results = new ArrayList<DirectoryDetailsModel>();
        try{

            subdirectory_details  = new JSONArray(getIntent().getStringExtra("subdirectory_details"));

            for (int i=0; i < subdirectory_details.length(); i++)
            {
                JSONObject detail_object = subdirectory_details.getJSONObject(i);

                // get all value here

                String detail_sub_directory = detail_object.getString("sub_directory_name");

                Log.d("detail_directory_subsss",detail_sub_directory);

            }

        }
        catch (org.json.JSONException jsone){
            jsone.printStackTrace();
        }

        return results;

    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}
</code>```

I am trying to store each on the ArrayList, i am still trying to experiment it when i tried to use arraylist i don't know if i am doing it right but it is only displaying the last element in the array. is there an easy way i can do this on textview? any help will be really appreciated.

答: Instead of looping Use recyclerview with viewholders (reusable view)</p>

Body:
i have a response of JSONArray that look like this:

[
   {
      "sub_directory_name":"Directory 1",
      "address":"Address 1",
      "email":[
         {
            "key":0,
            "value":"Directory 1 Email"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 1 Contact Num"
         }
      ],
      "description":""
   },
   {
      "sub_directory_name":"Directory 2",
      "address":"Directory 2 Address",
      "email":[
         {
            "key":0,
            "value":"Directory 2 Email"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 2 Contact"
         }
      ],
      "description":""
   },
   {
      "sub_directory_name":"Directory 3",
      "address":"Directory 3 Address",
      "email":[
         {
            "key":0,
            "value":"Directory 3 Email 3.1"
         },
         {
            "key":1,
            "value":"Directory 3 Email 3.2"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 3 Contact 3.1"
         },
         {
            "key":1,
            "value":"Directory 3 Contact 3.2"
         }
      ],
      "description":""
   },
   {
      "sub_directory_name":"Directory 4",
      "address":"Directory 4 Address",
      "email":[
         {
            "key":0,
            "value":"Directory 4 Email 4.1"
         },
         {
            "key":1,
            "value":"Directory 4 Email 4.2"
         },
         {
            "key":2,
            "value":"Directory 4 Email 4.3"
         }
      ],
      "contact_no":[
         {
            "key":0,
            "value":"Directory 4 Contact 4.1"
         },
         {
            "key":1,
            "value":"Directory 4 Contact 4.1"
         }
      ],
      "description":""
   }
]

How can i make my view to be like this using textview?

Directory 1
Address: Address 1
Email: Directory 1 Email
Contact: Directory 1 Contact Num

Directory 2
Address: Directory 2 Address
Email: Director 2 Email
Contact: Directory 2 Contact

Directory 3
Address: Directory 3 Address
Email: Directory 3 Email 3.1
       Directory 3 Email 3.2
Contact: Directory 3 Contact 3.1
         Directory 3 Contact 3.2

Directory 4
Address: Directory 4 Address
Email:Directory 4 Email 4.1
      Directory 4 Email 4.2
      Directory 4 Email 4.3
Contact:Directory 4 Contact 4.1
        Directory 4 Contact 4.2

My current code is look this:

DirectoryCustomListAdapter

 public class DirectoryCustomListAdapter extends BaseAdapter {
    private ArrayList<DirectoryDetailsModel> listData;
    private LayoutInflater layoutInflater;

    public DirectoryCustomListAdapter(Context aContext, ArrayList<DirectoryDetailsModel> listData) {
        this.listData = listData;
        layoutInflater = LayoutInflater.from(aContext);
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.activity_detail_directories, null);
            holder = new ViewHolder();
            holder.tvSubDirectory = (TextView) convertView.findViewById(R.id.tvSubDirectory);
            holder.tvDirectoryAddress = (TextView) convertView.findViewById(R.id.tvDirectoryAddress);
            holder.tvDirectoryEmail = (TextView) convertView.findViewById(R.id.tvDirectoryEmail);
            holder.tvDirectoryContact = (TextView) convertView.findViewById(R.id.tvDirectoryContact);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tvSubDirectory.setText(listData.get(position).getSub_directory_name());
        holder.tvDirectoryAddress.setText(listData.get(position).getSub_address());
        holder.tvDirectoryEmail.setText(listData.get(position).getSub_email().toString());
        holder.tvDirectoryContact.setText(listData.get(position).getSub_contact().toString());

        return convertView;
    }

    static class ViewHolder {
        TextView tvSubDirectory,tvDirectoryAddress,tvDirectoryEmail,tvDirectoryContact;
    }
}

MyModel

public class DirectoryDetailsModel {

    public String sub_directory_name;
    public String sub_address;
    private JSONArray sub_email;
    private JSONArray sub_contact;

    public String getSub_directory_name() {
        return sub_directory_name;
    }

    public void setSub_directory_name(String sub_directory_name) {
        this.sub_directory_name = sub_directory_name;
    }

    public String getSub_address() {
        return sub_address;
    }

    public void setSub_address(String sub_address) {
        this.sub_address = sub_address;
    }

    public JSONArray getSub_email() {
        return sub_email;
    }

    public void setSub_email(JSONArray sub_email) {
        this.sub_email = sub_email;
    }

    public JSONArray getSub_contact() {
        return sub_contact;
    }

    public void setSub_contact(JSONArray sub_contact) {
        this.sub_contact = sub_contact;
    }

}

MainActivity

public class DirectoryDetailActivity extends AppCompatActivity {

    JSONArray subdirectory_details;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_directories);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        // add back arrow to toolbar
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        ArrayList details = getListData();
        final ListView listViewDirectory = (ListView) findViewById(R.id.custom_list);
        listViewDirectory.setAdapter(new DirectoryCustomListAdapter(this, details));

    }

    private ArrayList getListData() {
        ArrayList<DirectoryDetailsModel> results = new ArrayList<DirectoryDetailsModel>();
        try{

            subdirectory_details  = new JSONArray(getIntent().getStringExtra("subdirectory_details"));

            for (int i=0; i < subdirectory_details.length(); i++)
            {
                JSONObject detail_object = subdirectory_details.getJSONObject(i);

                // get all value here

                String detail_sub_directory = detail_object.getString("sub_directory_name");

                Log.d("detail_directory_subsss",detail_sub_directory);

            }

        }
        catch (org.json.JSONException jsone){
            jsone.printStackTrace();
        }

        return results;

    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}

I am trying to store each on the ArrayList, i am still trying to experiment it when i tried to use arraylist i don't know if i am doing it right but it is only displaying the last element in the array. is there an easy way i can do this on textview? any help will be really appreciated.


问:
Why do we have to normalize the input for an artificial neural network?
Why do we have to normalize the input for a neural network?

I understand that sometimes, when for example the input values are non-numerical a certain transformation must be performed, but when we have a numerical input? Why the numbers must be in a certain interval?

What will happen if the data is not normalized?

答:
There are 2 Reasons why we have to Normalize Input Features before Feeding them to Neural Network:

Reason 1: If a Feature in the Dataset is big in scale compared to others then this big scaled feature becomes dominating and as a result of that, Predictions of the Neural Network will not be Accurate.

Example: In case of Employee Data, if we consider Age and Salary, Age will be a Two Digit Number while Salary can be 7 or 8 Digit (1 Million, etc..). In that Case, Salary will Dominate the Prediction of the Neural Network. But if we Normalize those Features, Values of both the Features will lie in the Range from (0 to 1).

Reason 2: Front Propagation of Neural Networks involves the Dot Product of Weights with Input Features. So, if the Values are very high (for Image and Non-Image Data), Calculation of Output takes a lot of Computation Time as well as Memory. Same is the case during Back Propagation. Consequently, Model Converges slowly, if the Inputs are not Normalized.

Example: If we perform Image Classification, Size of Image will be very huge, as the Value of each Pixel ranges from 0 to 255. Normalization in this case is very important.

Mentioned below are the instances where Normalization is very important:

K-Means

K-Nearest-Neighbours

Principal Component Analysis (PCA)

Gradient Descent


问:
Python replacement for SQL bcp.exe
The goal is to load a csv file into an Azure SQL database from Python directly, that is, not by calling bcp.exe. The csv files will have the same number of fields as do the destination tables. It'd be nice to not have to create the format file bcp.exe requires (xml for +-400 fields for each of 16 separate tables).

Following the Pythonic approach, try to insert the data and ask SQL Server to throw an exception if there is a type mismatch, or other.

答:
If you don't want use bcp cammand to import the csv file, you can using Python pandas library.

Here's the example that I import a no header 'test9.csv' file on my computer to Azure SQL database.

Csv file:

Python code example:

```<code>import pandas as pd
import sqlalchemy
import urllib
import pyodbc

# set up connection to database (with username/pw if needed)
params = urllib.parse.quote_plus("Driver={ODBC Driver 17 for SQL Server};Server=tcp:***.database.windows.net,1433;Database=Mydatabase;Uid=***@***;Pwd=***;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;")

engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

# read csv data to dataframe with pandas
# datatypes will be assumed
# pandas is smart but you can specify datatypes with the `dtype` parameter
df = pd.read_csv (r'C:\Users\leony\Desktop\test9.csv',header=None,names = ['id', 'name', 'age'])

# write to sql table... pandas will use default column names and dtypes
df.to_sql('test9',engine,if_exists='append',index=False)

# add 'dtype' parameter to specify datatypes if needed; dtype={'column1':VARCHAR(255), 'column2':DateTime})
</code>```

Notice:

get the connect string on Portal.

UID format is like [username]@[servername].

Run this scripts and it works:

Please reference these documents:

HOW TO IMPORT DATA IN PYTHON

pandas.DataFrame.to_sql

Hope this helps.

Title: Python replacement for SQL bcp.exe

Body:
If you don't want use bcp cammand to import the csv file, you can using Python pandas library.

Here's the example that I import a no header 'test9.csv' file on my computer to Azure SQL database.

Csv file:

Python code example:

import pandas as pd
import sqlalchemy
import urllib
import pyodbc

# set up connection to database (with username/pw if needed)
params = urllib.parse.quote_plus("Driver={ODBC Driver 17 for SQL Server};Server=tcp:***.database.windows.net,1433;Database=Mydatabase;Uid=***@***;Pwd=***;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;")

engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

# read csv data to dataframe with pandas
# datatypes will be assumed
# pandas is smart but you can specify datatypes with the `dtype` parameter
df = pd.read_csv (r'C:\Users\leony\Desktop\test9.csv',header=None,names = ['id', 'name', 'age'])

# write to sql table... pandas will use default column names and dtypes
df.to_sql('test9',engine,if_exists='append',index=False)

# add 'dtype' parameter to specify datatypes if needed; dtype={'column1':VARCHAR(255), 'column2':DateTime})

Notice:

get the connect string on Portal.

UID format is like [username]@[servername].

Run this scripts and it works:

Please reference these documents:

HOW TO IMPORT DATA IN PYTHON

pandas.DataFrame.to_sql

Hope this helps.


问:
Firebase user's context.auth is present still allAuthenticatedUsers secured Google function error with UNAUTHENTICATED
I wrote a simple cloud function:

```<code>import * as functions from 'firebase-functions';

export const repeat = functions.https.onCall( function (data, context) {
    // Authentication user information is automatically added to the request.
    if (context.auth) {
        console.log(' context.auth is defined ');
        console.log(' uid is ' + context.auth.uid);
    } else {
        console.log(' context.auth undefine. ');
    }
        if (context.auth) {
            return {
                repeat_message: context.auth.uid + ' ' + data.message,
                repeat_count: data.count + 1,
            };
        } else {
            return {
                repeat_message: ' noUID ' + data.message,
                repeat_count: data.count + 1,
            };
        }    }
);
</code>```

And a corresponding Flutter Client app:

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_functions/cloud_functions.dart';

final FirebaseAuth _fAuth = FirebaseAuth.instance;

final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['email'], signInOption: SignInOption.standard);

FirebaseUser _firebaseUser;
GoogleSignInAccount _googleSignInAccount;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        textTheme: TextTheme(
          caption: TextStyle(
              fontSize: 20.0
          ),
          body1: TextStyle(
              fontSize: 20.0
          ),
        ),
      ),
      title: 'calling function',
      debugShowCheckedModeBanner: false,
      home: LaunchScreen(),
    );
  }
}

class LaunchScreen extends StatefulWidget {
  @override
  _LaunchScreenState createState() {
   return _LaunchScreenState();
  }
} // LoggingOptions  to _LaunchScreenState

class _LaunchScreenState extends State<LaunchScreen> {
  String _response = 'no response';
  int _responseCount = 1;
  final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(functionName: 'repeat')
    ..timeout = const Duration(seconds: 90);

  Future<FirebaseUser> _handleSignIn() async {
    try {
      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      _googleSignInAccount = googleSignInAccount;

      GoogleSignInAuthentication authentication = await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: authentication.accessToken, idToken: authentication.idToken,
      );
      AuthResult authResult;
      authResult = await _fAuth.signInWithCredential( credential);

      _firebaseUser = authResult.user;
      setState(() {});
      return _firebaseUser;
    } catch (e) {
      print(e.toString());
    }
    return null;
  }

  Future<void> _handleSignOut() async {
    FirebaseAuth.instance.signOut();
    _googleSignIn.signOut();

    setState(() {
      _firebaseUser =null;
      _googleSignInAccount= null;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar( title: const Text('Sample Code'),),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              MaterialButton(
                  child: const Text( 'Sign in with Google', style: TextStyle(fontSize: 16.0),),
                  onPressed: () {
                    _handleSignIn().then((user) {
                      // logggedIn
                      debugPrint('user ' + user.toString());
                    }
                        );
                  },
                  ),

                 MaterialButton(
                  child: const Text( 'Sign out with Google', style: TextStyle(fontSize: 16.0),),
                  onPressed: () {
                    _handleSignOut();
                  },
                ),

              Text( _firebaseUser != null ? _firebaseUser.uid : 'user logged off'),

              Text('FromServer $_responseCount: $_response'),
              MaterialButton(
                child: const Text('SEND REQUEST', style: TextStyle(fontSize: 18.0),),
                onPressed: () async {
                  try {
                    final HttpsCallableResult result = await callable.call(
                      <String, dynamic>{
                        'message': 'hello',
                        'count': _responseCount,
                      }
                      ,
                    );
                    print(result.data);
                    setState(() {
                      _response = result.data['repeat_message'];
                      _responseCount = result.data['repeat_count'];
                    });
                  } on CloudFunctionsException catch (e) {
                    print('caught Firebase functions exception');
                    print(e.code);
                    print(e.message);
                    print(e.details);
                  } catch (e) {
                    print('caught generic exception');
                    print(e);
                  }
                },
              ),
            ],
          ),
        ));
  }    }
</code>```

and I can see in both server logs and client side that Auth is passed correctly.

But when I add allAuthenticatedUsers and remove allUsers to 'Cloud Functions Invoker' Role from the function, the App starts getting PlatformException with UNAUTHENTICATED code.

Here is how setting looks before the change:

And after adding allAuthenticatedUsers:

After removing allUsers:

Then when Flutter invokes the function (when the user is logged in), Flutter errors with

PlatformException(functionsError, Cloud function failed with
  exception., {message: UNAUTHENTICATED, details: null, code:
  UNAUTHENTICATED})

It should show an error only when the user is not logged in, but it is showing in either cases.

答:
The cloud configuration for allAuthenticatedUsers is not in any way related to Firebase, and what it does for authentication for callable type functions.  Firebase callable functions handle their own authentication separately from the configuration you changed.  You should change it back if you want callables to work properly.

The allUsers permission that you removed was responsible for making your function accessible to the public, including your app.  When you removed that, you effectively removed the ability for anyone on the internet to be able to invoke the function (which is very much required for callable functions to operate as designed).

When you added allAuthenticatedUsers, what you did was require only callers that authenticate themselves with a Google service account.  Again, this is not related to Firebase or Firebase Auth.  It's a Google Cloud IAM concept.  It's not applicable for callable functions, so you shouldn't use it.  It's not clear to me why you thought this was a good configuration to make.

If you want Firebase callable functions to be invoked normally from apps, you should leave the permission at the default allUsers, and let the Firebase SDK handle the authentication of the end user.

Read more about Google Cloud access control lists to understand the cloud configurations that you were changing.

Body:
I wrote a simple cloud function:

import * as functions from 'firebase-functions';

export const repeat = functions.https.onCall( function (data, context) {
    // Authentication user information is automatically added to the request.
    if (context.auth) {
        console.log(' context.auth is defined ');
        console.log(' uid is ' + context.auth.uid);
    } else {
        console.log(' context.auth undefine. ');
    }
        if (context.auth) {
            return {
                repeat_message: context.auth.uid + ' ' + data.message,
                repeat_count: data.count + 1,
            };
        } else {
            return {
                repeat_message: ' noUID ' + data.message,
                repeat_count: data.count + 1,
            };
        }    }
);

And a corresponding Flutter Client app:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_functions/cloud_functions.dart';

final FirebaseAuth _fAuth = FirebaseAuth.instance;

final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['email'], signInOption: SignInOption.standard);

FirebaseUser _firebaseUser;
GoogleSignInAccount _googleSignInAccount;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        textTheme: TextTheme(
          caption: TextStyle(
              fontSize: 20.0
          ),
          body1: TextStyle(
              fontSize: 20.0
          ),
        ),
      ),
      title: 'calling function',
      debugShowCheckedModeBanner: false,
      home: LaunchScreen(),
    );
  }
}

class LaunchScreen extends StatefulWidget {
  @override
  _LaunchScreenState createState() {
   return _LaunchScreenState();
  }
} // LoggingOptions  to _LaunchScreenState

class _LaunchScreenState extends State<LaunchScreen> {
  String _response = 'no response';
  int _responseCount = 1;
  final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(functionName: 'repeat')
    ..timeout = const Duration(seconds: 90);

  Future<FirebaseUser> _handleSignIn() async {
    try {
      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      _googleSignInAccount = googleSignInAccount;

      GoogleSignInAuthentication authentication = await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: authentication.accessToken, idToken: authentication.idToken,
      );
      AuthResult authResult;
      authResult = await _fAuth.signInWithCredential( credential);

      _firebaseUser = authResult.user;
      setState(() {});
      return _firebaseUser;
    } catch (e) {
      print(e.toString());
    }
    return null;
  }

  Future<void> _handleSignOut() async {
    FirebaseAuth.instance.signOut();
    _googleSignIn.signOut();

    setState(() {
      _firebaseUser =null;
      _googleSignInAccount= null;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar( title: const Text('Sample Code'),),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              MaterialButton(
                  child: const Text( 'Sign in with Google', style: TextStyle(fontSize: 16.0),),
                  onPressed: () {
                    _handleSignIn().then((user) {
                      // logggedIn
                      debugPrint('user ' + user.toString());
                    }
                        );
                  },
                  ),

                 MaterialButton(
                  child: const Text( 'Sign out with Google', style: TextStyle(fontSize: 16.0),),
                  onPressed: () {
                    _handleSignOut();
                  },
                ),

              Text( _firebaseUser != null ? _firebaseUser.uid : 'user logged off'),

              Text('FromServer $_responseCount: $_response'),
              MaterialButton(
                child: const Text('SEND REQUEST', style: TextStyle(fontSize: 18.0),),
                onPressed: () async {
                  try {
                    final HttpsCallableResult result = await callable.call(
                      <String, dynamic>{
                        'message': 'hello',
                        'count': _responseCount,
                      }
                      ,
                    );
                    print(result.data);
                    setState(() {
                      _response = result.data['repeat_message'];
                      _responseCount = result.data['repeat_count'];
                    });
                  } on CloudFunctionsException catch (e) {
                    print('caught Firebase functions exception');
                    print(e.code);
                    print(e.message);
                    print(e.details);
                  } catch (e) {
                    print('caught generic exception');
                    print(e);
                  }
                },
              ),
            ],
          ),
        ));
  }    }

and I can see in both server logs and client side that Auth is passed correctly.

But when I add allAuthenticatedUsers and remove allUsers to 'Cloud Functions Invoker' Role from the function, the App starts getting PlatformException with UNAUTHENTICATED code.

Here is how setting looks before the change:

And after adding allAuthenticatedUsers:

After removing allUsers:

Then when Flutter invokes the function (when the user is logged in), Flutter errors with

PlatformException(functionsError, Cloud function failed with
  exception., {message: UNAUTHENTICATED, details: null, code:
  UNAUTHENTICATED})

It should show an error only when the user is not logged in, but it is showing in either cases.


问:
How to store user input if it was something like a sentence? Or if it was someones name?
Similar to my old question. Is there a way I can store what the user inputs into an array so I can call it via stringName[1] or stringName[2]?
I am not well versed in java split.
 for example, if I had

```<code>System.out.println ("A sentence or your full name please" );
for (int j = 0; j < arrayTwo.length; j++){
array[j]= sc.nextLine();
System.out.println(array[0]);
</code>```

this only prints out the first name

if the user inputs "John Will Smith" and later i want to print out

```<code>System.out.println (+firstName);
System.out.println (+middleName);
System.out.println (+lastName);
</code>```

how do i go about individually updating the array or split it in a way I can grab what the user inputted?

答:
Use of a for loop seems useless here. Read the string as a line and then split it by white space. Check the below code:

```<code>public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("A sentence or your full name please");
    String fullName = scanner.nextLine(); //Read the full name
    String[] nameArray = fullName.split("\\s+"); //Split the full name by white spaces and insert it to array
    for (String name : nameArray) { //Print names in array
        System.out.println(name);
    }
}
</code>```

Body:
Similar to my old question. Is there a way I can store what the user inputs into an array so I can call it via stringName[1] or stringName[2]?
I am not well versed in java split.
 for example, if I had

System.out.println ("A sentence or your full name please" );
for (int j = 0; j < arrayTwo.length; j++){
array[j]= sc.nextLine();
System.out.println(array[0]);

this only prints out the first name

if the user inputs "John Will Smith" and later i want to print out

System.out.println (+firstName);
System.out.println (+middleName);
System.out.println (+lastName);

how do i go about individually updating the array or split it in a way I can grab what the user inputted?

Body:
Use of a for loop seems useless here. Read the string as a line and then split it by white space. Check the below code:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("A sentence or your full name please");
    String fullName = scanner.nextLine(); //Read the full name
    String[] nameArray = fullName.split("\\s+"); //Split the full name by white spaces and insert it to array
    for (String name : nameArray) { //Print names in array
        System.out.println(name);
    }
}


问:
NavigationController is nil on pushing VC (simple project created programmatically)
I created simple project with two ViewControllers (ViewController and SecondVC) programmatically.
In ViewController I've added a button, which push to SecondVC.
In AppDelegate didFinishLaunchingWithOptions I've set ViewController as rootViewController.

ViewController code:

```<code>class ViewController: UIViewController {
   let button = UIButton.init(frame: CGRect(x: 30, y: 30, width: 200, height: 200))

   override func viewDidLoad() {
       super.viewDidLoad()
       view.backgroundColor = .brown
       view.addSubview(button)
       button.backgroundColor = .black
       button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
   }

   @objc func tapped() {
       let vc = SecondVC()
       self.navigationController?.pushViewController(vc, animated: true)
   }
}
</code>```

SecondVC code:

```<code>class SecondVC: UIViewController {

    override func viewDidLoad() {
       view.backgroundColor = .white
    }
}
</code>```

AppDelegate code:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var navigationController: UINavigationController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)

    if let window = window {
        let mainVC = ViewController()
        navigationController = UINavigationController(rootViewController: mainVC)
        window.rootViewController = navigationController
        window.makeKeyAndVisible()
    }

    return true
}
</code>```

In targets deployment info I've removed Main Interface:

When app starts, there is no navigation in my ViewController, so when I tap on button, navigationController is nil, and nothing happens. Cannot find the problem the second day, please help to understand where the problem is.
I use XCode 11.3

sources like these, doesn't help me
Creating a navigationController programmatically (Swift)

答:
Your code works just fine. I copied it and pasted it into a new project and this is what I saw at launch:

I tapped the big black square and we slide to the side and this is what I saw:

My guess as to why it doesn't work for you is that you are using Xcode 11. If so, the issue is that the app delegate is not where the work of launching the app's interface takes place: it's the scene delegate. But you can change that by following the instructions here: https://stackoverflow.com/a/57467270/341994

Body:
I created simple project with two ViewControllers (ViewController and SecondVC) programmatically.
In ViewController I've added a button, which push to SecondVC.
In AppDelegate didFinishLaunchingWithOptions I've set ViewController as rootViewController.

ViewController code:

class ViewController: UIViewController {
   let button = UIButton.init(frame: CGRect(x: 30, y: 30, width: 200, height: 200))

   override func viewDidLoad() {
       super.viewDidLoad()
       view.backgroundColor = .brown
       view.addSubview(button)
       button.backgroundColor = .black
       button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
   }

   @objc func tapped() {
       let vc = SecondVC()
       self.navigationController?.pushViewController(vc, animated: true)
   }
}

SecondVC code:

class SecondVC: UIViewController {

    override func viewDidLoad() {
       view.backgroundColor = .white
    }
}

AppDelegate code:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var navigationController: UINavigationController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)

    if let window = window {
        let mainVC = ViewController()
        navigationController = UINavigationController(rootViewController: mainVC)
        window.rootViewController = navigationController
        window.makeKeyAndVisible()
    }

    return true
}

In targets deployment info I've removed Main Interface:

When app starts, there is no navigation in my ViewController, so when I tap on button, navigationController is nil, and nothing happens. Cannot find the problem the second day, please help to understand where the problem is.
I use XCode 11.3

sources like these, doesn't help me
Creating a navigationController programmatically (Swift)


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
Please note Linq to SQL = dead, Source: http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx

Entity framework is what you should use currently if you want to implement such architecture.

Furthermore if you are using another select query (like GordonB suggests) for your "in" clause it would be better to use "exists" instead of "in" for example:

```<code>select * from tablename where exists (select id from othertablename where fieldtype=1)
</code>```

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

Body:
Please note Linq to SQL = dead, Source: http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx

Entity framework is what you should use currently if you want to implement such architecture.

Furthermore if you are using another select query (like GordonB suggests) for your "in" clause it would be better to use "exists" instead of "in" for example:

select * from tablename where exists (select id from othertablename where fieldtype=1)

OwnerDisplayName: Roel Snetselaar


问:
How to integrate database search with pdf search in a web app?
I've a jsp web application with a custom search engine.

The search engine is basically build on top of a 'documents' table of a SQL Server database.

To exemplify, each document record has three fields:

document id

'descripion' (text field)

'attachment', a path of a pdf file in the filesystem.

The search engine actually searches keywords in description field and returns a result list in an HTML page. Now I want to search keywords even in the pdf file content.

I'm investigating about Lucene, Tika, Solr, but I don't understand how I can use these frameworks for my goal.

One possible solution: using Tika to extract pdf content and store in a new document table field, so I can write SQL queries on this field.

Are there better alternatives?
Can I use Solr/Lucene indexing features as an integration of SQL-based search engine and not as a totally substitute of it?

Thanks

答:
I would consider Lucene to be completely independent of an SQL Database, i.e. you will not use SQL/jdbc/whatever DB to query Lucene, but its own API and its own data store.

You could of course use Tika to extract the full text of a pdf, store it, and use whatever your SQL DB provides re. fulltext search capacity.

If you are using Hibernate, Hibernate Search is a fantastic product which integrates both an SQL store and Lucene. But you would have to go the Hibernate/JPA way, which might be overkill for your project.

ContentLicense: CC BY-SA 3.0


问:
Unable to get result on multiple databases (SQL-Tools)
I have to get mixed result from the databases but this code is raising an error:

from sql_tools import sqlite

sqlite.connect(["main.db", "base.sqlite3"])
data = sqlite.execute(["SELECT * FROM PREFERENCES", "SELECT * FROM USERS"]).get
sqlite.disconnect()
```

<p>Error:</p>

```Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\sqlite\execute.py", line 28, in execute
    obj.execute()
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\internals.py", line 188, in execute
    self.__command = self.__parseCommands()
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\internals.py", line 270, in __parseCommands
    raise e
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\internals.py", line 260, in __parseCommands
    raise exception.UnknownError(
sql_tools.exception.UnknownError: Database and commands are not commuting, n(commands) != n(database)
```

Can anybody tell me how to solve this?

答:
It's because when you connect multiple databases, the execute function expects you to pass the commands as lists of list where each element of list is the list of commands to be executed on each database. You can read more at documentation.

Corrected Code:

from sql_tools import sqlite

sqlite.connect(["main.db", "base.sqlite3"])
data = sqlite.execute([["SELECT * FROM PREFERENCES"], ["SELECT * FROM USERS"]]).get
sqlite.disconnect()
```

Body:
I have to get mixed result from the databases but this code is raising an error:

from sql_tools import sqlite

sqlite.connect(["main.db", "base.sqlite3"])
data = sqlite.execute(["SELECT * FROM PREFERENCES", "SELECT * FROM USERS"]).get
sqlite.disconnect()

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\sqlite\execute.py", line 28, in execute
    obj.execute()
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\internals.py", line 188, in execute
    self.__command = self.__parseCommands()
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\internals.py", line 270, in __parseCommands
    raise e
  File "C:\Users\Hunny\AppData\Local\Programs\Python\Python38\lib\site-packages\sql_tools\internals.py", line 260, in __parseCommands
    raise exception.UnknownError(
sql_tools.exception.UnknownError: Database and commands are not commuting, n(commands) != n(database)

Can anybody tell me how to solve this?


问:
How to get the respective value from a multiple column based on the given value in mysql
I have a table in mysql as follows

```
id  slab1     slab2     slab3
1   200-500   600-800   900-100
```

my given value for search is 250

how to find the corresponding column value, based on the given no. in mysql

My expected output will be is 200-500

答:
This query will give you the column name and range for a given search value (in this case 250):

```<code>SELECT slab_num, slab
FROM (
  SELECT 'slab1' AS slab_num, slab1 AS slab,
         SUBSTRING_INDEX(slab1, '-', 1) AS low,
         SUBSTRING_INDEX(slab1, '-', -1) AS high
  FROM slabs
  UNION ALL
  SELECT 'slab2', slab2,
         SUBSTRING_INDEX(slab2, '-', 1),
         SUBSTRING_INDEX(slab2, '-', -1)
  FROM slabs
  UNION ALL
  SELECT 'slab3', slab3,
         SUBSTRING_INDEX(slab3, '-', 1),
         SUBSTRING_INDEX(slab3, '-', -1)
  FROM slabs
) s
WHERE 250 BETWEEN low AND high
</code>```

Output

```<code>slab_num    slab
slab1       200-500
</code>```

Demo on SQLFiddle

Body:
I have a table in mysql as follows

id  slab1     slab2     slab3
1   200-500   600-800   900-100

my given value for search is 250

how to find the corresponding column value, based on the given no. in mysql

My expected output will be is 200-500

Body:
This query will give you the column name and range for a given search value (in this case 250):

SELECT slab_num, slab
FROM (
  SELECT 'slab1' AS slab_num, slab1 AS slab,
         SUBSTRING_INDEX(slab1, '-', 1) AS low,
         SUBSTRING_INDEX(slab1, '-', -1) AS high
  FROM slabs
  UNION ALL
  SELECT 'slab2', slab2,
         SUBSTRING_INDEX(slab2, '-', 1),
         SUBSTRING_INDEX(slab2, '-', -1)
  FROM slabs
  UNION ALL
  SELECT 'slab3', slab3,
         SUBSTRING_INDEX(slab3, '-', 1),
         SUBSTRING_INDEX(slab3, '-', -1)
  FROM slabs
) s
WHERE 250 BETWEEN low AND high

Output

slab_num    slab
slab1       200-500

Demo on SQLFiddle


问:
How to insert href URL to Javascript var?
I am trying to create a script for autoreply in google apps and would love to have that reply to have some formatting. I've been getting a syntax error due to the quotes closing with the opening of the href tag. Is there a way to insert the URL into the html message? My scribbles below.

function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var message = "We are out of the office until Monday morning and will reply to your email then. If you are having an emergency, please text (800) 590-2508, we'll do our best to reply as soon as possible.";
  var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([6,0].indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply(message, {htmlBody: htmlMessage});
      threads[i].markRead();
      threads[i].star();
      }
    }
  }
}```
</div>
</div>
</p>

<p>The error is on line 4</p>

``` var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";
```

The quotes after htmlMessage = open the message, and the quotes after the first href= close it, so the rest of the message breaks the syntax.

Any insight on how to include the whole html under the var statement?

Thanks!

答:
add \ before "

 var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";```

another method is to replace " with ' inside the string

Body:
I am trying to create a script for autoreply in google apps and would love to have that reply to have some formatting. I've been getting a syntax error due to the quotes closing with the opening of the href tag. Is there a way to insert the URL into the html message? My scribbles below.

function autoReply() {
var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var message = "We are out of the office until Monday morning and will reply to your email then. If you are having an emergency, please text (800) 590-2508, we'll do our best to reply as soon as possible.";
  var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";
  var date = new Date();
  var day = date.getDay();
  var hour = date.getHours();
  if ([6,0].indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].isUnread()){
      threads[i].reply(message, {htmlBody: htmlMessage});
      threads[i].markRead();
      threads[i].star();
      }
    }
  }
}

The error is on line 4

 var htmlMessage = "
Hi,

Thanks for your message.

We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:

Link text

Link text

If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.

Have a pleasant weekend,

My Signature
";

The quotes after htmlMessage = open the message, and the quotes after the first href= close it, so the rest of the message breaks the syntax.

Any insight on how to include the whole html under the var statement?

Thanks!

Body:
add \ before "

 var htmlMessage = "<p>Hi,</p><p>Thanks for your message.</p><p>We are out of the office until Monday morning and will reply to your email then. In the meantime, check out some helpful resources:</p><p><a href=\"https://sampleurl.com\" target=\"_blank\" rel=\"noopener\">Link text</a></p><p><a href=\"https://anothersammple.com\" target=\"_blank\" rel=\"noopener\">Link text</a></p><p>If you are having an emergency, please text (800) 000-0000, we'll do our best to get back to you as soon as possible.</p><p>Have a pleasant weekend,</p><p>My Signature</p>";

another method is to replace " with ' inside the string


问:
go build can't find a revision
I developed a repo on computer A and created a go.mod/go.sum that I checked in.

I pull that repo with the go.mod/go.sum files on computer B, but when I try to build the program, the module constraints can't be satisfied.

```<code>$ go build
go: finding github.ibm.com/kms/key-protect-client v0.1.5
go: finding golang.org/x/tools v0.0.0-20180221164845-07fd8470d635
go: github.ibm.com/kms/key-protect-client@v0.1.5: unknown revision v0.1.5
go: error loading module requirements
</code>```

The repo that is failing is a private repo, and for some reason it doesn't get downloaded to the module cache. On another computer, the dependencies are downloaded and the build succeeds. I am building another private repo in that same domain, so I know that my github credentials give me access to these repos. But for some reason, the go module system can't get to the dependent repo.

I cannot find more information how to debug this.

答:
Possible solutions for golang unknown revision if you are using private repository:

git config --global url."ssh://git@yourserver".insteadOf "https://yourserver"

Check your git repository permissions

Title: go build can't find a revision

Body:
I developed a repo on computer A and created a go.mod/go.sum that I checked in.

I pull that repo with the go.mod/go.sum files on computer B, but when I try to build the program, the module constraints can't be satisfied.

$ go build
go: finding github.ibm.com/kms/key-protect-client v0.1.5
go: finding golang.org/x/tools v0.0.0-20180221164845-07fd8470d635
go: github.ibm.com/kms/key-protect-client@v0.1.5: unknown revision v0.1.5
go: error loading module requirements

The repo that is failing is a private repo, and for some reason it doesn't get downloaded to the module cache. On another computer, the dependencies are downloaded and the build succeeds. I am building another private repo in that same domain, so I know that my github credentials give me access to these repos. But for some reason, the go module system can't get to the dependent repo.

I cannot find more information how to debug this.


问:
How to make EditText ediable but disable no keyboard?
I made a calculator. Its working fine. I want to have touch focus in edittext but the problem is when i touch it the keyboard popup. How to disable keyboard?

Screenshot of Calculator

```<code><EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="bottom|end"
    android:textSize="40sp"
    android:enabled="true"
    android:singleLine="true"
    android:textIsSelectable="true"
    android:scrollHorizontally="true"
    android:id="@+id/tvExpression_ID"/>
</code>```

答:
I had the same issue before and this solution works for me

```<code> <EditText
    android:focusableInTouchMode="true"
    android:cursorVisible="false"
    android:focusable="false"  />
</code>```

Regards!

Body:
I made a calculator. Its working fine. I want to have touch focus in edittext but the problem is when i touch it the keyboard popup. How to disable keyboard?

Screenshot of Calculator

<EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="bottom|end"
    android:textSize="40sp"
    android:enabled="true"
    android:singleLine="true"
    android:textIsSelectable="true"
    android:scrollHorizontally="true"
    android:id="@+id/tvExpression_ID"/>

Body:
I had the same issue before and this solution works for me

 <EditText
    android:focusableInTouchMode="true"
    android:cursorVisible="false"
    android:focusable="false"  />

Regards!


问:
Issue making model pop up onPress of flatlist
I have a flatlist of cards, and I want a modal to appear when someone presses the card. Pressing the card doesn't seem to do anything though, so I'm wondering what I've done wrong. In my code at the top I have defined the state for the visibility of the modal, if you scroll down to the card you'll see onPress changes the state. Below the card is the actual modal which uses the state of the visible property to display it or not.

Code:

```<code>class HomeScreen extends React.Component {

  state = {
    isModalVisible: false
  };

  toggleModal = () => {
    this.setState({ isModalVisible: !this.state.isModalVisible });
  };

  render() {
    return (
      <View style = {{flex:1}}>
        <Header
          centerComponent={{ text: 'MY MACROS', style: { color: '#fff', letterSpacing: 2} }}
          containerStyle={{
            backgroundColor: '#5BC0EB',
          }}
        />
        <Progress.Bar progress={0.7} width={null} height={10} borderRadius = {0} color = {'lightgreen'}/>
        <ScrollView>
          <FlatList
            data = {Macros}
            renderItem = {({ item }) => (
              <TouchableOpacity>
                  <Card style = {{justifyContent: 'center', margin: 1, backgroundColor: '#ffff', borderRadius: 25}} onPress = {() => {this.toggleModal}}>
                    <Card.Content>
                      <View style = {{flexDirection: 'row', justifyContent: 'space-between'}}>
                        <View style = {{flexDirection: 'column', justifyContent: 'space-between'}}>
                          <Title style = {{paddingTop: 20, fontSize: 35, fontWeight: 'bold',color: 'black', letterSpacing: 2}}>{item.total} {item.unit}</Title>
                          <Text style= {{fontSize: 30, color: 'black', letterSpacing: 2, fontWeight: '100'}}>{item.title}</Text>
                        </View>
                        <MainProgress/>
                      </View>
                    </Card.Content>
                    <Card.Actions>
                    </Card.Actions>
                  </Card>

                  <Modal isVisible = {this.state.isModalVisible}>
                    <View>
                      <Text>Test</Text>
                      <Button title = "Cancel" onPress = {this.toggleModal}/>
                    </View>
                  </Modal>

              </TouchableOpacity>
            )}
            keyExtractor = {item => item.key}
          />
        </ScrollView>
       <Button color = {'#5BC0EB'} onPress={popUpForm}>Add New Macro</Button>
      </View>
    );
  }
}
</code>```

答:
According to your code, you need to pass your toggleModal function to TouchableOpacity in order to display your Model. Check below sample for more information.

```<code>import React, { Component } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, TouchableOpacity, Modal, Button } from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

export default class App extends Component {
  state = {
    isModalVisible: false
  }

  toggleModal = () => {
    this.setState({
      isModalVisible: !this.state.isModalVisible
    });
  };

  renderItem = ({ item }) => (
    <TouchableOpacity style={styles.item} onPress={this.toggleModal}>
      <Text style={styles.title}>{item.title}</Text>
    </TouchableOpacity>
  )

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <FlatList
          data={DATA}
          renderItem={this.renderItem}
          keyExtractor={item => item.id}
        />
        {
          this.state.isModalVisible &&
          <Modal
            visible={this.state.isModalVisible}
            transparent={true}
            animationType='slide'
            onRequestClose={this.toggleModal}
          >
            <View style={styles.modelStyle}>
              <View style={styles.modelWrapperStyle}>
                <Text>Test</Text>
                <Button title="Cancel" onPress={this.toggleModal} />
              </View>
            </View>
          </Modal>
        }
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
  modelStyle: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)'
  },
  modelWrapperStyle: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ffffff',
    padding: 20,
    width: '90%'
  }
});
</code>```

Change this according to your requirement.

Hope this helps you. Feel free for doubts.

Body:
I have a flatlist of cards, and I want a modal to appear when someone presses the card. Pressing the card doesn't seem to do anything though, so I'm wondering what I've done wrong. In my code at the top I have defined the state for the visibility of the modal, if you scroll down to the card you'll see onPress changes the state. Below the card is the actual modal which uses the state of the visible property to display it or not.

Code:

class HomeScreen extends React.Component {

  state = {
    isModalVisible: false
  };

  toggleModal = () => {
    this.setState({ isModalVisible: !this.state.isModalVisible });
  };

  render() {
    return (
      <View style = {{flex:1}}>

        <Progress.Bar progress={0.7} width={null} height={10} borderRadius = {0} color = {'lightgreen'}/>
        <ScrollView>
          <FlatList
            data = {Macros}
            renderItem = {({ item }) => (
              <TouchableOpacity>
                  <Card style = {{justifyContent: 'center', margin: 1, backgroundColor: '#ffff', borderRadius: 25}} onPress = {() => {this.toggleModal}}>
                    <Card.Content>
                      <View style = {{flexDirection: 'row', justifyContent: 'space-between'}}>
                        <View style = {{flexDirection: 'column', justifyContent: 'space-between'}}>
                          <Title style = {{paddingTop: 20, fontSize: 35, fontWeight: 'bold',color: 'black', letterSpacing: 2}}>{item.total} {item.unit}</Title>
                          <Text style= {{fontSize: 30, color: 'black', letterSpacing: 2, fontWeight: '100'}}>{item.title}</Text>
                        </View>
                        <MainProgress/>
                      </View>
                    </Card.Content>
                    <Card.Actions>
                    </Card.Actions>
                  </Card>

                  <Modal isVisible = {this.state.isModalVisible}>
                    <View>
                      <Text>Test</Text>
                      <Button title = "Cancel" onPress = {this.toggleModal}/>
                    </View>
                  </Modal>

              </TouchableOpacity>
            )}
            keyExtractor = {item => item.key}
          />
        </ScrollView>
       <Button color = {'#5BC0EB'} onPress={popUpForm}>Add New Macro</Button>
      </View>
    );
  }
}

Body:
According to your code, you need to pass your toggleModal function to TouchableOpacity in order to display your Model. Check below sample for more information.

import React, { Component } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, TouchableOpacity, Modal, Button } from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

export default class App extends Component {
  state = {
    isModalVisible: false
  }

  toggleModal = () => {
    this.setState({
      isModalVisible: !this.state.isModalVisible
    });
  };

  renderItem = ({ item }) => (
    <TouchableOpacity style={styles.item} onPress={this.toggleModal}>
      <Text style={styles.title}>{item.title}</Text>
    </TouchableOpacity>
  )

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <FlatList
          data={DATA}
          renderItem={this.renderItem}
          keyExtractor={item => item.id}
        />
        {
          this.state.isModalVisible &&
          <Modal
            visible={this.state.isModalVisible}
            transparent={true}
            animationType='slide'
            onRequestClose={this.toggleModal}
          >
            <View style={styles.modelStyle}>
              <View style={styles.modelWrapperStyle}>
                <Text>Test</Text>
                <Button title="Cancel" onPress={this.toggleModal} />
              </View>
            </View>
          </Modal>
        }
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
  modelStyle: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)'
  },
  modelWrapperStyle: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ffffff',
    padding: 20,
    width: '90%'
  }
});

Change this according to your requirement.

Hope this helps you. Feel free for doubts.


问:
Git push gives an error after loading repo and making some changes in the project
I did git init + git pull to load my repository. Git haven't asked me about any auth despite this repo is private (I earlier used it and connected to this repo so maybe this is the reason). So then I made some changes in this local project and after that I tried git push. This caused an error:

```<code>fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

    git remote add <name> <url>

and then push using the remote name

    git push <name>
</code>```

This one looks like a popular error in the internet but people have it when they really don't have connection to the repo so they have to connect. But in my case I firstly did git pull so I'd have it.

答:
I would start by checking two things:

Do you have a remote setted ?

The given error message seem to indicated that no remote are setted. So if you try to run git remote -vv, it should give you a result as:

```<code>origin  url-to-your-repository.git (fetch)
origin  url-to-your-repository.git (push)
</code>```

If not, please add a remote with git remote add.
If you do have a remote specified, please verify that you do have the authorization to push on the remote. Sometime, private repository allow pulling codebase, but restrict pushing.

If you are sure that you have all authorization, you should check if you have a remote branch specified for your local branch with git branch -vv:

```<code>* feature-name 51ff531 [origin/remote-feature-name] Commit message
</code>```

Here in my example, my local branch feature-name is linked to my origin remote branch named remote-feature-name (specified in []).
Depending on your git configuration, git push command could need you to specify a remote and a branch name such as git push origin feature-name.

Body:
I did git init + git pull to load my repository. Git haven't asked me about any auth despite this repo is private (I earlier used it and connected to this repo so maybe this is the reason). So then I made some changes in this local project and after that I tried git push. This caused an error:

fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

    git remote add <name> <url>

and then push using the remote name

    git push <name>

This one looks like a popular error in the internet but people have it when they really don't have connection to the repo so they have to connect. But in my case I firstly did git pull so I'd have it.

Body:
I would start by checking two things:

Do you have a remote setted ?

The given error message seem to indicated that no remote are setted. So if you try to run git remote -vv, it should give you a result as:

origin  url-to-your-repository.git (fetch)
origin  url-to-your-repository.git (push)

If not, please add a remote with git remote add.
If you do have a remote specified, please verify that you do have the authorization to push on the remote. Sometime, private repository allow pulling codebase, but restrict pushing.

If you are sure that you have all authorization, you should check if you have a remote branch specified for your local branch with git branch -vv:

* feature-name 51ff531 [origin/remote-feature-name] Commit message

Here in my example, my local branch feature-name is linked to my origin remote branch named remote-feature-name (specified in []).
Depending on your git configuration, git push command could need you to specify a remote and a branch name such as git push origin feature-name.


问:
How to make sure only clean URL is used all the time?
Assuming my site will do something if the URL looks like this mysite.com/index.php?myparam=test

In .htaccess, I added the following line:

```<code>#RewriteRule ^([a-z]+)$ /index.php?myparam=$1 [L]
</code>```

Which works great! URL mysite.com/test will redirect accordingly and everything works

I would like to get rid of the dirty URL so that if someone keys in manually mysite.com/index.php?myparam=test he will be redirected to mysite.com/test and still works, without going into an infinite loop..

答:
If you get the idea of "routing" where you have the mechanism translating parameters to URL and get the execution parameters from entered URL, if someone enters execution parameters manually, you redirect him to the URL you get from routing mechanism.

Some information about routing mechanism in symfony 1.4 framework:

http://www.symfony-project.org/jobeet/1_4/Doctrine/en/05

I've wrote a routing mechanism for my university project in a couple of hours, so it is possible to have one. If not, the most popular [IMHO] routing library is Horde:

http://dev.horde.org/routes/

Body:
Assuming my site will do something if the URL looks like this mysite.com/index.php?myparam=test

In .htaccess, I added the following line:

#RewriteRule ^([a-z]+)$ /index.php?myparam=$1 [L]

Which works great! URL mysite.com/test will redirect accordingly and everything works

I would like to get rid of the dirty URL so that if someone keys in manually mysite.com/index.php?myparam=test he will be redirected to mysite.com/test and still works, without going into an infinite loop..


问:
In DolphinDB， How to add a new column of DATETIME type that combines time and date
In DolphinDB， I have a table with a column of DATE type and a column of TIME type, How to add a  new column of DATETIME type that combines time and date.</p>

```<code>t = table(2020.02.01..2020.02.10 as date, 11:12:55.000..11:12:55.009 as time, 1..10 as num)
</code>```

答:
Please use concatDateTime to combine date and time

```<code>update t set datetime = concatDateTime(date, time)
</code>```

Body:
In DolphinDB， I have a table with a column of DATE type and a column of TIME type, How to add a  new column of DATETIME type that combines time and date.

t = table(2020.02.01..2020.02.10 as date, 11:12:55.000..11:12:55.009 as time, 1..10 as num)

Body:
Please use concatDateTime to combine date and time

update t set datetime = concatDateTime(date, time)


问:
Display Images from file in R Jupyter notebook
I have an image on disk and want to display it in a markdown cell in an R Jupyter Notebook. How can I go about this?

I know with Python this as simple as importing the Image class from display.

答:
Here is code for the Jupyter R Kernel Notebook User to select choose an image file (.PNG) from the file system, strip off the full pathname, and then insert the image into the cell below this code.  </p>

```<code>image_chosen = choose.files(
               default = "",
               caption = "Select The Image File (in PNG format) to Insert",
               multi = TRUE, filters = Filters,
               index = nrow(Filters)
               )

chosen_image_name = basename(image_chosen)
#chosen_image_name   # uncomment this line to show the location of the image.

IRdisplay::display_png(file = chosen_image_name)    # This line inserts the image.
</code>```

<p>Then use the standard Jupyter Notebook extension "Hide Input" to hide this codecell, and the "Freeze" NBextension to freeze the codecell so the image stays frozen and the notebook does not try to select and insert a new image everytime the notebook code runs. </p>

Body:
Here is code for the Jupyter R Kernel Notebook User to select choose an image file (.PNG) from the file system, strip off the full pathname, and then insert the image into the cell below this code.

image_chosen = choose.files(
               default = "",
               caption = "Select The Image File (in PNG format) to Insert",
               multi = TRUE, filters = Filters,
               index = nrow(Filters)
               )

chosen_image_name = basename(image_chosen)
#chosen_image_name   # uncomment this line to show the location of the image.

IRdisplay::display_png(file = chosen_image_name)    # This line inserts the image.

Then use the standard Jupyter Notebook extension "Hide Input" to hide this codecell, and the "Freeze" NBextension to freeze the codecell so the image stays frozen and the notebook does not try to select and insert a new image everytime the notebook code runs.