问:
Using || double-pipe inside of a START CMD
Similar to

```<code>CMD /C Do.cmd || goto :error
</code>```

I‘m trying to use the double-pipe as part of a command within a start statement, but i don‘t manage to nest it correctly. I.e. the "on-error" statement runs only when the start-command itself fails (i.e. as part of the caller script). But i want the started sub-process to run it when the main do.cmd fails.

Here is what i‘m trying to run:

```<code>(
      start „parallelproc1“ cmd /c do.cmd || echo 1 > pperror.log
      start „parallelproc2“ cmd /c do.cmd || echo 1 > pperror.log
    ) | pause
    if exist pperror.log goto :error
    Continue.cmd
</code>```

Basically, i only want to continue, if none of the do.cmd of the parallelproc failed. Can i not use || inside start?

答:
You need to tell the parser how to "group" the parts of the command line:

```<code>start "parallelproc1" cmd /c "do.cmd || echo 1 > pperror.log"
</code>```

See cmd /?, especially the part beginning with:

If /C or /K i specified, then the remainder of the command line after
  the switch is processed as a command line, ...

Another way to tell the parser to pass poison characters like | and > to the subprocess is to escape them:

```<code>start "parallelproc1" cmd /c do.cmd ^|^| echo 1 ^> pperror.log
</code>```

(personally, I prefer the first one, but there might be reasons to use the second one in some special cases)

Body:
Similar to

CMD /C Do.cmd || goto :error

I‘m trying to use the double-pipe as part of a command within a start statement, but i don‘t manage to nest it correctly. I.e. the "on-error" statement runs only when the start-command itself fails (i.e. as part of the caller script). But i want the started sub-process to run it when the main do.cmd fails.

Here is what i‘m trying to run:

(
      start „parallelproc1“ cmd /c do.cmd || echo 1 > pperror.log
      start „parallelproc2“ cmd /c do.cmd || echo 1 > pperror.log
    ) | pause
    if exist pperror.log goto :error
    Continue.cmd

Basically, i only want to continue, if none of the do.cmd of the parallelproc failed. Can i not use || inside start?

Body:
You need to tell the parser how to "group" the parts of the command line:

start "parallelproc1" cmd /c "do.cmd || echo 1 > pperror.log"

See cmd /?, especially the part beginning with:

If /C or /K i specified, then the remainder of the command line after
  the switch is processed as a command line, ...

Another way to tell the parser to pass poison characters like | and > to the subprocess is to escape them:

start "parallelproc1" cmd /c do.cmd ^|^| echo 1 ^> pperror.log

(personally, I prefer the first one, but there might be reasons to use the second one in some special cases)


来源: stackexchange

问:
How to get the text cursor position in Windows?
Is it possible to get the overall cursor position in Windows using the standard Python libraries?</p>

答:
Using pyautogui

To install

pip install pyautogui

and to find the location of the mouse pointer

```<code>import pyautogui
print(pyautogui.position())
</code>```

This will give the pixel location to which mouse pointer is at.

ContentLicense: CC BY-SA 4.0

Body:
Using pyautogui

To install

pip install pyautogui

and to find the location of the mouse pointer

import pyautogui
print(pyautogui.position())

This will give the pixel location to which mouse pointer is at.


问:
Bootstrap Table Filter by Multiple Columns
I am using Bootstrap Table by wenzhixin. I need to filter by several columns. For example, I need to filter Countries and then Cities.

I have two select fields for each field in the table (Select Country and Select City).

The way I am doing it right now is I apply filterBy method on change of select option:

```<code>    $('#countries-list').on('change', function (evt) {
        var selectedCountry = $('#countries-list').select2('val');
        if (selectedCountry == "all") {
            $tableFilter.bootstrapTable('filterBy');
        } else {
            $tableFilter.bootstrapTable('filterBy', {country: selectedCountry});
        }
    });

    $('#cities-list').on('change', function (evt) {
        var selectedCity = $('#cities-list').select2('val');
        if (selectedCity == "all") {
            $tableFilter.bootstrapTable('filterBy');
        } else {
            $tableFilter.bootstrapTable('filterBy', {city: selectedCity});
        }
    });
</code>```

The problem is that they overwrite each other. I would appreciate any suggestions on how to apply second filter only to the results of the first one, not to the entire dataset.

Thank you!

答:
Fairly old question but I just struggled with the same thing today and just figured out a solution.

Set needed variables:

```<code>var $table = $('#table-id')
var FilterOptions = {}
</code>```

Create a function to check if a object is empty:

```<code>function isEmpty(obj) {
        for(var key in obj) {
            if(obj.hasOwnProperty(key))
                return false;
        }
        return true;
    }
</code>```

Create a function that will filter the table with the help of our isEmpty() function:

```<code>function FilterTable(){
        if(isEmpty(FilterOptions)){
            $table.bootstrapTable('filterBy', {})
        } else {
            $table.bootstrapTable('filterBy', FilterOptions)
        }
    }
</code>```

Then for each of our select fields we will create a function that adds/change a property to our FilterOptions object depending on what is selected or deletes the property if the default option is selected ("all" in this example). At the end we filter our table with our FilterTable() function.

```<code>$('#Selector_column1_filter').change(function(){
        if ($(this).val() != "all") {
            FilterOptions.column1 = $(this).val();
        } else {
            delete FilterOptions.column1;
        }
        FilterTable();
    })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Bootstrap Table by wenzhixin. I need to filter by several columns. For example, I need to filter Countries and then Cities.

I have two select fields for each field in the table (Select Country and Select City).

The way I am doing it right now is I apply filterBy method on change of select option:

    $('#countries-list').on('change', function (evt) {
        var selectedCountry = $('#countries-list').select2('val');
        if (selectedCountry == "all") {
            $tableFilter.bootstrapTable('filterBy');
        } else {
            $tableFilter.bootstrapTable('filterBy', {country: selectedCountry});
        }
    });

    $('#cities-list').on('change', function (evt) {
        var selectedCity = $('#cities-list').select2('val');
        if (selectedCity == "all") {
            $tableFilter.bootstrapTable('filterBy');
        } else {
            $tableFilter.bootstrapTable('filterBy', {city: selectedCity});
        }
    });

The problem is that they overwrite each other. I would appreciate any suggestions on how to apply second filter only to the results of the first one, not to the entire dataset.

Thank you!

Body:
Fairly old question but I just struggled with the same thing today and just figured out a solution.

Set needed variables:

var $table = $('#table-id')
var FilterOptions = {}

Create a function to check if a object is empty:

function isEmpty(obj) {
        for(var key in obj) {
            if(obj.hasOwnProperty(key))
                return false;
        }
        return true;
    }

Create a function that will filter the table with the help of our isEmpty() function:

function FilterTable(){
        if(isEmpty(FilterOptions)){
            $table.bootstrapTable('filterBy', {})
        } else {
            $table.bootstrapTable('filterBy', FilterOptions)
        }
    }

Then for each of our select fields we will create a function that adds/change a property to our FilterOptions object depending on what is selected or deletes the property if the default option is selected ("all" in this example). At the end we filter our table with our FilterTable() function.

$('#Selector_column1_filter').change(function(){
        if ($(this).val() != "all") {
            FilterOptions.column1 = $(this).val();
        } else {
            delete FilterOptions.column1;
        }
        FilterTable();
    })


问:
can i use dimdim for web based video chat
I want to know how can i have my own web based video chat service similar to gmail chat/video chat.
I have come to know that we can use dimdim open source project for this purpose.

All i want to provide a video chat option to the users, when they are chatting online. similar to commetchat option, though they use tokbox. But i want my own video server to work that way.

.

All replies are welcome.

Best Regards,

James

答: dimdim is bought by salesforce  doesnt look like its opensource anymore: http://www.salesforce.com/company/news-press/press-releases/2011/01/110106.jsp</p>


问:
Is Geopandas fully written in python language?
I have used VegaLite.jl to plot a choropleth map in Julia. And Geopandas to plot the same in Python.

As I want to make a benchmark between both I would like to know if Geopandas has been fully written in Python or if it is just a wrapper?

Thank you

答:
GeoPandas itself is written in pure python, but it depends on fiona, rtree, pyproj and shapely. All of them are using C libraries to do the work. Fiona GDAL, rtree libspatialindex, pyproj PROJ6 and shapely GEOS.

Regarding plotting, GeoPandas uses matplotlib. I see that matplotlib has some C code, but not sure if it is used in this case.


问:
UnboundLocalError: local variable 'csv_file' referenced before assignment
When I run my code I get these errors:

```<code>if not csv_file.name.endswith('.csv'):

</code>```

UnboundLocalError: local variable 'csv_file' referenced before
  assignment

views.py

```<code>import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Profile

# Create your views here.# one parameter named request
def profile_upload(request):    # declaring template
    template = "profile_upload.html"
    data = Profile.objects.all()# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Profile.objects.update_or_create(
                name=column[0],
                email=column[1],
                address=column[2],
                phone=column[3],
                profile=column[4]
            )
        context = {}
        return render(request, template, context)

</code>```

I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong.

答:
scope of variable is limited here , so define the variable with empty at beginning to use it further as:</p>

```<code>csv_file = ''// overwrites Empty if value found in condition
if request.method == "GET":
    csv_file = request.files['file']... //files for FILES as per docs
</code>```

Body:
When I run my code I get these errors:

if not csv_file.name.endswith('.csv'):

UnboundLocalError: local variable 'csv_file' referenced before
  assignment

views.py

import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Profile

# Create your views here.# one parameter named request
def profile_upload(request):    # declaring template
    template = "profile_upload.html"
    data = Profile.objects.all()# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Profile.objects.update_or_create(
                name=column[0],
                email=column[1],
                address=column[2],
                phone=column[3],
                profile=column[4]
            )
        context = {}
        return render(request, template, context)

I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong.

Body:
scope of variable is limited here , so define the variable with empty at beginning to use it further as:

csv_file = ''// overwrites Empty if value found in condition
if request.method == "GET":
    csv_file = request.files['file']... //files for FILES as per docs


问:
Delete empty folders inside working directory
I have number of empty folders inside a working directory. Want to remove those empty folders in R. Can somebody help me out on this.</p>

答:
Assuming the current directory is the one in which you want to delete the empty folders, you can do:</p>

```<code>folders <- list.dirs(recursive = FALSE)
for(folder in folders){
  if(length(dir(folder)) == 0){
    unlink(folder, recursive = TRUE)
  }
}
</code>```

Body:
Assuming the current directory is the one in which you want to delete the empty folders, you can do:

folders <- list.dirs(recursive = FALSE)
for(folder in folders){
  if(length(dir(folder)) == 0){
    unlink(folder, recursive = TRUE)
  }
}


问:
for loop in c# for IDs of controls to read text of textbox
```<code><asp:TextBox ID="PFtxtname1" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname2" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname3" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname4" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname5" runat="server"></asp:TextBox>
.
.
.
<asp:TextBox ID="PFtxtname100" runat="server"></asp:TextBox>
</code>```

I need to create for loop to read all data of txt and save all in string array variable!

```<code>       //string[] arr = new string[100];
        //   for (int i = 0; i < 100; i++)
         //  {
               //arr[i] = (i+1).ToString();
               //i+=1;
               //TextBox mytext = new TextBox();
               //mytext.ID = "PFtxtname" + i;
               //TextBox txtbox = Page.FindControl("PFtxtname"+i) as TextBox;

               //i += 1;
               //arr[i] = txtbox.Text;
          //}
</code>```

答:
you can try this

```<code>//Member variable
var textBox = new TextBox();

public void CreateTextBox(int length)
{
    for (int index = 0; index < length; index++)
    {
            textBox = new TextBox();
            textBox.ID = "PFtxtname" + "_" + index;
            textBox.CssClass = "yourCSSClass";
            textBox.ClientIDMode = ClientIDMode.Static;
            this.Controls.Add(textBox);
     }
}
</code>```

get the textbox values bt  calling getTextBoxValues method

```<code>public string[] getTextBoxValues(int length)
{
        string[] arr = new string[length];
        for (int index = 0; index < length; index++)
        {
            TextBox txtbox = Page.FindControl("PFtxtname_"+ index) as TextBox;
            arr[nRowIndex] = txtbox.value;
        }
        return arr;
}
</code>```

Body:
<asp:TextBox ID="PFtxtname1" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname2" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname3" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname4" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname5" runat="server"></asp:TextBox>
.
.
.
<asp:TextBox ID="PFtxtname100" runat="server"></asp:TextBox>

I need to create for loop to read all data of txt and save all in string array variable!

       //string[] arr = new string[100];
        //   for (int i = 0; i < 100; i++)
         //  {
               //arr[i] = (i+1).ToString();
               //i+=1;
               //TextBox mytext = new TextBox();
               //mytext.ID = "PFtxtname" + i;
               //TextBox txtbox = Page.FindControl("PFtxtname"+i) as TextBox;

               //i += 1;
               //arr[i] = txtbox.Text;
          //}

Body:
you can try this

//Member variable
var textBox = new TextBox();

public void CreateTextBox(int length)
{
    for (int index = 0; index < length; index++)
    {
            textBox = new TextBox();
            textBox.ID = "PFtxtname" + "_" + index;
            textBox.CssClass = "yourCSSClass";
            textBox.ClientIDMode = ClientIDMode.Static;
            this.Controls.Add(textBox);
     }
}

get the textbox values bt  calling getTextBoxValues method

public string[] getTextBoxValues(int length)
{
        string[] arr = new string[length];
        for (int index = 0; index < length; index++)
        {
            TextBox txtbox = Page.FindControl("PFtxtname_"+ index) as TextBox;
            arr[nRowIndex] = txtbox.value;
        }
        return arr;
}


问:
Upload APK in Internal app sharing in Google Play Console but "Item not found"
I have uploaded APK since 24 hours in internal app sharing as a any one can download app from link.
but when try to open that link it's showing "Item not found".

Here is screenshort of Manage testers settings.

I want to do something like any can download app from link(without adding tester accounts)

答:
According to the internal app sharing documentation (See "Troubleshoot issues"), there are many reasons why this could be the case, but they often boil down to the users not being eligible to receive the app in production (e.g. incompatible device, not in the country the app is distributed in, etc.).

Note that we (Play Console team) understand that this is not ideal and are actively working to remove this limitation.


问:
Parameter name conflict with column name in MySQL
The following code works fine when put it outside a function and return 1 if it exists at the table.

```<code> SET @Result = (SELECT (
     CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = 'username') THEN 10
     ELSE 1
END) r);

SELECT @Result;
</code>```

But it returns 10 when I am passing the value 'username' to a function like below

```<code>CREATE DEFINER=`root`@`localhost` FUNCTION `FN_CheckUsername`(
   Username VARCHAR(128)
) RETURNS int
READS SQL DATA
BEGIN
  SET @Result = (SELECT (
    CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = Username) THEN 10
     ELSE 1
    END) r);

RETURN @Result;
END
</code>```

答:
Please try naming your username parameter to the FN_CheckUsername function something other than Username:

```<code>CREATE DEFINER=`root`@`localhost` FUNCTION `FN_CheckUsername`(uname VARCHAR(128))
    RETURNS int
READS SQL DATA
BEGIN
    SET @Result = (SELECT (
        CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = uname)
             THEN 10 ELSE 1 END) r);
    RETURN @Result;
END
</code>```

The parameter and column name could be masking each other, which would result in the exists clause always being true.

Body:
The following code works fine when put it outside a function and return 1 if it exists at the table.

 SET @Result = (SELECT (
     CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = 'username') THEN 10
     ELSE 1
END) r);

SELECT @Result;

But it returns 10 when I am passing the value 'username' to a function like below

CREATE DEFINER=`root`@`localhost` FUNCTION `FN_CheckUsername`(
   Username VARCHAR(128)
) RETURNS int
READS SQL DATA
BEGIN
  SET @Result = (SELECT (
    CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = Username) THEN 10
     ELSE 1
    END) r);

RETURN @Result;
END

Body:
Please try naming your username parameter to the FN_CheckUsername function something other than Username:

CREATE DEFINER=`root`@`localhost` FUNCTION `FN_CheckUsername`(uname VARCHAR(128))
    RETURNS int
READS SQL DATA
BEGIN
    SET @Result = (SELECT (
        CASE WHEN NOT EXISTS(SELECT 1 FROM `Member` WHERE Username = uname)
             THEN 10 ELSE 1 END) r);
    RETURN @Result;
END

The parameter and column name could be masking each other, which would result in the exists clause always being true.


问:
PHP cannot load whole web page
It's strange problem, I apologize for I really can't explain what kind of problem it is.

I can just say what it happen.

I have a php file, it print the html page, I can't copy whole of my code, it's too long, So I just typo a simple version

```<code><html>
// ... some code

$count = 0;
$query = $mysql->query($sql);
while($row = $mysql->fetch_array($query)) {
    // ... some php code

    echo "<div id='id{$count}'>.....lots of html code and some php variable </div>"  // it is a long html code

    echo "<ul id='ul{$count}'> ..... almost the same as above, lost html </ul>"

    echo ...
    echo ...

    // ... some php code

    $count++;

}

// ... lots of other code
</html>
</code>```

Normally, It's not any problem, but this time, it will read about 800 record in the loop, then, it can only load about 80.

I think maybe some error occur, so I try to print something in the loop, then something strange happened.

I add this

var_dump("!@#!@#!@#!@#");

Then, I refresh page, now it can load 96 record (I refresh page serval times, always 96)

Then I change it to
var_dump("!@#!@#!@#!@#$$$$$");

Now it can load 257 record

after that, I try to change the string that I print, very times I change it, the number of record will change, until I use this:var_dump("!@#!@#!@#!@#!@#!@#!@#!@#", $count);. whole page could be loaded.

答:
Some debugging tips:

look into error log (mostly if you use apache2: /var/log/apache2/error

enable direct error output

```<code>ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
</code>```

It totally seems that you are reaching some size limits, and script execution (or data handling) stops at one point, which is reached at 69 - or outputting more chars per record - at 257 records.

Maybe

maximum execution time for a call is exceeded: use set_time_limit

Maximum Size for output is exceeded. Some servers may have one, for example Ngnix.

PHPs memory limit is exceeded.

there is is a limit set for PHPs output buffering  which causes problems. Edit: How  afraid.jpg solved it

I don't think it's about the number of queries or such, but the the mass of output you generate. Otherwise it would not make any difference how big your var_dump dummy is.

Title: PHP cannot load whole web page

Body:
It's strange problem, I apologize for I really can't explain what kind of problem it is.

I can just say what it happen.

I have a php file, it print the html page, I can't copy whole of my code, it's too long, So I just typo a simple version

// ... some code

$count = 0;
$query = $mysql->query($sql);
while($row = $mysql->fetch_array($query)) {
    // ... some php code

    echo "
.....lots of html code and some php variable
"  // it is a long html code

    echo "
 ..... almost the same as above, lost html
"

    echo ...
    echo ...

    // ... some php code

    $count++;

}

// ... lots of other code

Normally, It's not any problem, but this time, it will read about 800 record in the loop, then, it can only load about 80.

I think maybe some error occur, so I try to print something in the loop, then something strange happened.

I add this

var_dump("!@#!@#!@#!@#");

Then, I refresh page, now it can load 96 record (I refresh page serval times, always 96)

Then I change it to
var_dump("!@#!@#!@#!@#$$$$$");

Now it can load 257 record

after that, I try to change the string that I print, very times I change it, the number of record will change, until I use this:var_dump("!@#!@#!@#!@#!@#!@#!@#!@#", $count);. whole page could be loaded.

Body:
Some debugging tips:

look into error log (mostly if you use apache2: /var/log/apache2/error

enable direct error output

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

It totally seems that you are reaching some size limits, and script execution (or data handling) stops at one point, which is reached at 69 - or outputting more chars per record - at 257 records.

Maybe

maximum execution time for a call is exceeded: use set_time_limit

Maximum Size for output is exceeded. Some servers may have one, for example Ngnix.

PHPs memory limit is exceeded.

there is is a limit set for PHPs output buffering  which causes problems. Edit: How  afraid.jpg solved it

I don't think it's about the number of queries or such, but the the mass of output you generate. Otherwise it would not make any difference how big your var_dump dummy is.


问:
Send and run multiple lines of Python to a visible running python/bpython/ipython interpreter process
I am running a full-screen tmux, split into two panes.  The left pane runs vim, where I edit Python files.  The right pane runs a Python interpreter.

I would like to be able to highlight multiple lines in vim (Shift+V), then using some shortcut key, send these lines to the running Python interpreter on the other pane.

Is there some vim plugin that does this?

This functionality is similar to that in Spyder, where you can highlight multiple lines, right-click, then send those lines to the active interpreter within Spyder.  I hesitate moving to Spyder because my muscle memory is already heavily invested in vim and tmux (keeping hands on the keyboard and all that).

答:
You probaly want vimux : https://github.com/benmills/vimux

From the documentation:

" If text is selected, save it in the v buffer and send that buffer
  it to tmux:

vmap <LocalLeader>vs "vy :call VimuxSlime()<CR>


问:
Best way to add items to ReadOnlyCollection<T> internally (within the same assembly)?
I have the following class:

```<code>public class Foo
{
     public List<Bar> Bars {get; internal set;}
}
</code>```

Now I want to make Bars a ReadOnlyCollection so that the contents of Bars can't be changed publicly:

```<code>public class Foo
{
     public ReadOnlyCollection<Bar> Bars {get; internal set;}
}
</code>```

Now if I have a class within the same assembly that needs to add items to Bars, what is the best way to do this?

This is how I am doing it now:

```<code>public class FooHelper
{
   public FooHelper()
   {
      Foo foo = new Foo();
      //Code to modify the collection
      List<Bar> bars = foo.Bars.ToList<Bar>();
      bars.Add(new Bar("BAR BAR BAR"));
      foo.Bars = bars.AsReadOnly();
   }
}
</code>```

I realized that it would be easier if I have a Private List<Bar> in Foo like so:

```<code>public class Foo
{
     private List<Bar> _bars;
     public ReadOnlyCollection<Bar> Bars {get { return _bars.AsReadOnly; }}
}
</code>```

... but with this approach, how would I add an item to _bars?

Should I make it Internal, make it an Internal Property, or add a new Internal AddBar() method?

答:
Personally I would go for adding an internal AddBar method, like so:

```<code>public class Foo
{
     private List<Bar> _bars;

     public ReadOnlyCollection<Bar> Bars {get { return _bars.AsReadOnly; }}

     internal void AddBar(Bar bar)
     {
          _bars.Add(bar);
     }
}
</code>```

other assemblies will see the readonly collection, making it immutable. Code within the same assembly will only be able to add Bar items, giving you a 'defensive' API.

Body:
I have the following class:

public class Foo
{
     public List<Bar> Bars {get; internal set;}
}

Now I want to make Bars a ReadOnlyCollection so that the contents of Bars can't be changed publicly:

public class Foo
{
     public ReadOnlyCollection<Bar> Bars {get; internal set;}
}

Now if I have a class within the same assembly that needs to add items to Bars, what is the best way to do this?

This is how I am doing it now:

public class FooHelper
{
   public FooHelper()
   {
      Foo foo = new Foo();
      //Code to modify the collection
      List<Bar> bars = foo.Bars.ToList<Bar>();
      bars.Add(new Bar("BAR BAR BAR"));
      foo.Bars = bars.AsReadOnly();
   }
}

I realized that it would be easier if I have a Private List<Bar> in Foo like so:

public class Foo
{
     private List<Bar> _bars;
     public ReadOnlyCollection<Bar> Bars {get { return _bars.AsReadOnly; }}
}

... but with this approach, how would I add an item to _bars?

Should I make it Internal, make it an Internal Property, or add a new Internal AddBar() method?

Body:
Personally I would go for adding an internal AddBar method, like so:

public class Foo
{
     private List<Bar> _bars;

     public ReadOnlyCollection<Bar> Bars {get { return _bars.AsReadOnly; }}

     internal void AddBar(Bar bar)
     {
          _bars.Add(bar);
     }
}

other assemblies will see the readonly collection, making it immutable. Code within the same assembly will only be able to add Bar items, giving you a 'defensive' API.


问:
Azure- update function code in Function App using CLI
I want to update the code in one of the functions in my Function App using CLI.
I can't find the appropriate command to do so using az functionapp.
What is the best wat yo do this, not using the portal?

答:
If you want to update Function App , you can use the CLI command,

```<code>az functionapp update --name MyFunctionApp --resource-group MyResourceGroup
</code>```

However best practice is to automate by using Azure Devops or GithubActions

Body:
If you want to update Function App , you can use the CLI command,

az functionapp update --name MyFunctionApp --resource-group MyResourceGroup

However best practice is to automate by using Azure Devops or GithubActions


问:
Eclipse not recognizing Gradle dependencies
I am new to Gradle and I was trying this tutorial https://spring.io/guides/gs/rest-service/
I was able to compile the jar with the required dependencies and run it.
However, I find it annoying that the libraries are not recognized by the IDE.

Is there anyway to do it?

答: I have had this problem importing Gradle projects from TFS. Unless the initial import uses the Gradle importer the build.gradle will not be setup. You have to remove the project from the Eclipse workspace (do not delete on disk) and then import the project again as a Gradle project. This updates the build path according to build.gradle


答:
You are getting this error because variable is defined only if request method is GET. Else if method is POST you didn't define it but try to use here:

```<code>if not csv_file.name.endswith('.csv'):
</code>```

Also, it's possible to make this code fail because you defined this variable as a request.FILES['file'], where there could be no file in request. You can change this to:

```<code>csv_file = request.FILES.get('file')
if not csv_file:
    # raise error
</code>```

And finally it's better way to use serializers or forms to validate request data.

Title: UnboundLocalError: local variable 'csv_file' referenced before assignment

Body:
You are getting this error because variable is defined only if request method is GET. Else if method is POST you didn't define it but try to use here:

if not csv_file.name.endswith('.csv'):

Also, it's possible to make this code fail because you defined this variable as a request.FILES['file'], where there could be no file in request. You can change this to:

csv_file = request.FILES.get('file')
if not csv_file:
    # raise error

And finally it's better way to use serializers or forms to validate request data.


问:
How to create an SQL Server 2008 database from script
I'm trying to do an Entity Framework walkthrough so I:

downloaded SQL script here: http://www.learnentityframework.com

in SQL Server Management Studio, I right-clicked Database, Create Database, named it

right-clicked on the new database, New Query

clicked on "Open File" and opened the script file: Create_ProgrammingEFDB1_SQLServer2008.sql

clicked "! Execute"

But the script (756K) has been running for 10 minutes now and still says "executing..."

My questions are:

Is this the standard way to read in an SQL script into SQL Server?

Is it supposed to take this long? This is how I would do it in MySQL/PHPMyAdmin it it might take a couple seconds, so I assume I'm not doing something right.

Here is the beginning of the script, I changed the file paths so they point to the right .mdf and .ldf files:

```<code>****/

--PART ONE  CREATE THE DATABASE. Note the file paths in the first few commands.
--Change them for your own computer.--
USE [master]
GO

    /****** Object:  Database [ProgrammingEFDB1]    Script Date: 01/28/2009 10:17:44 ******/
    CREATE DATABASE [ProgrammingEFDB1] ON  PRIMARY
    ( NAME = N'ProgrammingEFDB1', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1.mdf' , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
     LOG ON
    ( NAME = N'ProgrammingEFDB1_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1_log.LDF' , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
    GO

    ALTER DATABASE [ProgrammingEFDB1] SET COMPATIBILITY_LEVEL = 90
    GO

    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
    begin
    EXEC [ProgrammingEFDB1].[dbo].[sp_fulltext_database] @action = 'disable'
    end
    ...
</code>```

ANSWER:

I had already created a database with the same name so it was trying to create a database that was already there which made it hang for some reason. I deleted that database, reran the script and it completed successfully in 3 seconds.

答:
But the script (756K)

Must be a lot more than just a CREATE DATABASE in the script, so very hard to say when the script is doing.

You can write progress reports from the script back to the client, or use SQL Profiler to see what commands are being executed.

OwnerDisplayName: Edward Tanguay

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to do an Entity Framework walkthrough so I:

downloaded SQL script here: http://www.learnentityframework.com

in SQL Server Management Studio, I right-clicked Database, Create Database, named it

right-clicked on the new database, New Query

clicked on "Open File" and opened the script file: Create_ProgrammingEFDB1_SQLServer2008.sql

clicked "! Execute"

But the script (756K) has been running for 10 minutes now and still says "executing..."

My questions are:

Is this the standard way to read in an SQL script into SQL Server?

Is it supposed to take this long? This is how I would do it in MySQL/PHPMyAdmin it it might take a couple seconds, so I assume I'm not doing something right.

Here is the beginning of the script, I changed the file paths so they point to the right .mdf and .ldf files:

****/

--PART ONE  CREATE THE DATABASE. Note the file paths in the first few commands.
--Change them for your own computer.--
USE [master]
GO

    /****** Object:  Database [ProgrammingEFDB1]    Script Date: 01/28/2009 10:17:44 ******/
    CREATE DATABASE [ProgrammingEFDB1] ON  PRIMARY
    ( NAME = N'ProgrammingEFDB1', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1.mdf' , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
     LOG ON
    ( NAME = N'ProgrammingEFDB1_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\ProgrammingEFDB1_log.LDF' , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
    GO

    ALTER DATABASE [ProgrammingEFDB1] SET COMPATIBILITY_LEVEL = 90
    GO

    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
    begin
    EXEC [ProgrammingEFDB1].[dbo].[sp_fulltext_database] @action = 'disable'
    end
    ...

ANSWER:

I had already created a database with the same name so it was trying to create a database that was already there which made it hang for some reason. I deleted that database, reran the script and it completed successfully in 3 seconds.

LastEditorDisplayName: Edward Tanguay

OwnerDisplayName: Richard


问:
html,JS search field list
I'm new to JS but have good knowledge in C and HTML and want to create a search box so that when I write something, a drop-down list appears with some results. I already have the code to create the animated search field (which is not mine) and the code to create this search filter list but I don't know how to "connect" them.

Here is the JS part for the search bar filter: (To use it you just need this html code
<input type="text" id="searchInput" placeholder="Search article"/> here is the fiddle: https://jsfiddle.net/c30L5esq/)

```<code>$("#searchInput").on('keyup', function() {
  var searchValue = $(this).val().toUpperCase();
  if(searchValue.length > 0) {
    searchAndFilter(searchValue);
  } else {
    $("#articlesearch li").hide();
  }
});

function searchAndFilter(searchTerm) {
  $("#articlesearch li").each(function() {
    var currentText = $(this).text().toUpperCase();
    if (currentText.indexOf(searchTerm) >= 0) {
      $(this).show();
    } else {
        $(this).hide();
    }
  });
}

$(document).ready(function() {
  $("#articlesearch li").hide();
});
</code>```

And here it is the link for the search bar fullscreen animation :
https://codepen.io/suez/pen/obpLvy/

And what I want is that when I use this search bar animation, I can actually search through a list and it will show me results that match what I typed in a dropdown.

Thank you !

答:
I think you are looking for is autocomplete for search input. For that we have to use typeahead.js plugin. You can go with the link on the plugin and Codepen example link. There are multiple example demos in the link.

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];

$('#the-basics .typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.jquery.min.js"></script></code>```

Title: html,JS search field list

Body:
I'm new to JS but have good knowledge in C and HTML and want to create a search box so that when I write something, a drop-down list appears with some results. I already have the code to create the animated search field (which is not mine) and the code to create this search filter list but I don't know how to "connect" them.

Here is the JS part for the search bar filter: (To use it you just need this html code
<input type="text" id="searchInput" placeholder="Search article"/> here is the fiddle: https://jsfiddle.net/c30L5esq/)

$("#searchInput").on('keyup', function() {
  var searchValue = $(this).val().toUpperCase();
  if(searchValue.length > 0) {
    searchAndFilter(searchValue);
  } else {
    $("#articlesearch li").hide();
  }
});

function searchAndFilter(searchTerm) {
  $("#articlesearch li").each(function() {
    var currentText = $(this).text().toUpperCase();
    if (currentText.indexOf(searchTerm) >= 0) {
      $(this).show();
    } else {
        $(this).hide();
    }
  });
}

$(document).ready(function() {
  $("#articlesearch li").hide();
});

And here it is the link for the search bar fullscreen animation :
https://codepen.io/suez/pen/obpLvy/

And what I want is that when I use this search bar animation, I can actually search through a list and it will show me results that match what I typed in a dropdown.

Thank you !

Body:
I think you are looking for is autocomplete for search input. For that we have to use typeahead.js plugin. You can go with the link on the plugin and Codepen example link. There are multiple example demos in the link.

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];

$('#the-basics .typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});

<div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.jquery.min.js"></script>


问:
JSP cannot resolve Servlet data object by using JSTL, IntelliJ IDE
i am now learning the basics of MVC based on servlet and .jsp;
but when i tried to have a simple test, IntelliJ gave me warning on items="${}" of such:"This inspection reports possible EL problems, such as unresolved references and invalid EL locations";

i checked my servlet configuration in web.xml; checked the path of my .jsp file is in root, but it just doesn't work;

here's my code:

--TestView.jsp

```<code><%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>
    <title>test view</title>
</head>
<body>
    <c:forEach var="templist" items = "${mystringlist}">
        ${templist} <br/>
    </c:forEach>
</body>
</code>```

--TestServlet.java

```<code>import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "TestServlet")
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String[] list = {"aaa","bbb","ccc","ddd","eee"};
    request.setAttribute("mystringlist", list);
    RequestDispatcher dispatcher = request.getRequestDispatcher("/TestView.jsp");
    dispatcher.forward(request,response);
    }
}
</code>```

--web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.gpwz.labExcercise.TestServlet</servlet-class>
    </servlet>

<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</code>```

Any advice? I searched a lot, but none of them can solve this issue...

答:
I meet this prooblem in other way,but i can`t fix it.

I was learning SpringMVC Hello world program,and finish copy code(the maven.pom..)then I find I can`t get the EL data.Same time SpringMVC ModelAndView has problem in the setViewName()

I put my mouse on this function, the hit is

No view resolvers found Checks if Spring MVC View references are
  resolved correctly._from IntelliJ IDE

I think maybe is some ModelAndView mapping mistake that i can`t let data go JSP

I also use the Google F12 want to look some thing,Nothing i find:(

Body:
i am now learning the basics of MVC based on servlet and .jsp;
but when i tried to have a simple test, IntelliJ gave me warning on items="${}" of such:"This inspection reports possible EL problems, such as unresolved references and invalid EL locations";

i checked my servlet configuration in web.xml; checked the path of my .jsp file is in root, but it just doesn't work;

here's my code:

--TestView.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

    <title>test view</title>

    <c:forEach var="templist" items = "${mystringlist}">
        ${templist}

    </c:forEach>

--TestServlet.java

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "TestServlet")
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String[] list = {"aaa","bbb","ccc","ddd","eee"};
    request.setAttribute("mystringlist", list);
    RequestDispatcher dispatcher = request.getRequestDispatcher("/TestView.jsp");
    dispatcher.forward(request,response);
    }
}

--web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.gpwz.labExcercise.TestServlet</servlet-class>
    </servlet>

<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
</servlet-mapping>

Any advice? I searched a lot, but none of them can solve this issue...


问:
Adding attribute on root element of XML
I have a class which is adding attribute to the all other elements except the root element of the XML File. C# Class is as follows

```<code>[XmlRoot(ElementName = "bd", Namespace = "http://www.fca.com/ifast")]
public class Bd
{
    [XmlElement(ElementName = "msg", Namespace = "http://www.fca.com/ifast")]
    public Msg Msg { get; set; }
}

[XmlRoot(ElementName = "tr", Namespace = "http://www.fca.com/ifast")]
public class Tr
{
    [XmlElement(ElementName = "hd", Namespace = "http://www.fca.com/ifast")]
    public Hd Hd { get; set; }
    [XmlElement(ElementName = "bd", Namespace = "http://www.fca.com/ifast")]
    public Bd Bd { get; set; }
    [XmlAttribute(AttributeName = "if", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string If { get; set; }
}
</code>```

With this code i am able to generate XML file like this

```<code>'<?xml version="1.0" encoding="utf-16"?>
<tr xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance" xmlns:if="http://www.fca.com/ifast" xmlns="http://www.fca.com/ifast">
<if:hd>
</if:hd>
<if:bd>
</if:bd>
</tr>'
</code>```

But i need to add 'if:' element on root element as well like this

```<code><?xml version="1.0" encoding="utf-16"?>
<if:tr xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance" xmlns:if="http://www.fca.com/ifast" xmlns="http://www.fca.com/ifast">
<if:hd>
</if:hd>
<if:bd>
</if:bd>
</if:tr>
</code>```

答:
The xmlns:if attribute is a namespace declaration. These are special attributes and shouldn't be specified explicitly as properties as you've done here - the serialiser will handle this for you.

I'd also note that namespaces are inherited from their parents, so most of the places you've specified the namespace aren't required. You also only need an XmlRoot attribute on the root. This should be enough:

public class Bd
{
    [XmlElement("msg")]
    public Msg Msg { get; set; }
}

[XmlRoot("tr", Namespace = "http://www.fca.com/ifast")]
public class Tr
{
    [XmlElement("hd")]
    public Hd Hd { get; set; }
    [XmlElement("bd")]
    public Bd Bd { get; set; }
}
```

<p>The two bits of XML you've included are semantically the same thing, but if you want to control the namespace prefix you can do this on serialisation:</p>

<pre class="lang-cs prettyprint-override"><code>var ns = new XmlSerializerNamespaces();
ns.Add("if", "http://www.fca.com/ifast");

var serializer = new XmlSerializer(typeof(Tr));

serializer.Serialize(stream, obj, ns);
</code>```

See this fiddle for a working demo.

Title: Adding attribute on root element of XML

Body:
I have a class which is adding attribute to the all other elements except the root element of the XML File. C# Class is as follows

[XmlRoot(ElementName = "bd", Namespace = "http://www.fca.com/ifast")]
public class Bd
{
    [XmlElement(ElementName = "msg", Namespace = "http://www.fca.com/ifast")]
    public Msg Msg { get; set; }
}

[XmlRoot(ElementName = "tr", Namespace = "http://www.fca.com/ifast")]
public class Tr
{
    [XmlElement(ElementName = "hd", Namespace = "http://www.fca.com/ifast")]
    public Hd Hd { get; set; }
    [XmlElement(ElementName = "bd", Namespace = "http://www.fca.com/ifast")]
    public Bd Bd { get; set; }
    [XmlAttribute(AttributeName = "if", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string If { get; set; }
}

With this code i am able to generate XML file like this

'<?xml version="1.0" encoding="utf-16"?>

<if:hd>
</if:hd>
<if:bd>
</if:bd>

'

But i need to add 'if:' element on root element as well like this

<?xml version="1.0" encoding="utf-16"?>
<if:tr xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema
instance" xmlns:if="http://www.fca.com/ifast" xmlns="http://www.fca.com/ifast">
<if:hd>
</if:hd>
<if:bd>
</if:bd>
</if:tr>

Body:
The xmlns:if attribute is a namespace declaration. These are special attributes and shouldn't be specified explicitly as properties as you've done here - the serialiser will handle this for you.

I'd also note that namespaces are inherited from their parents, so most of the places you've specified the namespace aren't required. You also only need an XmlRoot attribute on the root. This should be enough:

public class Bd
{
    [XmlElement("msg")]
    public Msg Msg { get; set; }
}

[XmlRoot("tr", Namespace = "http://www.fca.com/ifast")]
public class Tr
{
    [XmlElement("hd")]
    public Hd Hd { get; set; }
    [XmlElement("bd")]
    public Bd Bd { get; set; }
}

The two bits of XML you've included are semantically the same thing, but if you want to control the namespace prefix you can do this on serialisation:

var ns = new XmlSerializerNamespaces();
ns.Add("if", "http://www.fca.com/ifast");

var serializer = new XmlSerializer(typeof(Tr));

serializer.Serialize(stream, obj, ns);

See this fiddle for a working demo.


问:
Deploying a kubernetes pods after a job is completed - helm
Goal - Start deployment of pod when a particular jobs in completed using helm.

Currently I am using helm to deploy the configmap/pods/jobs. When I do "helm install" everything get deployed at the same time.
Can I add delay/trigger saying when a particular jobs is completed then only deploy other pods.

I tried using "init container" but it difficult to get status of job in "init container"

答:
Helm chart hooks can do this.  There's a series of points where Helm can deploy a set of resources one at a time and wait for them to be ready or completed.

For what you're describing, it is enough to use an annotation to mark a job as a pre-install hook:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  annotations:
    "helm.sh/hook": pre-install
</code>```

None of the other resources in the chart will be deployed until the hook executes successfully.  If the Job fails, it will block deploying any other resources.  This pre-install hook only runs on first installation, but if you want the hook to run on upgrades or rollbacks, there are corresponding hooks to be able to do this.

There are still some workflows that are hard to express this way.  For instance, if your service includes a database and you want a job to run migrations or seed data, you can't really deploy the database StatefulSet, then block on a Job hook, then deploy everything else; your application still needs to tolerate things maybe not being in the exact state it expects.

Body:
Helm chart hooks can do this.  There's a series of points where Helm can deploy a set of resources one at a time and wait for them to be ready or completed.

For what you're describing, it is enough to use an annotation to mark a job as a pre-install hook:

apiVersion: batch/v1
kind: Job
metadata:
  annotations:
    "helm.sh/hook": pre-install

None of the other resources in the chart will be deployed until the hook executes successfully.  If the Job fails, it will block deploying any other resources.  This pre-install hook only runs on first installation, but if you want the hook to run on upgrades or rollbacks, there are corresponding hooks to be able to do this.

There are still some workflows that are hard to express this way.  For instance, if your service includes a database and you want a job to run migrations or seed data, you can't really deploy the database StatefulSet, then block on a Job hook, then deploy everything else; your application still needs to tolerate things maybe not being in the exact state it expects.


问:
Go to Top of page on button click in Angular 2
Want to go to top of the page on button click , Currently I using following code which is not working :

HTML:

```<code><button md-raised-button class="md-raised md-primary" (click)="onEdit()">Edit</button>
</code>```

Function:

```<code>onEdit(){
    window.scrollTo(0,0);
  }
</code>```

答:
The Right way is to use the DOCUMENT DI Token

Import it

```<code>import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
</code>```

Inject DOCUMENT

```<code>constructor(@Inject(DOCUMENT) private dom: Document) {
}
</code>```

And then you can call

```<code>this.dom.body.scrollTop =0;
this.dom.documentElement.scrollTop=0;
</code>```

This also works in SSR (Angular Universal)

Body:
Want to go to top of the page on button click , Currently I using following code which is not working :

HTML:

<button md-raised-button class="md-raised md-primary" (click)="onEdit()">Edit</button>

Function:

onEdit(){
    window.scrollTo(0,0);
  }

Body:
The Right way is to use the DOCUMENT DI Token

Import it

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

Inject DOCUMENT

constructor(@Inject(DOCUMENT) private dom: Document) {
}

And then you can call

this.dom.body.scrollTop =0;
this.dom.documentElement.scrollTop=0;

This also works in SSR (Angular Universal)


问:
Simple Traefik reverse proxy configuration
I'm starting up Traefik version 2.1.4 with the following configuration:

```<code>defaultEntryPoints:
  - http

entryPoints:
  hole-1:
    address: ':663'

frontends:
  hole-frontend-1:
    backend: hole-backend-1
    entrypoints:
      - hole-1

backends:
  hole-backend-1:
    servers:
      hole-server-1:
        url: 'http://11.23.24.1:3000'
        weight: 10
</code>```

When I hit the http://11.23.24.1:663 I'm hit with the Traefik page 404 pages not found. When I go to http://11.23.24.1:3000 in the browser, it works, it displays the page.

I can't seem to figure out how to set up a reverse proxy in Traefik to point http://11.23.24.1:663 to http://11.23.24.1:3000.

I tried this, but I get the error

2020/02/18 11:39:43 command traefik.exe error: no valid configuration found in file: C:\config\traefik.yaml

```<code>http:
  routers:
    hole-router-1:
      rule: "Host(`11.23.24.1`) && PathPrefix(`/`)"
      service: hole-service

services:
  hole-service:
    loadBalancer:
      servers:
        - url: http://11.23.24.1:3000
</code>```

答:
Traefik 2.1 do not support frontend and backends any more.
This repository provides some examples to deploy Traefik 2.1 https://github.com/wshihadeh/traefik_v2

Example to do it with Docker:

```<code>version: '3.7'

networks:
  traefik:
    external: true

volumes:
  db_data:

services:

  proxy:
    image: traefik:v2.1
    command:
      - '--providers.docker=true'
      - '--entryPoints.http.address=:80'
      - '--providers.providersThrottleDuration=2s'
      - '--providers.docker.watch=true'
      - '--providers.docker.exposedbydefault=false'
      - '--providers.docker.defaultRule=Host("local.me")'
      - '--accessLog.bufferingSize=0'
    volumes:
      - '/var/run/docker.sock:/var/run/docker.sock:ro'
    ports:
      - '663:80'
    deploy:
      restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 120s
      update_config:
        delay: 10s
        order: start-first
        parallelism: 1
      rollback_config:
        parallelism: 0
        order: stop-first
    logging:
      driver: json-file
      options:
        'max-size': '10m'
        'max-file': '5'
    networks:
      - traefik

   hole-backend:
    image:  hole-backend:demo-v1
    command: 'web'
    deploy:
      labels:
        - traefik.enable=true
        - traefik.http.services.hole.loadbalancer.server.port=8080
        - traefik.http.routers.hole.rule=Host(`hole.local.me`)
        - traefik.http.routers.hole.service=blog
        - traefik.http.routers.hole.entrypoints=web
        - traefik.docker.network=traefik
      restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 120s
      update_config:
        delay: 10s
        order: start-first
        parallelism: 1
      rollback_config:
        parallelism: 0
        order: stop-first
    logging:
      driver: json-file
      options:
        'max-size': '10m'
        'max-file': '5'
    networks:
      - traefik
</code>```

Body:
I'm starting up Traefik version 2.1.4 with the following configuration:

defaultEntryPoints:
  - http

entryPoints:
  hole-1:
    address: ':663'

frontends:
  hole-frontend-1:
    backend: hole-backend-1
    entrypoints:
      - hole-1

backends:
  hole-backend-1:
    servers:
      hole-server-1:
        url: 'http://11.23.24.1:3000'
        weight: 10

When I hit the http://11.23.24.1:663 I'm hit with the Traefik page 404 pages not found. When I go to http://11.23.24.1:3000 in the browser, it works, it displays the page.

I can't seem to figure out how to set up a reverse proxy in Traefik to point http://11.23.24.1:663 to http://11.23.24.1:3000.

I tried this, but I get the error

2020/02/18 11:39:43 command traefik.exe error: no valid configuration found in file: C:\config\traefik.yaml

http:
  routers:
    hole-router-1:
      rule: "Host(`11.23.24.1`) && PathPrefix(`/`)"
      service: hole-service

services:
  hole-service:
    loadBalancer:
      servers:
        - url: http://11.23.24.1:3000

Body:
Traefik 2.1 do not support frontend and backends any more.
This repository provides some examples to deploy Traefik 2.1 https://github.com/wshihadeh/traefik_v2

Example to do it with Docker:

version: '3.7'

networks:
  traefik:
    external: true

volumes:
  db_data:

services:

  proxy:
    image: traefik:v2.1
    command:
      - '--providers.docker=true'
      - '--entryPoints.http.address=:80'
      - '--providers.providersThrottleDuration=2s'
      - '--providers.docker.watch=true'
      - '--providers.docker.exposedbydefault=false'
      - '--providers.docker.defaultRule=Host("local.me")'
      - '--accessLog.bufferingSize=0'
    volumes:
      - '/var/run/docker.sock:/var/run/docker.sock:ro'
    ports:
      - '663:80'
    deploy:
      restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 120s
      update_config:
        delay: 10s
        order: start-first
        parallelism: 1
      rollback_config:
        parallelism: 0
        order: stop-first
    logging:
      driver: json-file
      options:
        'max-size': '10m'
        'max-file': '5'
    networks:
      - traefik

   hole-backend:
    image:  hole-backend:demo-v1
    command: 'web'
    deploy:
      labels:
        - traefik.enable=true
        - traefik.http.services.hole.loadbalancer.server.port=8080
        - traefik.http.routers.hole.rule=Host(`hole.local.me`)
        - traefik.http.routers.hole.service=blog
        - traefik.http.routers.hole.entrypoints=web
        - traefik.docker.network=traefik
      restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 120s
      update_config:
        delay: 10s
        order: start-first
        parallelism: 1
      rollback_config:
        parallelism: 0
        order: stop-first
    logging:
      driver: json-file
      options:
        'max-size': '10m'
        'max-file': '5'
    networks:
      - traefik


问:
Return inserted row
How do I return the row I just inserted including DB-generated identifier?
My SQL is just a standard dynamic SQL insert

```<code>insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2);
</code>```

I have tried select from inserted, but inserted object is not a known object

```<code>insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2); select * from inserted;
</code>```

I have tried using output, but I cannot do that, when there is a trigger on the table

```<code>insert into dbo.TableName (Col1, Col2) output inserted.* values (@Col1, @Col2);
</code>```

Any ideas?

答:
There is no way to ask SQL Server which row was inserted last unless you are doing so in the same batch as the insert. For example, if your table has an IDENTITY column, you can use SCOPE_IDENTITY() (never use @@IDENTITY, since that can be unreliable if you have or will ever add triggers to the source table):

```<code>INSERT dbo.table(column) SELECT 1;
SELECT SCOPE_IDENTITY();
</code>```

More generally, you can use the OUTPUT clause, which doesn't rely on an IDENTITY column (but will still make it difficult to identify which row(s) the clause identifies if there is no PK):

```<code>INSERT dbo.table(column) OUTPUT inserted.* SELECT 1;
</code>```

If you're not talking about the same batch, then the only real way to identify the last row inserted is to use a date/time column where the timestamp of insertion is recorded. Otherwise it is like you emptied a bag of marbles on the floor, then asked someone to enter the room and identify which one hit the floor last.

You may be tempted or even advised to use the IDENT_CURRENT() function, but I explain here why this is unreliable too.

You could add a column to track this going forward:

```<code>ALTER TABLE dbo.table ADD DateInserted DEFAULT CURRENT_TIMESTAMP;
</code>```

Now you can find the last row(s) inserted by simply:

```<code>;WITH x AS (SELECT *, r = RANK() OVER (ORDER BY DateInserted DESC)
   FROM dbo.table)
SELECT * FROM x WHERE r = 1;
</code>```

(If you don't want ties, you can add a tie-breaking column to the ORDER BY, or you can simply change RANK() to ROW_NUMBER() if you don't care which of the tied rows you get.)

You might make the assumption that the last row inserted is the highest identity value, but this isn't necessarily the case. The identity can be reseeded and it can also be overridden using SET IDENTITY_INSERT ON;.

Title: Return inserted row

Body:
How do I return the row I just inserted including DB-generated identifier?
My SQL is just a standard dynamic SQL insert

insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2);

I have tried select from inserted, but inserted object is not a known object

insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2); select * from inserted;

I have tried using output, but I cannot do that, when there is a trigger on the table

insert into dbo.TableName (Col1, Col2) output inserted.* values (@Col1, @Col2);

Any ideas?

Body:
There is no way to ask SQL Server which row was inserted last unless you are doing so in the same batch as the insert. For example, if your table has an IDENTITY column, you can use SCOPE_IDENTITY() (never use @@IDENTITY, since that can be unreliable if you have or will ever add triggers to the source table):

INSERT dbo.table(column) SELECT 1;
SELECT SCOPE_IDENTITY();

More generally, you can use the OUTPUT clause, which doesn't rely on an IDENTITY column (but will still make it difficult to identify which row(s) the clause identifies if there is no PK):

INSERT dbo.table(column) OUTPUT inserted.* SELECT 1;

If you're not talking about the same batch, then the only real way to identify the last row inserted is to use a date/time column where the timestamp of insertion is recorded. Otherwise it is like you emptied a bag of marbles on the floor, then asked someone to enter the room and identify which one hit the floor last.

You may be tempted or even advised to use the IDENT_CURRENT() function, but I explain here why this is unreliable too.

You could add a column to track this going forward:

ALTER TABLE dbo.table ADD DateInserted DEFAULT CURRENT_TIMESTAMP;

Now you can find the last row(s) inserted by simply:

;WITH x AS (SELECT *, r = RANK() OVER (ORDER BY DateInserted DESC)
   FROM dbo.table)
SELECT * FROM x WHERE r = 1;

(If you don't want ties, you can add a tie-breaking column to the ORDER BY, or you can simply change RANK() to ROW_NUMBER() if you don't care which of the tied rows you get.)

You might make the assumption that the last row inserted is the highest identity value, but this isn't necessarily the case. The identity can be reseeded and it can also be overridden using SET IDENTITY_INSERT ON;.


问:
php mysql select not working on field "name"
I know it's strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can't see anything strange.

Any suggestion that could help me investigate is welcome :(

```<code>class go {
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){
           throw new Exception('No Results');
       }

       $out = array();

       while ($r = $results->fetch_object()){
           $out[] = $r;
       }

       return json_encode($out);

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10";
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10";

$data = $client->Query( $sql );
</code>```

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é

答:
Solved with
mysqli_set_charset($db, "utf8");</p>

Body:
I know it's strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can't see anything strange.

Any suggestion that could help me investigate is welcome :(

class go {
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){
           throw new Exception('No Results');
       }

       $out = array();

       while ($r = $results->fetch_object()){
           $out[] = $r;
       }

       return json_encode($out);

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10";
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10";

$data = $client->Query( $sql );

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é


问:
Help with Undefined index and Undefined variable
Could somebody help me with this problem. I just trasferred my PHP/MYSQL program to another computer (both are running XAMPP and on localhost) and now I got a massive amount of Undefined index and Undefined variable ERRORS. Could somebody explain me why?

All the variables are checked with isset and all the values should be OK, but I can't get anything to work as it is supposed to and then there are the Undefined index and Undefined variable ERRORS.

Please Help!
Thanks

答:
The other answers help you fix the symptom, not the problem. You are not getting errors, just notices, it's a special error level that warns you of a possible problem, but does not stop execution.

Given php's nature of not needing to declare variables, it is very easy to make a spelling mistake in your code and spend yours tracking it down (I'm sure everyone has did it at least a few times). And there comes E_NOTICE to the rescue: it warns you whenever you're trying to use a variable that did not get set beforehand - helping you spot the typo.

Avoiding it is really easy, suppose you're checking the presence of a submit button in your post array to do form processing:

```<code>if ($_POST["submit"] == "submit")
</code>```

in case it's a regular get request, that line will throw an E_NOTICE for "submit" being an invalid index in $_POST. Avoiding it is really easy:

```<code>if (isset($_POST["submit"]) && $_POST["submit"] == "submit")
</code>```

this checks for the array index existence first. PHP uses lazy evaluation, in this case it means stopping after isset() if it returns false - the check that would throw the notice won't get executed. Also: isset is not a function, but a language construct - thus being fast.

My personal preference is to have error_reporting set to E_ALL | E_STRICT on all developer machines, that way I get notified of every possible problem - including using deprecated language features.

Body:
The other answers help you fix the symptom, not the problem. You are not getting errors, just notices, it's a special error level that warns you of a possible problem, but does not stop execution.

Given php's nature of not needing to declare variables, it is very easy to make a spelling mistake in your code and spend yours tracking it down (I'm sure everyone has did it at least a few times). And there comes E_NOTICE to the rescue: it warns you whenever you're trying to use a variable that did not get set beforehand - helping you spot the typo.

Avoiding it is really easy, suppose you're checking the presence of a submit button in your post array to do form processing:

if ($_POST["submit"] == "submit")

in case it's a regular get request, that line will throw an E_NOTICE for "submit" being an invalid index in $_POST. Avoiding it is really easy:

if (isset($_POST["submit"]) && $_POST["submit"] == "submit")

this checks for the array index existence first. PHP uses lazy evaluation, in this case it means stopping after isset() if it returns false - the check that would throw the notice won't get executed. Also: isset is not a function, but a language construct - thus being fast.

My personal preference is to have error_reporting set to E_ALL | E_STRICT on all developer machines, that way I get notified of every possible problem - including using deprecated language features.


问:
Inflating Images on ImageView on a RecylerView
I have been having a problem inflating an images on an Image view in a recyclerview.The images fetched from firebase database into the recyclerview, Precisely i get the following error.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.cnatra_measure, PID: 21096
    android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class android.widget.ImageView
    Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class android.widget.ImageView
    Caused by: java.lang.reflect.InvocationTargetException
</code>```

and a further in the error i get

```<code>at com.example.cnatra_measure.Adapters.Trads_StyleAdapter.onCreateViewHolder(Trads_StyleAdapter.java:54)
        at com.example.cnatra_measure.Adapters.Trads_StyleAdapter.onCreateViewHolder(Trads_StyleAdapter.java:21)
</code>```

my Adapter code is given below

```<code>public class Trads_StyleAdapter extends RecyclerView.Adapter<Trads_StyleAdapter.Trads_ViewHolder> {

    private Context mCtx;
    private List<Styles> stylesList;
    public Trads_StyleAdapter(Context mCtx, List<Styles> stylesList) {
        this.mCtx = mCtx;
        this.stylesList = stylesList;
    }
    public Trads_StyleAdapter(ArrayList<Styles> stylesList) {
        this.stylesList = stylesList;
    }
    public static class Trads_ViewHolder extends RecyclerView.ViewHolder {
        ImageView styleImage;
        TextView style_name, style_price;
        //List<Food> foods;
        //Context ctx;
        public Trads_ViewHolder(View v) {
            super(v);
            styleImage = v.findViewById(R.id.styleIcon);
            style_name = v.findViewById(R.id.style_names);
           style_price = v.findViewById(R.id.style_price);
       }
}
    @NonNull
    @Override
    public Trads_ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View v = inflater.inflate(R.layout.styles_items, parent, false);
        return new Trads_ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull Trads_ViewHolder holder, int position) {
        Styles mStyles = stylesList.get(position);
        holder.style_name.setText(mStyles.getStyle_name());
        holder.style_price.setText(mStyles.getPrice());
        Picasso.get()
                .load(mStyles.getStyle_image())
                .placeholder(R.drawable.img_placeholder)
                .fit()
                .centerCrop()
                .into(holder.styleImage);
    }
    @Override
    public int getItemCount() {
        return stylesList.size();
    }
}
</code>```

and the XML code for the list items is

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:elevation="15dp"
        card_view:cardCornerRadius="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/iconWrapper"
            android:orientation="vertical">

            <ImageView
                android:layout_width="130dp"
                android:layout_height="130dp"
                android:id="@+id/styleIcon"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:layout_gravity="center_horizontal|center_vertical"
                android:scaleType="fitXY"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:focusable="true" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/style_names"
                android:fontFamily="@font/nunito_semibold"
                android:padding="5dp"
                android:textSize="20sp"
                android:textColor="@color/blue"
                android:textAlignment="center"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/naira"
                    android:fontFamily="@font/nunito_bold"
                    android:padding="5dp"
                    android:textSize="15sp"
                    android:textColor="@color/blue"
                    android:textAlignment="center"/>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/style_price"
                    android:padding="5dp"
                    android:textSize="15sp"
                    android:fontFamily="@font/nunito_bold"
                    android:textColor="@color/black"
                    android:textAlignment="center"/>
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>
</code>```

Thanks in advance

答:
Use this xml : </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:elevation="15dp"
        card_view:cardCornerRadius="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/iconWrapper"
            android:orientation="vertical">

            <ImageView
                android:layout_width="130dp"
                android:layout_height="130dp"
                android:id="@+id/styleIcon"
                android:clickable="true"
                android:layout_gravity="center"
                android:scaleType="fitXY"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:focusable="true" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/style_names"
                android:fontFamily="@font/nunito_semibold"
                android:padding="5dp"
                android:textSize="20sp"
                android:textColor="@color/blue"
                android:textAlignment="center"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/naira"
                    android:fontFamily="@font/nunito_bold"
                    android:padding="5dp"
                    android:textSize="15sp"
                    android:textColor="@color/blue"
                    android:textAlignment="center"/>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/style_price"
                    android:padding="5dp"
                    android:textSize="15sp"
                    android:fontFamily="@font/nunito_bold"
                    android:textColor="@color/black"
                    android:textAlignment="center"/>
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>
</code>```

Body:
I have been having a problem inflating an images on an Image view in a recyclerview.The images fetched from firebase database into the recyclerview, Precisely i get the following error.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.cnatra_measure, PID: 21096
    android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class android.widget.ImageView
    Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class android.widget.ImageView
    Caused by: java.lang.reflect.InvocationTargetException

and a further in the error i get

at com.example.cnatra_measure.Adapters.Trads_StyleAdapter.onCreateViewHolder(Trads_StyleAdapter.java:54)
        at com.example.cnatra_measure.Adapters.Trads_StyleAdapter.onCreateViewHolder(Trads_StyleAdapter.java:21)

my Adapter code is given below

public class Trads_StyleAdapter extends RecyclerView.Adapter<Trads_StyleAdapter.Trads_ViewHolder> {

    private Context mCtx;
    private List

Body:
Use this xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:elevation="15dp"
        card_view:cardCornerRadius="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/iconWrapper"
            android:orientation="vertical">

            <ImageView
                android:layout_width="130dp"
                android:layout_height="130dp"
                android:id="@+id/styleIcon"
                android:clickable="true"
                android:layout_gravity="center"
                android:scaleType="fitXY"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:focusable="true" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/style_names"
                android:fontFamily="@font/nunito_semibold"
                android:padding="5dp"
                android:textSize="20sp"
                android:textColor="@color/blue"
                android:textAlignment="center"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/naira"
                    android:fontFamily="@font/nunito_bold"
                    android:padding="5dp"
                    android:textSize="15sp"
                    android:textColor="@color/blue"
                    android:textAlignment="center"/>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/style_price"
                    android:padding="5dp"
                    android:textSize="15sp"
                    android:fontFamily="@font/nunito_bold"
                    android:textColor="@color/black"
                    android:textAlignment="center"/>
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>


问:
Method that performs operations inside an array
I have an array a=[1, 2, 'N']. I would like a method to do if a[2] = 'N', increase a[1] by 1.
I tried this:

```<code>def change
  if self[2] == 'N'
    self[1] += 1
  end
end

a.change
</code>```

It gives me an error: undefined method `change' for [1, 2, "N"]:Array

What am I doing wrong?

答:
You could pass the array as an argument:</p>

```<code>def change(a)
  if a[2] == 'N'
    a[1] += 1
  end
end

change(a)
</code>```

Body:
I have an array a=[1, 2, 'N']. I would like a method to do if a[2] = 'N', increase a[1] by 1.
I tried this:

def change
  if self[2] == 'N'
    self[1] += 1
  end
end

a.change

It gives me an error: undefined method `change' for [1, 2, "N"]:Array

What am I doing wrong?

Body:
You could pass the array as an argument:

def change(a)
  if a[2] == 'N'
    a[1] += 1
  end
end

change(a)


问:
how to select distinct values from 2 tables in sql
table1

```<code>id
1
2
3
4
5
</code>```

table2

```<code>id
4
5
6
7
8
</code>```

I want to result in this way:

```<code>id
1
2
3
6
7
8
</code>```

答:
You can write your query like following.</p>

```<code>select coalesce(id1, id2) as id
from (
    select t1.id as id1
        ,t2.id as id2
    from table1 t1
    left join table2 t2 on t1.id = t2.id

    union

    select t1.id as id1
        ,t2.id as id2
    from table1 t1
    right join table2 t2 on t1.id = t2.id
    ) T
where t.id1 is null
    or t.id2 is null
</code>```

Body:
table1

id
1
2
3
4
5

table2

id
4
5
6
7
8

I want to result in this way:

id
1
2
3
6
7
8

Body:
You can write your query like following.

select coalesce(id1, id2) as id
from (
    select t1.id as id1
        ,t2.id as id2
    from table1 t1
    left join table2 t2 on t1.id = t2.id

    union

    select t1.id as id1
        ,t2.id as id2
    from table1 t1
    right join table2 t2 on t1.id = t2.id
    ) T
where t.id1 is null
    or t.id2 is null


问:
How to apply several functions on every possible row combinations within a dataframe in R?
I've got a dataframe with coordinates (lon, lat)

```<code>    lon <- list(505997.627175236, 505997.627175236, 505997.627175236, 505997.627175236)
    lon <- do.call(rbind.data.frame, lon)

    lat <- list(7941821.025438220, 7941821.025438220, 7941821.025438220, 7941821.025438220)
    lat <- do.call(rbind.data.frame, lat)

    coord <- cbind(lon, lat)
    colnames(coord) <- c("lon", "lat")
</code>```

I'm trying to calculate the euclidian distance and the angle between all the possible row combinations within the dataframe.

```<code>     lon   lat       apply function on every possible combinations such as v1-v2, v1-v3, v1-v4,
v1   x1    y1        v2-v3 and so on...
v2   x2    y2
v3   x3    y3        here are the two functions applied beetween v1 and v2 :
v4   x4    y4        **euclidian distance**    sqrt((x1-x2)^2 + (y1-y2)^2)
                     **angle**                 atan2((y1-y2),(x1-x2))*(180/pi)
</code>```

How to apply several functions on every possible row combinations and get the results in respective lists ? My goal is to use these calculations at every iteration whatever the number of row in input.

Thanks in advance for your answers and sorry if the question seems silly. I've looked at so many posts but couldn't find a solution that I could understand and replicate.

答:
In the end, I've adapted the code that Georgery provided but I used "combn" instead of "expand.grid" in order to avoid repetition among the row conbinations when applying the functions to the final dataframe. I also had to use the function "convert" from the package "hablar" in order to properly convert the factors of my dataframe "coord_combn" to numeric values.

Here's the code :

```<code>lon <- c(505997.627175236, 505597.627175236, 515997.627175236, 505297.627175236)
lat <- c(7941821.025438220, 7945821.025438220, 7141821.025438220, 7921821.025438220)

# dataframe creation + adding of an id column
coord <- data.frame(lon, lat) %>%
                 mutate(id = 1:nrow(.))

coord_combn <- combn(rownames(coord), 2) # all the possible row combinations
coord_combn <- as.data.frame(t(coord_combn)) # transpose columns into rows
coord_combn <- coord_combn %>%
                 convert(num(V1, V2)) # factor to numeric

#join our dataframe first on one index then on the other
coord_final <- coord_combn %>%
  left_join(coord, by = c("V1" = "id")) %>%
  left_join(coord, by = c("V2" = "id"))

eDistance <- function(x1, x2, y1, y2) sqrt((x1-x2)^2 + (y1-y2)^2)
eAngle <- function(x1, x2, y1, y2) atan2((y1-y2),(x1-x2))*(180/3.14159265359)

# euclidean distance calculation
coord_final <- coord_final %>%
                 mutate(distance = eDistance(lon.x, lon.y, lat.x, lat.y))
# angle calculation
coord_final <- coord_final %>%
                 mutate(angle = eAngle(lon.x, lon.y, lat.x, lat.y))
</code>```

Thank you everyone, you've been a great help.

Body:
I've got a dataframe with coordinates (lon, lat)

    lon <- list(505997.627175236, 505997.627175236, 505997.627175236, 505997.627175236)
    lon <- do.call(rbind.data.frame, lon)

    lat <- list(7941821.025438220, 7941821.025438220, 7941821.025438220, 7941821.025438220)
    lat <- do.call(rbind.data.frame, lat)

    coord <- cbind(lon, lat)
    colnames(coord) <- c("lon", "lat")

I'm trying to calculate the euclidian distance and the angle between all the possible row combinations within the dataframe.

     lon   lat       apply function on every possible combinations such as v1-v2, v1-v3, v1-v4,
v1   x1    y1        v2-v3 and so on...
v2   x2    y2
v3   x3    y3        here are the two functions applied beetween v1 and v2 :
v4   x4    y4        **euclidian distance**    sqrt((x1-x2)^2 + (y1-y2)^2)
                     **angle**                 atan2((y1-y2),(x1-x2))*(180/pi)

How to apply several functions on every possible row combinations and get the results in respective lists ? My goal is to use these calculations at every iteration whatever the number of row in input.

Thanks in advance for your answers and sorry if the question seems silly. I've looked at so many posts but couldn't find a solution that I could understand and replicate.

Body:
In the end, I've adapted the code that Georgery provided but I used "combn" instead of "expand.grid" in order to avoid repetition among the row conbinations when applying the functions to the final dataframe. I also had to use the function "convert" from the package "hablar" in order to properly convert the factors of my dataframe "coord_combn" to numeric values.

Here's the code :

lon <- c(505997.627175236, 505597.627175236, 515997.627175236, 505297.627175236)
lat <- c(7941821.025438220, 7945821.025438220, 7141821.025438220, 7921821.025438220)

# dataframe creation + adding of an id column
coord <- data.frame(lon, lat) %>%
                 mutate(id = 1:nrow(.))

coord_combn <- combn(rownames(coord), 2) # all the possible row combinations
coord_combn <- as.data.frame(t(coord_combn)) # transpose columns into rows
coord_combn <- coord_combn %>%
                 convert(num(V1, V2)) # factor to numeric

#join our dataframe first on one index then on the other
coord_final <- coord_combn %>%
  left_join(coord, by = c("V1" = "id")) %>%
  left_join(coord, by = c("V2" = "id"))

eDistance <- function(x1, x2, y1, y2) sqrt((x1-x2)^2 + (y1-y2)^2)
eAngle <- function(x1, x2, y1, y2) atan2((y1-y2),(x1-x2))*(180/3.14159265359)

# euclidean distance calculation
coord_final <- coord_final %>%
                 mutate(distance = eDistance(lon.x, lon.y, lat.x, lat.y))
# angle calculation
coord_final <- coord_final %>%
                 mutate(angle = eAngle(lon.x, lon.y, lat.x, lat.y))

Thank you everyone, you've been a great help.


问:
Multiline regex not working for filebeat but working in goplay tester
I have filebeat->ES setup.no logstash.
I have logs like below :

```<code>2020 Feb 11 06:56:30:554 GMT -0500 DEBUG [LogPool$0] com.ZU.digital.utilityservices.logging.Logging - EAI-DEBUG | ProcessOrderStatus.rule: Id - : OrderStatusNotification Payload : <?xml version="1.0" encoding="UTF-8"?>
<ns0:OSN >
ns0:merchantID200142</ns0:merchantID>
ns0:orderCode2003787391047586</ns0:orderCode>
ns0:lastEventCAPTURED</ns0:lastEvent>
ns0:paymentAmount12.90</ns0:paymentAmount>
ns0:paymentCurrencyEUR</ns0:paymentCurrency>
ns0:paymentCreditDebitINDC</ns0:paymentCreditDebitIND>
ns0:additionalData
ns0:data
ns0:name/
ns0:value/
</ns0:data>
</ns0:additionalData>
</ns0:OSN>
2020 Feb 11 06:56:30:554 GMT -0500 DEBUG [LogPool$0] com.ZU.digital.utilityservices.logging.Logging - Masking input XML in maskEntireXml
</code>```

I have multiline pattern as :

```<code>multiline.pattern: '^[0-9]{4}[[:space:]]'

  # Defines if the pattern set under pattern should be negated or not. Default is false.
  multiline.negate: true

  # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern
  # that was (not) matched before or after or as long as a pattern is not matched based on negate.
  # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash
  multiline.match: after
</code>```

but each line is treated as single event. Regex is tested in playgolang and working fine .I want logs as single event between dates

答: Got resolved after making negate : true</p>

Body:
I have filebeat->ES setup.no logstash.
I have logs like below :

2020 Feb 11 06:56:30:554 GMT -0500 DEBUG [LogPool$0] com.ZU.digital.utilityservices.logging.Logging - EAI-DEBUG | ProcessOrderStatus.rule: Id - : OrderStatusNotification Payload : <?xml version="1.0" encoding="UTF-8"?>
<ns0:OSN >
ns0:merchantID200142</ns0:merchantID>
ns0:orderCode2003787391047586</ns0:orderCode>
ns0:lastEventCAPTURED</ns0:lastEvent>
ns0:paymentAmount12.90</ns0:paymentAmount>
ns0:paymentCurrencyEUR</ns0:paymentCurrency>
ns0:paymentCreditDebitINDC</ns0:paymentCreditDebitIND>
ns0:additionalData
ns0:data
ns0:name/
ns0:value/
</ns0:data>
</ns0:additionalData>
</ns0:OSN>
2020 Feb 11 06:56:30:554 GMT -0500 DEBUG [LogPool$0] com.ZU.digital.utilityservices.logging.Logging - Masking input XML in maskEntireXml

I have multiline pattern as :

multiline.pattern: '^[0-9]{4}[[:space:]]'

  # Defines if the pattern set under pattern should be negated or not. Default is false.
  multiline.negate: true

  # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern
  # that was (not) matched before or after or as long as a pattern is not matched based on negate.
  # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash
  multiline.match: after

but each line is treated as single event. Regex is tested in playgolang and working fine .I want logs as single event between dates

Body: Got resolved after making negate : true


问:
Why does my App.js code changes itself upon save?
I am trying to build my first React Native app. I am using the default App.js code, the only difference is the output text that I changed from Open up App.js to Hello world!. I have an issue with the code changing itself upon save.

This is how the default function looks before I press Ctrl+S to save the file:

```<code>export default function App() {
  return (
    <View style={styles.container}>
      <Text>Hello world!</Text>
    </View>
  );
}
</code>```

And this is how the default function looks after the save:

```<code>export default function App() {
    return ( <
        View style = { styles.container } >
        <
        Text > Hello world! < /Text> <
        /View>
    );
}
</code>```

Is it a bug or am I doing something wrong?

答:
This is based on your IDE. Since you are using Visual Studio Code as IDE try to use code formatting extension to format your code accordingly.

Try to use Prettier - Code Formatter Extension for VS Code -> Here

If you wan to enable auto save add the following to your settings.json file:

"editor.formatOnSave": true

If you wan to disable auto save add the following to your settings.json file:

"editor.formatOnSave": false

Body:
I am trying to build my first React Native app. I am using the default App.js code, the only difference is the output text that I changed from Open up App.js to Hello world!. I have an issue with the code changing itself upon save.

This is how the default function looks before I press Ctrl+S to save the file:

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Hello world!</Text>
    </View>
  );
}

And this is how the default function looks after the save:

export default function App() {
    return ( <
        View style = { styles.container } >
        <
        Text > Hello world! < /Text> <
        /View>
    );
}

Is it a bug or am I doing something wrong?