问:
same vendor code from multiple packages
I'm trying to use grpc "google.golang.org/grpc" package.

```<code>import (
    "github.com/xxxx/yyyy"
    "google.golang.org/grpc"
)

conn, err := grpc.Dial(address)
pppp.NewXXXXClient(conn) // where pppp is from github.com/xxxx/yyyy
</code>```

What happens if github.com/xxxx/yyyy also vendors the same grpc package?
I am getting a compilation error like below

```<code>cannot use conn (type *"google.golang.org/grpc".ClientConn) as type
*"github.com/xxxx/yyyy/vendor/google.golang.org/grpc".ClientConn
</code>```

How can I get around this?

答: I think, you must vendor every dependency of your project (if necessary - include Go std library too), or you shouldn't use vendoring at all. There's no third choise.

Title: same vendor code from multiple packages

Body:
I'm trying to use grpc "google.golang.org/grpc" package.

import (
    "github.com/xxxx/yyyy"
    "google.golang.org/grpc"
)

conn, err := grpc.Dial(address)
pppp.NewXXXXClient(conn) // where pppp is from github.com/xxxx/yyyy

What happens if github.com/xxxx/yyyy also vendors the same grpc package?
I am getting a compilation error like below

cannot use conn (type *"google.golang.org/grpc".ClientConn) as type
*"github.com/xxxx/yyyy/vendor/google.golang.org/grpc".ClientConn

How can I get around this?


来源: stackexchange

问:
Rename and increment on duplicate
I have a series of image files with filename formats as follows.

```<code>9407-C-9406-B-038.jpg
9407-C-9406-B-118.jpg
9422-AC-012.jpg
9422-AC-112.jpg
9422-BD-043.jpg
9422-BD-Still-001.jpg
9405_M.jpg
9792A.jpg
9792B.jpg
</code>```

The relevant portion for my purpose is the first 4 characters, the rest is irrelevant.

I'd like to rename the files such that the leading 4 char string is retained, the extension is retained, but the rest is incremented when a duplicate is encountered :
e.g :

```<code>9422-AC-012.jpg becomes 942200.jpg
9422-AC-112.jpg becomes 942201.jpg
9422-BD-043.jpg becomes 942202.jpg
9422-BD-Still-001.jpg becomes 942203.jpg
9405_M.jpg becomes 940500.jpg
9792A.jpg becomes 979200.jpg
9792B.jpg becomes 979201.jpg
</code>```

Using 'rename' I can strip the string after the first 4 chars, and I can increment in totality, which results with the incremental portion of the filename ending up in the thousands.

rename -n  -N 0001 's/(?<=.{4}).*/$N.jpg/' *.jpg

Can anyone suggest a way to strip the filename after the first 4 chars, rename the file, and increment only when a duplicate is encountered?

答:
awk to the rescue!

With the filenames listed in file

```<code>$ while read f t;
  do
     echo "mv $f $t";
  done < <(awk -F\. '{k=substr($0,1,4); printf "%s\t%s%04d.%s\n", $0,k,a[k]++,$NF}' file)

mv 9407-C-9406-B-038.jpg 94070000.jpg
mv 9407-C-9406-B-118.jpg 94070001.jpg
mv 9422-AC-012.jpg 94220000.jpg
mv 9422-AC-112.jpg 94220001.jpg
mv 9422-BD-043.jpg 94220002.jpg
mv 9422-BD-Still-001.jpg 94220003.jpg
mv 9405_M.jpg 94050000.jpg
mv 9792A.jpg 97920000.jpg
mv 9792B.jpg 97920001.jpg
</code>```

remove echo for the actual renaming, assumes no white space in the file name, at least 4 chars long and has extension.

the example shows two digit counter, you mentioned the counter to be in the thousands, here it's controlled by the print format %04d, change 4 to 2 if you don't expect more than 100.  Regardless, the counter will create unique file but may extend from the allocated number of digits (e.g. it will generate 00,01,..99, and for the next one will be 100.)

ContentLicense: CC BY-SA 3.0

Title: Rename and increment on duplicate

Body:
I have a series of image files with filename formats as follows.

9407-C-9406-B-038.jpg
9407-C-9406-B-118.jpg
9422-AC-012.jpg
9422-AC-112.jpg
9422-BD-043.jpg
9422-BD-Still-001.jpg
9405_M.jpg
9792A.jpg
9792B.jpg

The relevant portion for my purpose is the first 4 characters, the rest is irrelevant.

I'd like to rename the files such that the leading 4 char string is retained, the extension is retained, but the rest is incremented when a duplicate is encountered :
e.g :

9422-AC-012.jpg becomes 942200.jpg
9422-AC-112.jpg becomes 942201.jpg
9422-BD-043.jpg becomes 942202.jpg
9422-BD-Still-001.jpg becomes 942203.jpg
9405_M.jpg becomes 940500.jpg
9792A.jpg becomes 979200.jpg
9792B.jpg becomes 979201.jpg

Using 'rename' I can strip the string after the first 4 chars, and I can increment in totality, which results with the incremental portion of the filename ending up in the thousands.

rename -n  -N 0001 's/(?<=.{4}).*/$N.jpg/' *.jpg

Can anyone suggest a way to strip the filename after the first 4 chars, rename the file, and increment only when a duplicate is encountered?

Body:
awk to the rescue!

With the filenames listed in file

$ while read f t;
  do
     echo "mv $f $t";
  done < <(awk -F\. '{k=substr($0,1,4); printf "%s\t%s%04d.%s\n", $0,k,a[k]++,$NF}' file)

mv 9407-C-9406-B-038.jpg 94070000.jpg
mv 9407-C-9406-B-118.jpg 94070001.jpg
mv 9422-AC-012.jpg 94220000.jpg
mv 9422-AC-112.jpg 94220001.jpg
mv 9422-BD-043.jpg 94220002.jpg
mv 9422-BD-Still-001.jpg 94220003.jpg
mv 9405_M.jpg 94050000.jpg
mv 9792A.jpg 97920000.jpg
mv 9792B.jpg 97920001.jpg

remove echo for the actual renaming, assumes no white space in the file name, at least 4 chars long and has extension.

the example shows two digit counter, you mentioned the counter to be in the thousands, here it's controlled by the print format %04d, change 4 to 2 if you don't expect more than 100.  Regardless, the counter will create unique file but may extend from the allocated number of digits (e.g. it will generate 00,01,..99, and for the next one will be 100.)


问:
What is the difference between mocking and spying when using Mockito?
What would be a use case for a use of a Mockito spy?

It seems to me that every spy  use case can be handled with a mock, using callRealMethod.

One difference I can see is if you want most method calls to be real, it saves some lines of code to use a mock vs. a spy. Is that it or am I missing the bigger picture?

答:
Spy can be useful when you want to create unit tests for legacy code.

I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.

If you have something like this code:

```<code>public void transfer(  DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService,
             double amount, String fromAccount, String toAccount){
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}
</code>```

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some, legacy code, dependency is in the code like this:

```<code>    public void transfer(String fromAccount, String toAccount, double amount){

        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
</code>```

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

```<code>    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }
</code>```

Then you can use the spy the inject the dependency like this:

```<code>DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target).proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target).proxyWithdrawMoneyServiceCreator();
</code>```

More detail in the link above.

Body:
Spy can be useful when you want to create unit tests for legacy code.

I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.

If you have something like this code:

public void transfer(  DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService,
             double amount, String fromAccount, String toAccount){
    withdrawMoneyService.withdraw(fromAccount,amount);
    depositMoneyService.deposit(toAccount,amount);
}

You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.

But with some, legacy code, dependency is in the code like this:

    public void transfer(String fromAccount, String toAccount, double amount){

        this.depositeMoneyService = new DepositMoneyService();
        this.withdrawMoneyService = new WithdrawMoneyService();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }

Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.

Alternative is that you can extract the dependency out like this:

    public void transfer(String fromAccount, String toAccount, double amount){
        this.depositeMoneyService = proxyDepositMoneyServiceCreator();
        this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();

        withdrawMoneyService.withdraw(fromAccount,amount);
        depositeMoneyService.deposit(toAccount,amount);
    }
    DepositMoneyService proxyDepositMoneyServiceCreator() {
        return new DepositMoneyService();
    }

    WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
        return new WithdrawMoneyService();
    }

Then you can use the spy the inject the dependency like this:

DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
        WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);

    TransferMoneyService target = spy(new TransferMoneyService());

    doReturn(mockDepositMoneyService)
            .when(target).proxyDepositMoneyServiceCreator();

    doReturn(mockWithdrawMoneyService)
            .when(target).proxyWithdrawMoneyServiceCreator();

More detail in the link above.


问:
How to find third or nᵗʰ maximum salary from salary table?
How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary) in optimized way?

答:
```<code>select
    Min(salary)
from ( select salary from employees order by salary desc) t
where rownum<=3;
</code>```

For 2nd highest salary,Change 3 to 2 in above query and for Nth highest salary to N where N = 1,2,3,4....

ContentLicense: CC BY-SA 4.0

Body:
select
    Min(salary)
from ( select salary from employees order by salary desc) t
where rownum<=3;

For 2nd highest salary,Change 3 to 2 in above query and for Nth highest salary to N where N = 1,2,3,4....


问:
'System.Windows.Baml2006.TypeConverterMarkupExtension' exception
I am using this to display a gif in my app:

```<code><Image Height="30" Width="30" gif:ImageBehavior.AnimatedSource="pack://application:,,,/OffPo diagnostic tool;component/resources/c1.gif" Grid.Column="1" Margin="394,110,42,22" Grid.Row="1" />
</code>```

And it throws me this error :

Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.

My resource path is okay, even it shows the image in design time but fails to compile... What's wrong ?

SEMI-FIX

I used the exact path as the source:

```<code>C:\Users\nabil\Documents\Visual Studio 2015\Projects\OffPo Diagnostic Tool\OffPo Diagnostic Tool\resources\c1.gif
</code>```

This fixed the problem but what if I move my application? Then the problem would occur again. Any permanent fix?

THIS IS WHAT I FOUND WHEN I TRIED INNEREXCEPTION

答:
Fixed it myself...Or should i say SO saved my day again ??

Source

All i had to do is, select the image from the Solution explorer>Properties>Build action>changed 'None' to 'Resources'

Body:
I am using this to display a gif in my app:

<Image Height="30" Width="30" gif:ImageBehavior.AnimatedSource="pack://application:,,,/OffPo diagnostic tool;component/resources/c1.gif" Grid.Column="1" Margin="394,110,42,22" Grid.Row="1" />

And it throws me this error :

Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.

My resource path is okay, even it shows the image in design time but fails to compile... What's wrong ?

SEMI-FIX

I used the exact path as the source:

C:\Users\nabil\Documents\Visual Studio 2015\Projects\OffPo Diagnostic Tool\OffPo Diagnostic Tool\resources\c1.gif

This fixed the problem but what if I move my application? Then the problem would occur again. Any permanent fix?

THIS IS WHAT I FOUND WHEN I TRIED INNEREXCEPTION


问:
How do I create a link using JavaScript?
I have a string for a title and a string for a link.  I'm not sure how to put the two together to create a link on a page using JavaScript.  Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs.  I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

答:
With JavaScript

```<code>var a = document.createElement('a');
a.setAttribute('href',desiredLink);
a.innerHTML = desiredText;
// apend the anchor to the body
// of course you can append it almost to any other dom element
document.getElementsByTagName('body')[0].appendChild(a);
</code>```

```<code>document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
</code>```

or, as suggested by @travis :

```<code>document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
</code>```

```<code><script type="text/javascript">
//note that this case can be used only inside the "body" element
document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
</script>
</code>```

With JQuery

```<code>$('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
</code>```

```<code>$('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
</code>```

```<code>var a = $('<a />');
a.attr('href',desiredLink);
a.text(desiredText);
$('body').append(a);
</code>```

In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.

Body:
With JavaScript

var a = document.createElement('a');
a.setAttribute('href',desiredLink);
a.innerHTML = desiredText;
// apend the anchor to the body
// of course you can append it almost to any other dom element
document.getElementsByTagName('body')[0].appendChild(a);

document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';

or, as suggested by @travis :

document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);

<script type="text/javascript">
//note that this case can be used only inside the "body" element
document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
</script>

With JQuery

$('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));

$('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));

var a = $('<a />');
a.attr('href',desiredLink);
a.text(desiredText);
$('body').append(a);

In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.


问:
scroll to next element with same parent class
I have several divs with the class name "fullcontent".
In each div I have 2 elements: "fullcontent--prev" and "fullcontent--next".
On click on this elements I want to scroll to the next/previous fullcontent-div.

But I don't get this working with this:

https://jsfiddle.net/whgxauyd/1/

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});
```

<pre class="lang-css prettyprint-override"><code>.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;

  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }

  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
    }
}
</code>```

 1

 2

 3

 4

```

Where is the error?

答:
You have to target specific clicked element's parent. You could use in your case $(this).closest('.fullcontent').

Your code becomes:

```<code>$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $(this).closest('.fullcontent').prevAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $(this).closest('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});
</code>```

JSFIDDLE

Body:
I have several divs with the class name "fullcontent".
In each div I have 2 elements: "fullcontent--prev" and "fullcontent--next".
On click on this elements I want to scroll to the next/previous fullcontent-div.

But I don't get this working with this:

https://jsfiddle.net/whgxauyd/1/

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;

  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }

  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
    }
}

 1

 2

 3

 4

Where is the error?

Body:
You have to target specific clicked element's parent. You could use in your case $(this).closest('.fullcontent').

Your code becomes:

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $(this).closest('.fullcontent').prevAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $(this).closest('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

JSFIDDLE


问:
How do I display a modalpopupextender from a server side button click?
I have an Ajax ModalPopUpExtender which works fine when launched by the target control, but what I want to do is launch it from a server side Button_Click event in VB.

This is because I want to check some variables before launching the ModalPopUpExtender.

I have tried the .show method which works fine on an initial PageLoad event when there is no post back, but the method won't work from an asp:button's onclick event or from a post back event.

I have given the ModalPopUpExtender a dummy button to target as you can't run one without the TargetControlID being set. The dummy control is visible.

As the .show method works on a PageLoad event I know the ModalPopUpExtender is set up correctly, but what could be stopping it from running from a server-side event?

Here's my code:

```<code><ajax:ModalPopupExtender
ID="mp1"
runat="server"
PopupControlID="Panel1"
TargetControlID="btnShowPopUp"                                                                      CancelControlID="btnClose"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
</code>```

Sub btnShow_Click(ByVal sender As Object, ByVal e As EventArgs)

        if myVariable = 1 then

           mp1.show

        End if

End Sub
```

答:
After searching on more permutations of my question I finally found the answer in an existing answer on the site.  The target control has to be a hidden field object, not another button.

The full answer is at:

ASP.NET: ModalPopupExtender prevents button click event from firing

Body:
I have an Ajax ModalPopUpExtender which works fine when launched by the target control, but what I want to do is launch it from a server side Button_Click event in VB.

This is because I want to check some variables before launching the ModalPopUpExtender.

I have tried the .show method which works fine on an initial PageLoad event when there is no post back, but the method won't work from an asp:button's onclick event or from a post back event.

I have given the ModalPopUpExtender a dummy button to target as you can't run one without the TargetControlID being set. The dummy control is visible.

As the .show method works on a PageLoad event I know the ModalPopUpExtender is set up correctly, but what could be stopping it from running from a server-side event?

Here's my code:

<ajax:ModalPopupExtender
ID="mp1"
runat="server"
PopupControlID="Panel1"
TargetControlID="btnShowPopUp"                                                                      CancelControlID="btnClose"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>

Sub btnShow_Click(ByVal sender As Object, ByVal e As EventArgs)

        if myVariable = 1 then

           mp1.show

        End if

End Sub


问:
a program in visual studio 2010 crushes and I dont know the reason for that
I have written a program in c++, which implements some operations on matrix using class and operations.

The code is shown below:

matrix.h

```<code>#ifndef Matrix_h
#define Matrix_h
#include <iostream>

class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix ( int rows, int cols);
    Matrix (const Matrix &other);
    ~Matrix ();
    int* & operator[](const int &index) const ;
    void operator=(const Matrix &other );
    Matrix  operator -()const;
    Matrix  operator -(const Matrix &other)const;
    Matrix  operator +(const Matrix &other)const ;
    Matrix  operator *(const Matrix &other)const;
    Matrix  operator *(const int &num)const;
    int getMatrixRows(const Matrix &other){return other.rows;}
    int getMatrixCols(const Matrix &other){return other.cols;}

    friend  Matrix operator *(const int & num,const Matrix &m)
    {
     return (m*num);
    }

    friend Matrix operator +(const int &num,const Matrix &t)
    {
     return (num+t);
    }

    friend std::ostream &operator<<(std::ostream &os, const Matrix &m)
    {
    for (int i=0; i < m.rows; ++i) {
        for (int j=0; j < m.cols; ++j) {
            os << m.Mat[i][j] << "  " ;
        }
        os << '\n';
    }
    return os;
}
};

#endif
</code>```

matrix.cpp

```<code>#include "Matrix.h"
#include <iostream>

Matrix::Matrix(int n_rows, int n_cols) //constructor
{
    rows = n_rows;
    cols = n_cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
       Mat[i] = new int[cols];
       for(int j = 0; i < cols; ++j)
           Mat[i][j] = 0;
    }
}

Matrix::Matrix(const Matrix &other) //copy constructor
{
    rows = other.rows;
    cols = other.cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
        Mat[i] = new int[cols];
        for(int j = 0; j < cols; ++j)
            Mat[i][j] = other.Mat[i][j];
    }
}

Matrix::~Matrix()  //deconstructor
{
    for(int i = 0; i < rows; ++i)
        delete Mat[i];
    delete[] Mat;
}

int* & Matrix::operator [](const int &index) const  // overloading operator []
{
  return  Mat [index];
}

void Matrix::operator=(const Matrix &other )   // overloading operator =
{
    if(Mat !=other.Mat && cols==other.cols && rows==other.rows)
     {
       for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            Mat[i][j]=other.Mat[i][j];
     }
}

 Matrix  Matrix::operator-()const   // overloading operator -
{
    Matrix temp(rows,cols);
    for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j]*-1;
   return temp;
}

 Matrix  Matrix::operator +(const Matrix &other)const  //add 2 matrix
{
    Matrix temp(rows,cols);
    if (rows!=other.rows ||cols!=other.cols)
    {
       for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j];
       return temp;
    }
    else
     {
         for(int i=0;i<rows;i++)
             for(int j=0;j<cols;j++)
                 temp.Mat[i][j]+=other.Mat[i][j]+Mat[i][j];
     }
    return temp;
}

Matrix  Matrix::operator *(const Matrix &other)const   //multiplay matrix on the right
{
    if (cols!=other.rows)
    {
      Matrix temp(cols,rows);
      for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j];
      return temp;
    }
    else
    {
      Matrix temp(cols,other.rows);
      for(int i=0;i<rows;i++)
          for(int j=0;j<other.cols;j++)
            for(int k =0;k<cols;k++)
                temp[i][j]+=Mat[i][k]*other.Mat[i][j];
      return temp;
    }

}

Matrix  Matrix::operator *(const int &num)const   //multiplay with number
{
    Matrix temp(rows,cols);
    for(int i=0;i<rows;i++)
       for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j]*num;
    return temp;
}

Matrix  Matrix::operator -(const Matrix &other)const //matrix subtraction
{
    Matrix temp(rows,cols);
    if (rows!=other.rows ||cols!=other.cols)
    {
       for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j];
       return temp;
    }
    else
     {

         for(int i=0;i<rows;i++)
             for(int j=0;j<cols;j++)
                 temp.Mat[i][j]+=Mat[i][j]-other.Mat[i][j];
     }
    return temp;
}
</code>```

main.cpp

```<code>#include "Matrix.h"
#include <iostream>
using namespace std;

void main()
{
  Matrix m(2, 2);
  m[0][0] = 2;
  m[1][1] = 2;
  cout << m << endl;
  m = m;
  const Matrix s = -m;
  cout << m << endl << s << endl;
  m = s + 2 * -m * m * 2 - s;
  cout << m << endl << s << endl;
  cout << s[1][1] << endl;
}
</code>```

The expected output is :

```<code>    2 0
    0 2
    2 0
    0 2
   -2 0
    0 -2
   -16 0
    0 -16
   -2 0
    0 -2
   -2
</code>```

Well, the program seems to be compiled well , since there is no warnings or errors. However, when I run this program - it crushes with none input.
The dubugger is pointing the line   Mat[i][j] = 0;  to be suspicious (this line is in the constructor). Hopefully someone will be able to help.

答:
The line  for(int j = 0; i < cols; ++j)   should   be

```<code> for(int j = 0; j < cols; ++j).
</code>```

Now it works.

Body:
I have written a program in c++, which implements some operations on matrix using class and operations.

The code is shown below:

matrix.h

#ifndef Matrix_h
#define Matrix_h
#include <iostream>

class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix ( int rows, int cols);
    Matrix (const Matrix &other);
    ~Matrix ();
    int* & operator[](const int &index) const ;
    void operator=(const Matrix &other );
    Matrix  operator -()const;
    Matrix  operator -(const Matrix &other)const;
    Matrix  operator +(const Matrix &other)const ;
    Matrix  operator *(const Matrix &other)const;
    Matrix  operator *(const int &num)const;
    int getMatrixRows(const Matrix &other){return other.rows;}
    int getMatrixCols(const Matrix &other){return other.cols;}

    friend  Matrix operator *(const int & num,const Matrix &m)
    {
     return (m*num);
    }

    friend Matrix operator +(const int &num,const Matrix &t)
    {
     return (num+t);
    }

    friend std::ostream &operator<<(std::ostream &os, const Matrix &m)
    {
    for (int i=0; i < m.rows; ++i) {
        for (int j=0; j < m.cols; ++j) {
            os << m.Mat[i][j] << "  " ;
        }
        os << '\n';
    }
    return os;
}
};

#endif

matrix.cpp

#include "Matrix.h"
#include <iostream>

Matrix::Matrix(int n_rows, int n_cols) //constructor
{
    rows = n_rows;
    cols = n_cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
       Mat[i] = new int[cols];
       for(int j = 0; i < cols; ++j)
           Mat[i][j] = 0;
    }
}

Matrix::Matrix(const Matrix &other) //copy constructor
{
    rows = other.rows;
    cols = other.cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
        Mat[i] = new int[cols];
        for(int j = 0; j < cols; ++j)
            Mat[i][j] = other.Mat[i][j];
    }
}

Matrix::~Matrix()  //deconstructor
{
    for(int i = 0; i < rows; ++i)
        delete Mat[i];
    delete[] Mat;
}

int* & Matrix::operator [](const int &index) const  // overloading operator []
{
  return  Mat [index];
}

void Matrix::operator=(const Matrix &other )   // overloading operator =
{
    if(Mat !=other.Mat && cols==other.cols && rows==other.rows)
     {
       for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            Mat[i][j]=other.Mat[i][j];
     }
}

 Matrix  Matrix::operator-()const   // overloading operator -
{
    Matrix temp(rows,cols);
    for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j]*-1;
   return temp;
}

 Matrix  Matrix::operator +(const Matrix &other)const  //add 2 matrix
{
    Matrix temp(rows,cols);
    if (rows!=other.rows ||cols!=other.cols)
    {
       for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j];
       return temp;
    }
    else
     {
         for(int i=0;i<rows;i++)
             for(int j=0;j<cols;j++)
                 temp.Mat[i][j]+=other.Mat[i][j]+Mat[i][j];
     }
    return temp;
}

Matrix  Matrix::operator *(const Matrix &other)const   //multiplay matrix on the right
{
    if (cols!=other.rows)
    {
      Matrix temp(cols,rows);
      for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j];
      return temp;
    }
    else
    {
      Matrix temp(cols,other.rows);
      for(int i=0;i<rows;i++)
          for(int j=0;j<other.cols;j++)
            for(int k =0;k<cols;k++)
                temp[i][j]+=Mat[i][k]*other.Mat[i][j];
      return temp;
    }

}

Matrix  Matrix::operator *(const int &num)const   //multiplay with number
{
    Matrix temp(rows,cols);
    for(int i=0;i<rows;i++)
       for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j]*num;
    return temp;
}

Matrix  Matrix::operator -(const Matrix &other)const //matrix subtraction
{
    Matrix temp(rows,cols);
    if (rows!=other.rows ||cols!=other.cols)
    {
       for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++)
            temp.Mat[i][j]=Mat[i][j];
       return temp;
    }
    else
     {

         for(int i=0;i<rows;i++)
             for(int j=0;j<cols;j++)
                 temp.Mat[i][j]+=Mat[i][j]-other.Mat[i][j];
     }
    return temp;
}

main.cpp

#include "Matrix.h"
#include <iostream>
using namespace std;

void main()
{
  Matrix m(2, 2);
  m[0][0] = 2;
  m[1][1] = 2;
  cout << m << endl;
  m = m;
  const Matrix s = -m;
  cout << m << endl << s << endl;
  m = s + 2 * -m * m * 2 - s;
  cout << m << endl << s << endl;
  cout << s[1][1] << endl;
}

The expected output is :

    2 0
    0 2
    2 0
    0 2
   -2 0
    0 -2
   -16 0
    0 -16
   -2 0
    0 -2
   -2

Well, the program seems to be compiled well , since there is no warnings or errors. However, when I run this program - it crushes with none input.
The dubugger is pointing the line   Mat[i][j] = 0;  to be suspicious (this line is in the constructor). Hopefully someone will be able to help.

Body:
The line  for(int j = 0; i < cols; ++j)   should   be

 for(int j = 0; j < cols; ++j).

Now it works.


问:
Registering a User in Hyperledger fabric
Currently admin's credentials are used to regsiter a user generating cert and private key which is stored in a single system. Both admin keys and user keys are accessible to anyone on a system where dockers are present. In a Production environment how to isolate and secure these certs and keys Because Blockchain is never hacked but the wallet is... </p>

答: Best practice would be to leverage an HSM (hardware security module) to store such material. Hyperledger Fabric supports HSMs that implement the PKCS11 standard API (though we do not publish images with PKCS11 support enabled by default, you would need to build a set of images with the appropriate compile flag).</p>


问:
How to mock a generic method to return concrete type?
I'm trying to mock the return type of a generic method to match a specific concrete type but I cannot seem to get the casting to work out:

```<code>    public T Get<T>(string key)
    {
        if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
            return GetGenericIsAuthenticatedResponse();

        return default(T);
    }

    private static GenericIsAuthenticatedResponse GetGenericIsAuthenticatedResponse()
    {
       return new GenericIsAuthenticatedResponse
        {
            AuthCode = "1234",
            Email = "email@email.com"
        };
    }
</code>```

So my question is how can I get the mock method to return the GenericIsAuthenticatedResponse?

答:
That does not work because of how generics work. If you want to return a specific type, you need to provide a filter for T:

```<code>public T Get<T>(string key) where T: GenericIsAuthenticatedResponse
</code>```

Otherwise, don't use generics for the return type:

```<code>public object Get<T>(string key)
{
    if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
        return GetGenericIsAuthenticatedResponse();

    return default(T);
}
</code>```

If you are completely sure that T will be GenericIsAuthenticatedResponse (given it's a test), you can do this:

```<code>public T Get<T>(string key)
{
    if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
        return (T)GetGenericIsAuthenticatedResponse();

    return default(T);
}
</code>```

Body:
I'm trying to mock the return type of a generic method to match a specific concrete type but I cannot seem to get the casting to work out:

    public T Get<T>(string key)
    {
        if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
            return GetGenericIsAuthenticatedResponse();

        return default(T);
    }

    private static GenericIsAuthenticatedResponse GetGenericIsAuthenticatedResponse()
    {
       return new GenericIsAuthenticatedResponse
        {
            AuthCode = "1234",
            Email = "email@email.com"
        };
    }

So my question is how can I get the mock method to return the GenericIsAuthenticatedResponse?

Body:
That does not work because of how generics work. If you want to return a specific type, you need to provide a filter for T:

public T Get<T>(string key) where T: GenericIsAuthenticatedResponse

Otherwise, don't use generics for the return type:

public object Get<T>(string key)
{
    if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
        return GetGenericIsAuthenticatedResponse();

    return default(T);
}

If you are completely sure that T will be GenericIsAuthenticatedResponse (given it's a test), you can do this:

public T Get<T>(string key)
{
    if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
        return (T)GetGenericIsAuthenticatedResponse();

    return default(T);
}


问:
Get range of a sheet up to the last cell containing data
I want to select the range of 2 columns till the last row with a value. Now I use this code:

var test = declSheet.getRange('Potjes!A:B');

Form this sheet:

The result I get is this:

How can I select till the last row with value?

答:
You can use Sheet.getDataRange function which:

Returns a Range corresponding to the dimensions in which data is
  present.

It seems like you are only interested in column A and B so:

```<code>// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// var sheet = spreadsheet.getActiveSheet();
var dataRange = sheet.getDataRange();
var desiredRange = sheet.getRange("A1:B" + dataRange.getLastRow());
// desiredRange will consist of A1:B5 in OP example
</code>```

Body:
You can use Sheet.getDataRange function which:

Returns a Range corresponding to the dimensions in which data is
  present.

It seems like you are only interested in column A and B so:

// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// var sheet = spreadsheet.getActiveSheet();
var dataRange = sheet.getDataRange();
var desiredRange = sheet.getRange("A1:B" + dataRange.getLastRow());
// desiredRange will consist of A1:B5 in OP example


问:
Using higher order component in Typescript
I am trying to use react-i18next with Typescript, and I am running into a few issues.

Here's my interface for the props that I am expecting.

```<code>import * as i18n from 'i18next';

export interface ReactI18nProps {
  t: i18n.TFunction;
}
</code>```

I then have a navigation component, which I compose.

```<code>import { translate } from 'react-i18next';

function Navigation({ t }: ReactI18nProps) {
  const userProfile = JSON.parse(localStorage.getItem('profile') || '');
  return (
    ...
  );
}

export default translate('navigation')(Navigation);
</code>```

And now I simply want to render this component that I have composed

```<code>function Appliances({ location }: NavLinkProps) {
  const userId = location && location.state.userId;
  return (
    <div>
      <Navigation />
    </div>
  );
}
</code>```

However, at this juncture, TS fails me and I get the following error

```<code>Type '{}' is not assignable to type 'IntrinsicAttributes & ReactI18nProps'.
  Type '{}' is not assignable to type 'ReactI18nProps'.
    Property 't' is missing in type '{}'.
</code>```

Could someone please explain what I am doing incorrectly.

答:
As the error message suggests:

Property 't' is missing in type '{}'

Your component expects the props to be:

```<code>interface ReactI18nProps {
    t: i18n.TFunction;
}
</code>```

But you're not passing this t:

```<code><Navigation />
</code>```

You can either make this t property optional:

```<code>interface ReactI18nProps {
    t?: i18n.TFunction;
}
</code>```

Or satisfy it:

```<code><Navigation t={ (key: string, options: i18n.TOptions) => return getTranslation(key, options) } />
</code>```

Edit

Based on the type definitions for react-i18next translation function:

```<code>function translate<TKey extends string = string>
    (namespaces?: TKey[] | TKey, options?: TOptions)
        : <C extends Function>(WrappedComponent: C) => C;
</code>```

The type of the component you pass is the exact type you get back, meaning that the same props type is used.

In this case, you'll need to use an optional t because sometimes it is used without this property (when you call it) but then it is used with t (when the translate method calls it).

To avoid the compiler complaining about t possibly be undefined you can use the non-null assertion operator:

```<code>function Navigation({ t }: ReactI18nProps) {
    ...
    const translation = t!(...);
    ...
}
</code>```

Notice that it's using t! instead of just t.

Body:
I am trying to use react-i18next with Typescript, and I am running into a few issues.

Here's my interface for the props that I am expecting.

import * as i18n from 'i18next';

export interface ReactI18nProps {
  t: i18n.TFunction;
}

I then have a navigation component, which I compose.

import { translate } from 'react-i18next';

function Navigation({ t }: ReactI18nProps) {
  const userProfile = JSON.parse(localStorage.getItem('profile') || '');
  return (
    ...
  );
}

export default translate('navigation')(Navigation);

And now I simply want to render this component that I have composed

function Appliances({ location }: NavLinkProps) {
  const userId = location && location.state.userId;
  return (

      <Navigation />

  );
}

However, at this juncture, TS fails me and I get the following error

Type '{}' is not assignable to type 'IntrinsicAttributes & ReactI18nProps'.
  Type '{}' is not assignable to type 'ReactI18nProps'.
    Property 't' is missing in type '{}'.

Could someone please explain what I am doing incorrectly.

Body:
As the error message suggests:

Property 't' is missing in type '{}'

Your component expects the props to be:

interface ReactI18nProps {
    t: i18n.TFunction;
}

But you're not passing this t:

<Navigation />

You can either make this t property optional:

interface ReactI18nProps {
    t?: i18n.TFunction;
}

Or satisfy it:

<Navigation t={ (key: string, options: i18n.TOptions) => return getTranslation(key, options) } />

Edit

Based on the type definitions for react-i18next translation function:

function translate<TKey extends string = string>
    (namespaces?: TKey[] | TKey, options?: TOptions)
        : <C extends Function>(WrappedComponent: C) => C;

The type of the component you pass is the exact type you get back, meaning that the same props type is used.

In this case, you'll need to use an optional t because sometimes it is used without this property (when you call it) but then it is used with t (when the translate method calls it).

To avoid the compiler complaining about t possibly be undefined you can use the non-null assertion operator:

function Navigation({ t }: ReactI18nProps) {
    ...
    const translation = t!(...);
    ...
}

Notice that it's using t! instead of just t.


问:
FontAwesome 5 SVG as square element
I am trying to use a font awesome 5 svg as a background image. However, it isn't showing up, and I don't know how to change the color. This is what I am using:

```<code>.no-profile-image {
  display: block;
  width: 100%;
  padding-bottom: 100%;
  background: url('/images/fa-solid.svg#user');
  background-size: contain;
  background-position: center center;
}
</code>```

I can use it as an html svg element, but then I can't make the item square like I did as a background image above. I have tried the following but it makes element the oval shaped:

```<code>svg.no-profile-image {
    width: 100%;
    padding-bottom: 100%;
}

<svg class="no-profile-image">
    <use xlink:href="/images/fa-solid.svg#user" fill="white"></use>
</svg>
</code>```

How can I either make this a background image so my div is square or make it a square html svg element?

答:
In order to get Font Awesome 5 working, you must first include the JavaScript library in the  like this:

```<code><head>
    <script defer src="https://use.fontawesome.com/releases/v5.0.1/js/all.js"></script>
</head>
</code>```

Then, in order to get the icon (the user icon in this example) you must type the following:

```<code><i class="fas fa-user"></i>
</code>```

fas stands for "font awesome solid".

There are 4 types of icons now. Solid, Regular, Light and Brands.

You can now even change the size of the icon within the  class by typing fa-lg for example. Read more about it here: https://fontawesome.com/how-to-use/svg-with-js

Title: FontAwesome 5 SVG as square element

Body:
I am trying to use a font awesome 5 svg as a background image. However, it isn't showing up, and I don't know how to change the color. This is what I am using:

.no-profile-image {
  display: block;
  width: 100%;
  padding-bottom: 100%;
  background: url('/images/fa-solid.svg#user');
  background-size: contain;
  background-position: center center;
}

I can use it as an html svg element, but then I can't make the item square like I did as a background image above. I have tried the following but it makes element the oval shaped:

svg.no-profile-image {
    width: 100%;
    padding-bottom: 100%;
}

<svg class="no-profile-image">
    <use xlink:href="/images/fa-solid.svg#user" fill="white"></use>
</svg>

How can I either make this a background image so my div is square or make it a square html svg element?

Body:
In order to get Font Awesome 5 working, you must first include the JavaScript library in the <head> like this:

<head>
    <script defer src="https://use.fontawesome.com/releases/v5.0.1/js/all.js"></script>
</head>

Then, in order to get the icon (the user icon in this example) you must type the following:

<i class="fas fa-user"></i>

fas stands for "font awesome solid".

There are 4 types of icons now. Solid, Regular, Light and Brands.

You can now even change the size of the icon within the <i> class by typing fa-lg for example. Read more about it here: https://fontawesome.com/how-to-use/svg-with-js


问:
JavaScript second function parameter magically gets a value
I am reading the JavaScript Guide, section about functions. I got the following code from there:

```<code>function map(f, a) {
    var result = [], i;

    for (i = 0; i != a.length; i++) {
        result[i] = f(a[i]);
    }
    return result;
}

var numbers = [0, 1, 2, 5, 10];
var cube = numbers.map(function(x) {
    return x * x * x;
});

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

Result: (5) [0, 1, 8, 125, 1000]

My question is how does the second param a, in map(f, a) even get a value when called in numbers.map? I only see one param being passed and that is the anonymous function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

答:
Your code is not complete, or at least different from the guide at the source page:</p>

```<code>function map(f, a) {
  var result = [];
  var i;
  for (i = 0; i != a.length; i++)
    result[i] = f(a[i]);
  return result;
}

var f = function(x) {
  return x * x * x;
}

var numbers = [0,1, 2, 5,10];
var cube = map(f, numbers);
console.log(cube);
</code>```

Body:
I am reading the JavaScript Guide, section about functions. I got the following code from there:

function map(f, a) {
    var result = [], i;

    for (i = 0; i != a.length; i++) {
        result[i] = f(a[i]);
    }
    return result;
}

var numbers = [0, 1, 2, 5, 10];
var cube = numbers.map(function(x) {
    return x * x * x;
});

console.log(cube);

Result: (5) [0, 1, 8, 125, 1000]

My question is how does the second param a, in map(f, a) even get a value when called in numbers.map? I only see one param being passed and that is the anonymous function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Body:
Your code is not complete, or at least different from the guide at the source page:

function map(f, a) {
  var result = [];
  var i;
  for (i = 0; i != a.length; i++)
    result[i] = f(a[i]);
  return result;
}

var f = function(x) {
  return x * x * x;
}

var numbers = [0,1, 2, 5,10];
var cube = map(f, numbers);
console.log(cube);


问:
getting error at " edittext.getText().toString() " inside a custom dialog
I am facing errors at the following places inside the custom dialogs that i hav created. Is is not possible to hav such functions inside a custom dialog??

final EditText x= (EditText)findViewById(R.id.edtLocationName);

String strTextValue = x.getText().toString();  //here

int x1 =geoLat.intValue()xt().toString();  //and here

答:
```<code>String strTextValue = x.getText().toString(); //here
</code>```

^ Nothing seems wrong to me on this

```<code>int x1 = geoLat.intValue()xt().toString(); //and here
</code>```

^ i think you should try int x1 = geoLat.intValue(xt).toString();

Hope that helped :)

Edit: Can you tell what errors you get?

ContentLicense: CC BY-SA 2.5

Body:
String strTextValue = x.getText().toString(); //here

^ Nothing seems wrong to me on this

int x1 = geoLat.intValue()xt().toString(); //and here

^ i think you should try int x1 = geoLat.intValue(xt).toString();

Hope that helped :)

Edit: Can you tell what errors you get?


问:
How to get a tag if I know the property of data-ng-model
I ask for help in resolving the issue.

I have code with which I fill the field:

```<code>oie.document.parentWindow.execScript "angular.element(document.getElementsByTagName('input')[52]).scope().someText = '12345';"
oie.document.parentWindow.execScript "angular.element(document.getElementsByTagName('input')[52]).scope().$apply();"
</code>```

In this case, I get the field using the tag number [52], but i know the property data-ng-model of the input tag that I fill - this property is called "sometext".

Can I fill out the form field by referring not to the tag number, but by the property data-ng-model?

Will it work like this:

```<code>oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]') = '12345';"
oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]').$apply();"
</code>```

答:
Try this..</p>

```<code>oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]').scope().sometext = '12345';"
oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]').scope().$apply();"
</code>```

Body:
I ask for help in resolving the issue.

I have code with which I fill the field:

oie.document.parentWindow.execScript "angular.element(document.getElementsByTagName('input')[52]).scope().someText = '12345';"
oie.document.parentWindow.execScript "angular.element(document.getElementsByTagName('input')[52]).scope().$apply();"

In this case, I get the field using the tag number [52], but i know the property data-ng-model of the input tag that I fill - this property is called "sometext".

Can I fill out the form field by referring not to the tag number, but by the property data-ng-model?

Will it work like this:

oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]') = '12345';"
oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]').$apply();"

Body:
Try this..

oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]').scope().sometext = '12345';"
oie.document.parentWindow.execScript "angular.element('[ng-model="sometext"]').scope().$apply();"


问:
Using dnsmasq with wildcard on Mac
I'd like to point all *.test domains to my Laravel Homestead machine on 192.168.10.10. I used to have it working with *.dev domains, but after new *.dev policy implemented by Chrome 63, I prefer to change it to *.test.

I fail to understand how local DNS works, as it seems to use trillion different configs and caches. What I did is:

Making sure 192.168.10.10 with HTTP Host set to me.test works. It works.

In /usr/local/etc/dnsmasq.conf, I do have an entry address=/.test/192.168.10.10 (I also tried with 127.0.0.1)

In /etc/resolver/test file, I put nameserver 127.0.0.1 - it used to work this way with /etc/resolver/dev. I still don't understand why it's 127.0.0.1 and not 192.168.10.10. I tried both anyway.

Clearing DNS cache with sudo killall -HUP mDNSResponder; sudo killall mDNSResponderHelper; sudo dscacheutil -flushcache

Restarting dnsmasq with sudo launchctl stop homebrew.mxcl.dnsmasq; sudo launchctl start homebrew.mxcl.dnsmasq.

Trying to visit http://me.test/.

It doesn't work. The domain will take forever to be loaded and nothing happens.

What am I doing wrong?

My OS is High Sierra, dnsmasq installed via homebrew.

答:
I don't use dnsmasq, but I believe you want to edit /usr/local/etc/dnsmasq.conf and have listen-address=127.0.0.1 set so dnsmasq is listening on that IP, but have address=/.test/192.168.10.10 so that .test is routed to 192.168.10.10.

Then make sure System Preferences -> Advanced you have 127.0.0.1 as the first DNS server entry for your connection.

Make sure you're restarting dnsmasq every time you edit the configuration file.

Title: Using dnsmasq with wildcard on Mac


问:
How to exit a for loop java?
Hi I am writing java code that will take user input and place the user input into an ArrayList but I want the user to be able to enter Q when they have input all the data. But when I input q on certain instances I am getting the wrong output.

```<code>public void enterScores()
{
    System.out.println("Enter the scores of the student, press Q to finish");
    for (int i = 0; i < SCORES_SIZE; i++)
    {
        exitLoop = userInput.next();
        if (exitLoop.equalsIgnoreCase("Q"))
        {
            break;
        }
        scores.add(i, userInput.nextInt());
    }
    System.out.println("___________");
    for (int i = 0; i < scores.size(); i++)
        System.out.println(scores.get(i)); //Prints out the arraylist of scores entered
    System.out.println("_____");
    System.out.println(scores.size()); //prints out the size of the arraylist but is wrong
}
</code>```

The following code after the for loop was only so I could make sure it was running properly but unfortunately it is not. It seems as if it is only reading some of the numbers into the ArrayList So the input I am getting is:

```<code>   Enter the scores of the student, press Q to finish
12
13
14
145
14
13
q
___________
13
145
13
_____
3
</code>```

So when I enter q (to quit the loop) in an odd position, the program will exit the loop but the only numbers that are read into the ArrayList are the numbers in the even positions. And when i enter q in an even position I get the following error:

```<code>Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Chapter_7.GradeBook.enterScores(GradeBook.java:36)
    at Chapter_7.GradeBookTester.main(GradeBookTester.java:12)
</code>```

答:
Try this one:</p>

```<code>public void enterScores() {
    Scanner userInput = new Scanner(System.in);
    System.out.println("Enter the scores of the student, press Q to finish");
    for (int i = 0; i < SCORES_SIZE; i++) {
        String input = userInput.next();
        if ("Q".equals(input)) {
            break;
        }
        try {
            scores.add(i, Integer.parseInt(input));
        } catch (NumberFormatException e) {
            System.out.println("entered value can not be casted to integer");
        }
    }
}
</code>```

Title: How to exit a for loop java?

Body:
Hi I am writing java code that will take user input and place the user input into an ArrayList but I want the user to be able to enter Q when they have input all the data. But when I input q on certain instances I am getting the wrong output.

public void enterScores()
{
    System.out.println("Enter the scores of the student, press Q to finish");
    for (int i = 0; i < SCORES_SIZE; i++)
    {
        exitLoop = userInput.next();
        if (exitLoop.equalsIgnoreCase("Q"))
        {
            break;
        }
        scores.add(i, userInput.nextInt());
    }
    System.out.println("___________");
    for (int i = 0; i < scores.size(); i++)
        System.out.println(scores.get(i)); //Prints out the arraylist of scores entered
    System.out.println("_____");
    System.out.println(scores.size()); //prints out the size of the arraylist but is wrong
}

The following code after the for loop was only so I could make sure it was running properly but unfortunately it is not. It seems as if it is only reading some of the numbers into the ArrayList So the input I am getting is:

   Enter the scores of the student, press Q to finish
12
13
14
145
14
13
q
___________
13
145
13
_____
3

So when I enter q (to quit the loop) in an odd position, the program will exit the loop but the only numbers that are read into the ArrayList are the numbers in the even positions. And when i enter q in an even position I get the following error:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Chapter_7.GradeBook.enterScores(GradeBook.java:36)
    at Chapter_7.GradeBookTester.main(GradeBookTester.java:12)

Body:
Try this one:

public void enterScores() {
    Scanner userInput = new Scanner(System.in);
    System.out.println("Enter the scores of the student, press Q to finish");
    for (int i = 0; i < SCORES_SIZE; i++) {
        String input = userInput.next();
        if ("Q".equals(input)) {
            break;
        }
        try {
            scores.add(i, Integer.parseInt(input));
        } catch (NumberFormatException e) {
            System.out.println("entered value can not be casted to integer");
        }
    }
}


问:
Is it better practice to maintain specialised log tables or calculate number of entries with each sql
I've been looking through some open source projects such as SMF forums etc and noticed that it incorporates specialised log tables that store just what seems like counts of boards, member, topics and even search results.

Currently in my projects I don't use such tables at all and instead make use of SQL_CALC_ROWS or COUNT in order to get total number of entries for a search query etc. I'm assuming that this is a bit of an over head on its own and was wondering if using log tables are an effective solution or is it vice versa.

Likewise I also have used the same method in a web application which could do with a speed boost. What are the overheads in executing specialised sql queries using GROUP_CONCAT, COUNT etc as opposed to setting up a program to automatically update a numeric count in a certain table when required.

For example if on one page I need to show statistics like number of members, number of classifeds entry and last active users - I normally execute a SQL_CALC_ROWS + FOUND_ROWS in mysql.

答:
Using COUNT is inherently slow as by definition it requires counting all rows, and usually this requires a full scan. It can therefore by advantageous to cache this result for performance reasons.

Note that this violates normalization and can lead to slight inconsistencies if the cached value isn't updated every time the data changes, but if performance is a real concern it can be worth it.

For example, if you are doing a search and you want to show 'Results 1-10 out of 105,000' it is often more important that results are returned quickly than the total numbers of rows is exactly correct.


问:
Confusion with type inference of literals in Go
I have started learning GoLang and I am currently reading about its type inference system using the short variable declaration syntax.

Here is a simple program that caught my attention and is causing me some diffculty in understanding:

```<code>package main

import (
    "fmt"
    "sort"
)

type statistics struct {
    numbers []float64
    mean    float64
    median  float64
}

// Performs analytics on a slice of floating-point numbers
func GenerateStats(numbers []float64) (stats statistics) {
    stats.numbers = numbers
    stats.mean = sum(numbers) / float64(len(numbers))
    sort.Float64s(numbers)
    stats.median = median(numbers)
    return stats
}

// Helper function to sum up a slice of floats
func sum(numbers []float64) (total float64) {
    for _, num := range numbers {
        total += num
    }
    return total
}

// Helper to find the median of a sorted slice of floats
func median(numbers []float64) (med float64) {
    n := len(numbers)
    if n%2 == 0 {
        med = numbers[n/2]
    } else {
        med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01
    }
    return med
}

func main() {
    nums := []float64{1, 2, 3, 3, 4}
    result := generateStats(nums)
    fmt.Println(result.numbers)
    fmt.Println(result.mean)
    fmt.Println(result.median)

    b := "This is Go" + 1.9 // Infer 02
    fmt.Println(b)
}
</code>```

When I execute this program using: $ go run <path>/statistics.go,

I get the following error message:

```<code># command-line-arguments
<path>/statistics.go:47:20: cannot convert "This is Go" to type float64
<path>/statistics.go:47:20: invalid operation: "This is Go" + 1.9 (mismatched types string and float64)
</code>```

Here is reasoning for the different behavious:

Infer 01: The type of numeric literal 2 is inferred on the basis of the expression it is used in. Since the type of numerator is float64, Go performs the division successfully by assuming 2 as of the corresponding type. Hence, the type of the variable on LHS is float64.

I used the same reasoning for Infer 02:
The type of float literal 1.9 is inferred on the basis of the declaration. However, a float literal cannot be added to a string unless it is implicitly converted to a string. So, I am unsure about the type of the variable b. Hence, an error should be raised.

Now, I am confused by the error message.

Why does the compiler try to implicitly convert string literal to float64 type?

In a general sense: How does the compiler infer types when both the operands are literals? What are some good resources that can help me understand Go's type inference system better?

答:
Literal and constants in Go does not have a Go type. For example:

think of 1.1234 as float constant (and not a float32 or float64)

2 as an int constant

"hi" as a string constant.

When you try to put a constant inside a variable Go tries to fit the constant in the variable based on variable type:

```<code>type DayCount int
const i = 123456

var a int32 = i
var b uint64 = i
var c int = i
var d int8 = i  // compile error: constant 123456 overflows int8
var e DayCount = i
var f DayCount = c  // compile error: cannot use c (type int) as type DayCount in assignment
</code>```

If the variable itself doesn't have a type and the right hand side of assignment is a constant, compiler will assume the "default type" of the constant. That is int type for int constants and float64 for float constants.

```<code>var a = 1234          // a type will be int
var b = 1.1234567890  // b type will be float64
var c = "gogogo"      // c type will be string
</code>```

You could also do some operations on constants (before they are converted to normal go variable) that is done in compile time:

```<code>var a int8 = 25 * 87  // compile error: constant 2175 overflows int8
</code>```

As both 25 and 87 are constants compiler will multiple them when your are compiling your program and tries to fit it into variable a that fails. The point is multiply is not done when you are running your program.

If you try to mix normal variables and constants, compiler will try to convert constants to your variables type:

```<code>var a uint64 = 87
var b = 25 * a
// Is the same as
var b = uint64(25) * a
// so b type is uint64
</code>```

Now about the first case in your question

```<code>med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01
</code>```

is the same as

```<code>med = (numbers[n/int(2)] + numbers[(n-int(1))/int(2)]) / float64(2)
</code>```

Compiler will try to cast constant into nearby variable type. The first and second 2 is being used in a division operation with an int and are converted to int. The third one is used in a division with a float64 and converted to float64. I don't think "type inference" is a fitting name for here.

In the second case both + operators are constants, compiler uses a heuristic approach and assumes that if one of the constants is float both constants should be fit into a float64 (that is faulty) and tries to put a string constant into float64 that fails (Hence the can't convert to float64 error).

The second case behavior is not documented in spec and I don't think it matters at all. IMO a valid compiler may try to fit 1.9 into a string variable and shows another error.

See also blog on constants, spec on constants, spec on constants expressions.

Body:
I have started learning GoLang and I am currently reading about its type inference system using the short variable declaration syntax.

Here is a simple program that caught my attention and is causing me some diffculty in understanding:

package main

import (
    "fmt"
    "sort"
)

type statistics struct {
    numbers []float64
    mean    float64
    median  float64
}

// Performs analytics on a slice of floating-point numbers
func GenerateStats(numbers []float64) (stats statistics) {
    stats.numbers = numbers
    stats.mean = sum(numbers) / float64(len(numbers))
    sort.Float64s(numbers)
    stats.median = median(numbers)
    return stats
}

// Helper function to sum up a slice of floats
func sum(numbers []float64) (total float64) {
    for _, num := range numbers {
        total += num
    }
    return total
}

// Helper to find the median of a sorted slice of floats
func median(numbers []float64) (med float64) {
    n := len(numbers)
    if n%2 == 0 {
        med = numbers[n/2]
    } else {
        med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01
    }
    return med
}

func main() {
    nums := []float64{1, 2, 3, 3, 4}
    result := generateStats(nums)
    fmt.Println(result.numbers)
    fmt.Println(result.mean)
    fmt.Println(result.median)

    b := "This is Go" + 1.9 // Infer 02
    fmt.Println(b)
}

When I execute this program using: $ go run <path>/statistics.go,

I get the following error message:

# command-line-arguments
<path>/statistics.go:47:20: cannot convert "This is Go" to type float64
<path>/statistics.go:47:20: invalid operation: "This is Go" + 1.9 (mismatched types string and float64)

Here is reasoning for the different behavious:

Infer 01: The type of numeric literal 2 is inferred on the basis of the expression it is used in. Since the type of numerator is float64, Go performs the division successfully by assuming 2 as of the corresponding type. Hence, the type of the variable on LHS is float64.

I used the same reasoning for Infer 02:
The type of float literal 1.9 is inferred on the basis of the declaration. However, a float literal cannot be added to a string unless it is implicitly converted to a string. So, I am unsure about the type of the variable b. Hence, an error should be raised.

Now, I am confused by the error message.

Why does the compiler try to implicitly convert string literal to float64 type?

In a general sense: How does the compiler infer types when both the operands are literals? What are some good resources that can help me understand Go's type inference system better?

Body:
Literal and constants in Go does not have a Go type. For example:

think of 1.1234 as float constant (and not a float32 or float64)

2 as an int constant

"hi" as a string constant.

When you try to put a constant inside a variable Go tries to fit the constant in the variable based on variable type:

type DayCount int
const i = 123456

var a int32 = i
var b uint64 = i
var c int = i
var d int8 = i  // compile error: constant 123456 overflows int8
var e DayCount = i
var f DayCount = c  // compile error: cannot use c (type int) as type DayCount in assignment

If the variable itself doesn't have a type and the right hand side of assignment is a constant, compiler will assume the "default type" of the constant. That is int type for int constants and float64 for float constants.

var a = 1234          // a type will be int
var b = 1.1234567890  // b type will be float64
var c = "gogogo"      // c type will be string

You could also do some operations on constants (before they are converted to normal go variable) that is done in compile time:

var a int8 = 25 * 87  // compile error: constant 2175 overflows int8

As both 25 and 87 are constants compiler will multiple them when your are compiling your program and tries to fit it into variable a that fails. The point is multiply is not done when you are running your program.

If you try to mix normal variables and constants, compiler will try to convert constants to your variables type:

var a uint64 = 87
var b = 25 * a
// Is the same as
var b = uint64(25) * a
// so b type is uint64

Now about the first case in your question

med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01

is the same as

med = (numbers[n/int(2)] + numbers[(n-int(1))/int(2)]) / float64(2)

Compiler will try to cast constant into nearby variable type. The first and second 2 is being used in a division operation with an int and are converted to int. The third one is used in a division with a float64 and converted to float64. I don't think "type inference" is a fitting name for here.

In the second case both + operators are constants, compiler uses a heuristic approach and assumes that if one of the constants is float both constants should be fit into a float64 (that is faulty) and tries to put a string constant into float64 that fails (Hence the can't convert to float64 error).

The second case behavior is not documented in spec and I don't think it matters at all. IMO a valid compiler may try to fit 1.9 into a string variable and shows another error.

See also blog on constants, spec on constants, spec on constants expressions.


问:
Optional input variables in scanf
is there a way to have optional input variables in scanf ?

I have a program that scans input until EOF. That input can look like this:

```<code>+ 10 20 30
- 10 20 30
? 10
</code>```

When I type (or read from a file) + or - it is always followed by three numbers but when I type in ? it is only followed by one number (always).

My current code looks like this:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(){
  char action;
  int dc1,dc2,cable;
  while(scanf(" %c %d %d %d",&action,&dc1,&dc2,&cable)!=EOF){
    if((dc1==dc2)||(cable<1)||(dc1>999)||(dc2>999)||(dc1<0)||(dc2<0)){
      printf("Wrong input.\n");
      return 0;
    }
    else{
      if(action=='+'){
      /*code*/
      }
      else if(action=='-'){
      /*code*/
      }
      else if(action=='?'){
      /*code*/
      }
      else{
        printf("Wrong input.\n");
        return 0;
      }
    }
  }
  return 0;
}
</code>```

Right now it requires me to type in three numbers all the time, even if I want to type in the "?" action.

Is there a way to make some of the variables in scanf optional so the input "? 10" would also be valid.

PS.

I have stripped the code so it is not too long. I hope I have included everything that is necessary.

I would also appreciate if I didn't have to rework the code too much because it is basically done, everything works like it needs to. This is the only thing that is stopping me from turning in my code.

PPS. This is for a homework.

答:
As mentioned in comment this can be easily checked with sscanf() and fgets.
We are using the fgets to read a line and then pass it to the parser function. That function tries to parse the line. sscanf returns the successful number of parameters passed. Based on that count we are deciding which input it is.

This code is just a starting point for how to start. It avoids the lots of error checking and concentrates on the technique as discussed above by Jonathan Leffler.

Code example

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 256

void add (int b,int c,int d){
    printf("%d+%d+%d=%d\n",b,c,d,b+c+d);
}
void sub (int b,int c,int d){
    printf("%d-%d-%d=%d\n",b,c,d,b-c-d);
}
void query (int a){
    printf("?%d\n",a);
}
void parseAndProcess(const char *buf){
    char a;
    int  b, c, d;
    size_t ct;
    ct  = sscanf(buf,"%c%d%d%d",&a,&b,&c,&d);
    if( ct <= 1){
        //error
    }
    else if( ct==2 ) {
        if( a == '?'){
            query(b);
        }
        else{
            //error
        }
    }
    else if( ct == 3){
        // error
    }
    else if( ct == 4){
        if( a == '+') add(b,c,d);
        else if( a == '-') sub(b,c,d);
        else{
            //error
        }
    }
    else{
        // error
    }

}

int main(void){
    char buf[BUFFSIZE];
    while(fgets(buf,BUFFSIZE,stdin)){
        parseAndProcess(buf);
    }
    return EXIT_SUCCESS;
}
</code>```

Here add,sub methods are to be implemented for actual code. A demo implementation is shown here above. For example here in add,sub no overflow checking is there.

Title: Optional input variables in scanf

Body:
is there a way to have optional input variables in scanf ?

I have a program that scans input until EOF. That input can look like this:

+ 10 20 30
- 10 20 30
? 10

When I type (or read from a file) + or - it is always followed by three numbers but when I type in ? it is only followed by one number (always).

My current code looks like this:

#include <stdio.h>
#include <stdlib.h>

int main(){
  char action;
  int dc1,dc2,cable;
  while(scanf(" %c %d %d %d",&action,&dc1,&dc2,&cable)!=EOF){
    if((dc1==dc2)||(cable<1)||(dc1>999)||(dc2>999)||(dc1<0)||(dc2<0)){
      printf("Wrong input.\n");
      return 0;
    }
    else{
      if(action=='+'){
      /*code*/
      }
      else if(action=='-'){
      /*code*/
      }
      else if(action=='?'){
      /*code*/
      }
      else{
        printf("Wrong input.\n");
        return 0;
      }
    }
  }
  return 0;
}

Right now it requires me to type in three numbers all the time, even if I want to type in the "?" action.

Is there a way to make some of the variables in scanf optional so the input "? 10" would also be valid.

PS.

I have stripped the code so it is not too long. I hope I have included everything that is necessary.

I would also appreciate if I didn't have to rework the code too much because it is basically done, everything works like it needs to. This is the only thing that is stopping me from turning in my code.

PPS. This is for a homework.

Body:
As mentioned in comment this can be easily checked with sscanf() and fgets.
We are using the fgets to read a line and then pass it to the parser function. That function tries to parse the line. sscanf returns the successful number of parameters passed. Based on that count we are deciding which input it is.

This code is just a starting point for how to start. It avoids the lots of error checking and concentrates on the technique as discussed above by Jonathan Leffler.

Code example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 256

void add (int b,int c,int d){
    printf("%d+%d+%d=%d\n",b,c,d,b+c+d);
}
void sub (int b,int c,int d){
    printf("%d-%d-%d=%d\n",b,c,d,b-c-d);
}
void query (int a){
    printf("?%d\n",a);
}
void parseAndProcess(const char *buf){
    char a;
    int  b, c, d;
    size_t ct;
    ct  = sscanf(buf,"%c%d%d%d",&a,&b,&c,&d);
    if( ct <= 1){
        //error
    }
    else if( ct==2 ) {
        if( a == '?'){
            query(b);
        }
        else{
            //error
        }
    }
    else if( ct == 3){
        // error
    }
    else if( ct == 4){
        if( a == '+') add(b,c,d);
        else if( a == '-') sub(b,c,d);
        else{
            //error
        }
    }
    else{
        // error
    }

}

int main(void){
    char buf[BUFFSIZE];
    while(fgets(buf,BUFFSIZE,stdin)){
        parseAndProcess(buf);
    }
    return EXIT_SUCCESS;
}

Here add,sub methods are to be implemented for actual code. A demo implementation is shown here above. For example here in add,sub no overflow checking is there.


问:
Reduce height of div from top, instead of reduce from bottom
I want to make a chat application. my problem is, when my textbox increase it height, the chat-container reduce it height from bottom.

I want the chat container reduce it height from top.
For example:

This is my chat-box looklike. And, when my textbox increase it height, it'll show like this

What i expected is like this

And also, when the chat-container is not at bottom, they also reduce it height from top too. like this

This is my code

.chat-container, .chat-content, p, .chat-input {
  box-sizing: border-box;
 padding: 10px;
 border: 2px solid black;
}

.chat-container {
 width: 300px;
 height: 400px;
 display: flex;
 flex-direction: column;
}

.chat-content {
 width: 100%;
 overflow: auto;
 flex-grow: 1;
}

.input-here {
 width: 100%;
 max-height: 150px;
}

.input-here {
 border: 2px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="chat-container">
 <div class="chat-content">
  <p>Hello</p>
  <p>This is example words.</p>
  <p>This is another example #1</p>
  <p>This is another example #2</p>
  <p>This is another example #3</p>
  <p>This is another example #4</p>
  <p>This is another example #5</p>
 </div>
 <div class="chat-input">
  <div contenteditable="true" class="input-here"></div>
 </div>
</div></code>```

Sorry for my bad english.
Thank you so much.

答:
I think this is what you needed. Changes:

A bit of javascript added to scroll the chat content to the bottom when input is being typed using onkeyUp function.

A overflow-y:scroll added to your chat input so that the text doesn't overflow the max-height otherwise it normally does.

You also might want to reduce the max-height of .input-here to a lower value and it will look much better. Hope, it helps.

// Store your div in a variable
var objDiv = document.getElementById("chat");
// Execute the function once on load
myFunction();

function myFunction() {
  objDiv.scrollTop = objDiv.scrollHeight;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.chat-container,
.chat-content,
p,
.chat-input {
  box-sizing: border-box;
  padding: 10px;
  border: 2px solid black;
}

.chat-container {
  width: 300px;
  height: 400px;
  display: flex;
  flex-direction: column;
}

.chat-content {
  width: 100%;
  overflow: auto;
  flex-grow: 1;
}

.input-here {
  width: 100%;
  max-height: 100px;
  overflow-y: scroll;
}

.input-here {
  border: 2px solid red;
}</code>```

Hello

This is example words.

This is another example #1

This is another example #2

This is another example #3

This is another example #4

This is another example #5

This is another example #6

This is another example #7

This is another example #8

```

Body:
I want to make a chat application. my problem is, when my textbox increase it height, the chat-container reduce it height from bottom.

I want the chat container reduce it height from top.
For example:

This is my chat-box looklike. And, when my textbox increase it height, it'll show like this

What i expected is like this

And also, when the chat-container is not at bottom, they also reduce it height from top too. like this

This is my code

.chat-container, .chat-content, p, .chat-input {
  box-sizing: border-box;
 padding: 10px;
 border: 2px solid black;
}

.chat-container {
 width: 300px;
 height: 400px;
 display: flex;
 flex-direction: column;
}

.chat-content {
 width: 100%;
 overflow: auto;
 flex-grow: 1;
}

.input-here {
 width: 100%;
 max-height: 150px;
}

.input-here {
 border: 2px solid red;
}

Hello

This is example words.

This is another example #1

This is another example #2

This is another example #3

This is another example #4

This is another example #5

Sorry for my bad english.
Thank you so much.

Body:
I think this is what you needed. Changes:

A bit of javascript added to scroll the chat content to the bottom when input is being typed using onkeyUp function.

A overflow-y:scroll added to your chat input so that the text doesn't overflow the max-height otherwise it normally does.

You also might want to reduce the max-height of .input-here to a lower value and it will look much better. Hope, it helps.

// Store your div in a variable
var objDiv = document.getElementById("chat");
// Execute the function once on load
myFunction();

function myFunction() {
  objDiv.scrollTop = objDiv.scrollHeight;
}

.chat-container,
.chat-content,
p,
.chat-input {
  box-sizing: border-box;
  padding: 10px;
  border: 2px solid black;
}

.chat-container {
  width: 300px;
  height: 400px;
  display: flex;
  flex-direction: column;
}

.chat-content {
  width: 100%;
  overflow: auto;
  flex-grow: 1;
}

.input-here {
  width: 100%;
  max-height: 100px;
  overflow-y: scroll;
}

.input-here {
  border: 2px solid red;
}

<div class="chat-container">
  <div class="chat-content" id="chat">
    <p>Hello</p>
    <p>This is example words.</p>
    <p>This is another example #1</p>
    <p>This is another example #2</p>
    <p>This is another example #3</p>
    <p>This is another example #4</p>
    <p>This is another example #5</p>
    <p>This is another example #6</p>
    <p>This is another example #7</p>
     <p>This is another example #8</p>
  </div>
  <div class="chat-input">
    <div contenteditable="true" class="input-here" onkeyup="myFunction()"></div>
  </div>
</div>


问:
How backpropagation through gradient descent represents the error after each forward pass
In Neural NEtwork Multilayer Perceptron, I understand that the main difference between Stochastic Gradient Descent (SGD) vs Gradient Descent (GD) lies in the way of how many samples are chosen while training. That is, SGD iteratively chooses one sample to perform forward pass followed by backpropagation to adjust the weights, as oppose to GD where the backpropagation starts only after the entire samples have been calculated in the forward pass).

My questions are:

When the Gradient Descent (or even mini-batch Gradient Descent) is the chosen approach, how do we represent the error from a single forward pass? Assuming that my network has only a single output neuron, is the error represented by averaging all the individual errors from each sample or by summing all of them?

In MLPClassifier scikit learn, does anyone know how such error is accumulated? Averaging or summing?

Thank you very much.

答:
I think I can answer your first question. Yes, the error of a single forward pass is computed as either the instantaneous error, e.g., the norm of the difference between the network output and the desired response (label), if one sample is fed to the network or the average of the instantaneous errors obtained from feeding a mini-batch of samples.

I hope this helps.


问:
Strategy pattern Qt ambiguous base

For a school project we have to make a 'game', in this game we visualize a maze and find our way through it. This visualization has to be possible in two different ways, in our case a text-based visualization and a more fancy way.

We have to use Qt for this, we are using a QMainWindow with a QWidget in it, this widget will be one or the other visualization. Seeing that during the game we should be able to switch between visualizations, we use the Strategy Pattern, so made an interface (ViewInterface) and both visualizations implement this. Beside implementing ViewInterface, both visualizations inherit another class, in the text-based this is QPlainTextEdit (to have a QWidget with text) and in the Fancy this is QDialog. Probem here is that in my controller, I have a pointer to a ViewInterface which is used to fill the QWidet but to do this ViewInterface also has to inherit from QWidget, which causes this error: QObject is an ambiguous base of 'TerminalView'.

Since the switching between views can be done while playing the game, and update should be called only on the currently-active view, we can't pass the specific view to 'setWidget'.

Am I doing something wrong or how can I solve this? (I already thought about it but can't come with solutions).

答:
The problem here is that you inherit QObject twice: first in ViewInterface hierarchy, second in QDialog hierarchy (diamond problem). <s>Try using virtual inheritance for your FancyView and TextView classes </s> (DOES NOT WORK, SINCE VIRTUAL INHERITANCE SHOULD BE USED IN ENTIRE HIERARCHY)

But there is another problem with your design: both QDialog and QPlainTextEdit inherit QWidget. To resolve this issue you may do the following:

Make ViewInterface abstract without inheriting from QObject. This abstract class will define the interface of your FancyView and TextView and may or may not implement some common logic.

Implement FancyView and TextView with multiple inheritance from QDialog and ViewInterface and from QPlainTextEdit and ViewInterface respectively.

This way you may not encounter any problems with ambiguous base class.

UPDATE:

Did not see your edit yet: indeed this would solve the issue, but
  another problem rises: if I do this, I can't use a ViewInterface
  pointer to set my QWidget. It is possible indeed, but in my opinion
  this is not really clean

Well, that is a real problem. An obvious solution is not to use ViewInterface* instead of QWidget*. But this means that you need to change quite a lot of code and it may actually be not that great in your case.

With respect to the given comment, I propose another solution:

Inherit ViewInterface from QWidget (with all desired interface functions):

```<code>class ViewInterface: public QWidget {
    Q_OBJECT
    ...
}
</code>```

In ViewInterface constructor set layout to be used by widget and set it up:

```<code>ViewInterface::ViewInterface (QWidget* i_parent)
    : QWidget (i_parent) {
    auto layout {new QGridLayout (this)};

    // Zeroed margins to make full fit.
    layout->setContentsMargins (0, 0, 0, 0);

    setLayout (layout);
}
</code>```

In constructors of derived classes add specific widget to layout:

```<code>class FancyView : public ViewInterface {
    Q_OBJECT

    FancyView (QWidget* i_parent)
        : ViewInterface (i_parent)
        , dialog_widget_ {new QDialog (this)} {
        layout->addWidget (dialog_widget_);
    }
    ...

private:
    QDialog* dialog_widget_;
}
</code>```

Implement desired interface using target widget. If you want to process events, you may use QObject::eventFilter (). In this case you should set your FancyView object from the code above as event filter for dialog_widget_.

NOTE: In this case you can not use FancyView as QDialog. A workabound for this issue is proxy QDialog signals, slots and public functions and create yet another wrapper class FancyViewDialog, that works as proxy for the methods, signals and slots in FancyView. That is not a fantastic solution, but I do not see any other way around diamond problem that allows "is-a" relation between ViewInterface and QWidget.

Title: Strategy pattern Qt ambiguous base

Body:
The problem here is that you inherit QObject twice: first in ViewInterface hierarchy, second in QDialog hierarchy (diamond problem). <s>Try using virtual inheritance for your FancyView and TextView classes </s> (DOES NOT WORK, SINCE VIRTUAL INHERITANCE SHOULD BE USED IN ENTIRE HIERARCHY)

But there is another problem with your design: both QDialog and QPlainTextEdit inherit QWidget. To resolve this issue you may do the following:

Make ViewInterface abstract without inheriting from QObject. This abstract class will define the interface of your FancyView and TextView and may or may not implement some common logic.

Implement FancyView and TextView with multiple inheritance from QDialog and ViewInterface and from QPlainTextEdit and ViewInterface respectively.

This way you may not encounter any problems with ambiguous base class.

UPDATE:

Did not see your edit yet: indeed this would solve the issue, but
  another problem rises: if I do this, I can't use a ViewInterface
  pointer to set my QWidget. It is possible indeed, but in my opinion
  this is not really clean

Well, that is a real problem. An obvious solution is not to use ViewInterface* instead of QWidget*. But this means that you need to change quite a lot of code and it may actually be not that great in your case.

With respect to the given comment, I propose another solution:

Inherit ViewInterface from QWidget (with all desired interface functions):

class ViewInterface: public QWidget {
    Q_OBJECT
    ...
}

In ViewInterface constructor set layout to be used by widget and set it up:

ViewInterface::ViewInterface (QWidget* i_parent)
    : QWidget (i_parent) {
    auto layout {new QGridLayout (this)};

    // Zeroed margins to make full fit.
    layout->setContentsMargins (0, 0, 0, 0);

    setLayout (layout);
}

In constructors of derived classes add specific widget to layout:

class FancyView : public ViewInterface {
    Q_OBJECT

    FancyView (QWidget* i_parent)
        : ViewInterface (i_parent)
        , dialog_widget_ {new QDialog (this)} {
        layout->addWidget (dialog_widget_);
    }
    ...

private:
    QDialog* dialog_widget_;
}

Implement desired interface using target widget. If you want to process events, you may use QObject::eventFilter (). In this case you should set your FancyView object from the code above as event filter for dialog_widget_.

NOTE: In this case you can not use FancyView as QDialog. A workabound for this issue is proxy QDialog signals, slots and public functions and create yet another wrapper class FancyViewDialog, that works as proxy for the methods, signals and slots in FancyView. That is not a fantastic solution, but I do not see any other way around diamond problem that allows "is-a" relation between ViewInterface and QWidget.


问:
Unable to create the Write-in Product under Quote in Dynamics CRM using web-api
I am able to link the Existing product under quote by passing a Product ID and an UOMS ID using the post below in Postman.

```<code>{
"productid@odata.bind":"/products(de646511-f937-e711-8104-c4346bacc0f8)",

 "quoteid@odata.bind" : "/quotes(2f15f376-2b41-e711-8108-c4346bac2908)",

        "uomid@odata.bind": "/uoms(1cb3bab6-ed37-e711-8107-c4346baceb84)",

  "quantity":1
}
</code>```

But my requirement is to create the Writein Product where the UOMS ID should be null which I am unable to move further without passing an UOMS ID.

It is throwing an error saying:

need to pass UOMS ID.

答:
Specify that the product is a write-in product and include the required information for a write-in product in your object like this</p>

```<code>{
"quantity": 1,
"quoteid@odata.bind" : "/quotes(2f15f376-2b41-e711-8108-c4346bac2908)",
"productdescription" : "My Write-in Product",
"isproductoverridden" : true,
"ispriceoverridden" : true
}
</code>```

Body:
I am able to link the Existing product under quote by passing a Product ID and an UOMS ID using the post below in Postman.

{
"productid@odata.bind":"/products(de646511-f937-e711-8104-c4346bacc0f8)",

 "quoteid@odata.bind" : "/quotes(2f15f376-2b41-e711-8108-c4346bac2908)",

        "uomid@odata.bind": "/uoms(1cb3bab6-ed37-e711-8107-c4346baceb84)",

  "quantity":1
}

But my requirement is to create the Writein Product where the UOMS ID should be null which I am unable to move further without passing an UOMS ID.

It is throwing an error saying:

need to pass UOMS ID.

Body:
Specify that the product is a write-in product and include the required information for a write-in product in your object like this

{
"quantity": 1,
"quoteid@odata.bind" : "/quotes(2f15f376-2b41-e711-8108-c4346bac2908)",
"productdescription" : "My Write-in Product",
"isproductoverridden" : true,
"ispriceoverridden" : true
}


问:
Use of Datadog and Webhooks to call multiple numbers
I have my application integrated with Datadog for monitoring purpose. At the same time I want the notifications/calls to be sent to the team if any of the metric fails to achieve the desires value. I used Webhooks integration in Datadog for this purpose. In the webhooks configuration I have set the URL (Twilio request) and I do get a call on my number. Now I am looking for an scenario wherein if the user doesn't pick the call for say 30secs then try calling the second number. How do I achieve this? </p>

答: If you are looking for a more full featured paid solution I'd recommend PagerDuty. DataDog has an integration for PagerDuty. Any monitor that gets triggered that mentions @pagerduty-myteamname(as example) in the monitor message will cause PagerDuty to page the on call person.  If that person does not acknowledge the page you can configure it to go through list of people to contact next until it is acknowledged by someone.


问:
scroll to next element with same parent class
I have several divs with the class name "fullcontent".
In each div I have 2 elements: "fullcontent--prev" and "fullcontent--next".
On click on this elements I want to scroll to the next/previous fullcontent-div.

But I don't get this working with this:

https://jsfiddle.net/whgxauyd/1/

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});
```

<pre class="lang-css prettyprint-override"><code>.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;

  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }

  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
    }
}
</code>```

 1

 2

 3

 4

```

Where is the error?

答:
you were not saving the reference to the current element focused
just add the reference like var elementCur=$(this).parent();  for next and var curElement=$(this).parent() for prev like below

```<code>$(".fullcontent--prev").on('click',function() {
var curElement=$(this).parent();
  $('html, body').animate({
      scrollTop: curElement.prevAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").on('click',function() {

var elementCur=$(this).parent();
  $('html, body').animate({
      scrollTop: elementCur.nextAll().offset().top
  }, 1000, 'easeInOutSine');
});
</code>```

See Demo

$(".fullcontent--prev").on('click', function() {
  var curElement = $(this).parent();
  $('html, body').animate({
    scrollTop: curElement.prevAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").on('click', function() {

  var elementCur = $(this).parent();
  $('html, body').animate({
    scrollTop: elementCur.nextAll().offset().top
  }, 1000, 'easeInOutSine');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;
  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }
  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
  }
}</code>```

 1

Prev

Next

 2

Prev

Next

 3

Prev

Next

 4

Prev

Next

```

Body:
I have several divs with the class name "fullcontent".
In each div I have 2 elements: "fullcontent--prev" and "fullcontent--next".
On click on this elements I want to scroll to the next/previous fullcontent-div.

But I don't get this working with this:

https://jsfiddle.net/whgxauyd/1/

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;

  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }

  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
    }
}

 1

 2

 3

 4

Where is the error?

Body:
you were not saving the reference to the current element focused
just add the reference like var elementCur=$(this).parent();  for next and var curElement=$(this).parent() for prev like below

$(".fullcontent--prev").on('click',function() {
var curElement=$(this).parent();
  $('html, body').animate({
      scrollTop: curElement.prevAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").on('click',function() {

var elementCur=$(this).parent();
  $('html, body').animate({
      scrollTop: elementCur.nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

See Demo

$(".fullcontent--prev").on('click', function() {
  var curElement = $(this).parent();
  $('html, body').animate({
    scrollTop: curElement.prevAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").on('click', function() {

  var elementCur = $(this).parent();
  $('html, body').animate({
    scrollTop: elementCur.nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;
  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }
  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<section>

  <div class="fullcontent"> 1
    <div class="fullcontent--prev">Prev</div>
    <div class="fullcontent--next">Next</div>
  </div>

  <div class="fullcontent"> 2
    <div class="fullcontent--prev">Prev</div>
    <div class="fullcontent--next">Next</div>
  </div>

  <div class="fullcontent"> 3
    <div class="fullcontent--prev">Prev</div>
    <div class="fullcontent--next">Next</div>
  </div>

  <div class="fullcontent"> 4
    <div class="fullcontent--prev">Prev</div>
    <div class="fullcontent--next">Next</div>
  </div>

</section>