问:
The requested page cannot be accessed because the related configuration data for the page is invalid. (with a "catch"...)
Another user in my organization put a folder with source code on a central server. I copied the source code to my local machine and when I try to run the application in VS on my local machine I get the following error:

```<code>HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       Unknown
Handler    Not yet determined
Error Code     0x80070005
Config Error       Cannot read configuration file due to insufficient permissions
Config File    \\?\UNC\...\users\username\My Web Sites\Website1\web.config
</code>```

The issue is with the file location of the problematic .config file:

\\?\UNC...\users\username\My Web Sites\Website1\web.config

This location does not exist on my local machine. I have confirmed with the other user that it does exist on his machine - so it appears that the application is referencing a file location that simply does not exist. My suspicion is that there is some kind of folder/cache that needs to be cleared out, but I don't know what to do in this situation. Any ideas?

答:
Ended up actually finding a duplicate question with an answer regarding deleting an applicationhost.config file and then recreating it in VS:

HTTP error 500.19 - Cannot read configuration file

Body:
Another user in my organization put a folder with source code on a central server. I copied the source code to my local machine and when I try to run the application in VS on my local machine I get the following error:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       Unknown
Handler    Not yet determined
Error Code     0x80070005
Config Error       Cannot read configuration file due to insufficient permissions
Config File    \\?\UNC\...\users\username\My Web Sites\Website1\web.config

The issue is with the file location of the problematic .config file:

\\?\UNC...\users\username\My Web Sites\Website1\web.config

This location does not exist on my local machine. I have confirmed with the other user that it does exist on his machine - so it appears that the application is referencing a file location that simply does not exist. My suspicion is that there is some kind of folder/cache that needs to be cleared out, but I don't know what to do in this situation. Any ideas?


来源: stackexchange

问:
Springboot standalone application deploy in production
I am trying to deploy my springboot standalone application in production in linux server.I am trying to use the out of the box tomcat server.

'java -jar jarname.jar'

This works fine , but if I close my putty session the application is unistalled.

Now I used

'nohup java -jar jarname.jar &'

this works good and my application is not shutdown even if my putty session is closed.But the logs will not roll correctly(I have configured log4j to create a new log file for each day) in this case. So was wondering if this is the right way to do this.

I have searched several documentation but was not able to find a correct solution for this problem.
Please help.

Thanks

答:
Why not package it into a Docker image and run that on the server?

Here are a few ideas:

https://medium.com/swlh/deploying-spring-boot-applications-15e14db25ff0

ContentLicense: CC BY-SA 4.0


问:
MATLAB Parfor with high number of iterations not starting
I am running Matlab 2014a and trying to start a script with parfor. However it gets stuck at

```<code>Starting parallel pool (parpool) using the 'local' profile ... connected to 16 workers.
</code>```

I run a test script before and it worked ok. The difference is that the test script has 4 iterations of parfor and 2 arrays of 5x12x3x4 size which are filled in the parfor loop, whereas the main script has 100 iterations and 2 arrays of 31x12x3x100 size.
Any ideas how to make it run?
Thanks!

EDIT: here is a simplified version of my code to illustrate the problem, please note that this version, where I don't include the calculations actually works. It is not feasible to include the calculations as they involve other Matlab and a Python script. Also, when I say stuck, I mean that I am not getting any output from the disp(output) line.

```<code>close all;
clear all;
clc;

disp('starting');
results_nb = zeros(31,12,3,100);
results_ht = zeros(31,12,3,100);
progress = zeros(1,100);

parfor iter = 1:100

    t = getCurrentTask();
    output = ['Worker:' num2str(t.ID) ', Iteration:' num2str(iter)];
    disp(output);
    j_idx=0;
    results_nb_iter=zeros(31,12,3);
    results_ht_iter=zeros(31,12,3);
    for j=[10,20,50]
        j_idx=j_idx+1;
        for i=1:31
            line_nb = zeros(1,12);
            line_ht = zeros(1,12);

            %line_nb = some calculations
            %line_ht = some calculations

            results_nb_iter(i,:,j_idx)=line_nb;
            results_ht_iter(i,:,j_idx)=line_ht;

        end
    end
    results_nb(:,:,:,iter)=results_nb_iter;
    results_ht(:,:,:,iter)=results_ht_iter;

end

save('results')

exit
</code>```

答:
Your deduction is wrong because your measurement is wrong.

disp() inside a parfor loop is not ensured to print to screen exactly when the worker gets to it, it is instead queued and when the worker is free, it will send it to the client to print.

To keep progress of a parfor execution, you need parallel.pool.DataQueue

Read also this other Mathworks post about the same topic: https://uk.mathworks.com/matlabcentral/answers/372416-how-can-i-display-the-progress-of-a-parfor-or-parfeval-loop-in-matlab-r2017a-and-newer

Body:
I am running Matlab 2014a and trying to start a script with parfor. However it gets stuck at

Starting parallel pool (parpool) using the 'local' profile ... connected to 16 workers.

I run a test script before and it worked ok. The difference is that the test script has 4 iterations of parfor and 2 arrays of 5x12x3x4 size which are filled in the parfor loop, whereas the main script has 100 iterations and 2 arrays of 31x12x3x100 size.
Any ideas how to make it run?
Thanks!

EDIT: here is a simplified version of my code to illustrate the problem, please note that this version, where I don't include the calculations actually works. It is not feasible to include the calculations as they involve other Matlab and a Python script. Also, when I say stuck, I mean that I am not getting any output from the disp(output) line.

close all;
clear all;
clc;

disp('starting');
results_nb = zeros(31,12,3,100);
results_ht = zeros(31,12,3,100);
progress = zeros(1,100);

parfor iter = 1:100

    t = getCurrentTask();
    output = ['Worker:' num2str(t.ID) ', Iteration:' num2str(iter)];
    disp(output);
    j_idx=0;
    results_nb_iter=zeros(31,12,3);
    results_ht_iter=zeros(31,12,3);
    for j=[10,20,50]
        j_idx=j_idx+1;
        for i=1:31
            line_nb = zeros(1,12);
            line_ht = zeros(1,12);

            %line_nb = some calculations
            %line_ht = some calculations

            results_nb_iter(i,:,j_idx)=line_nb;
            results_ht_iter(i,:,j_idx)=line_ht;

        end
    end
    results_nb(:,:,:,iter)=results_nb_iter;
    results_ht(:,:,:,iter)=results_ht_iter;

end

save('results')

exit


问:
Insert page into existing PDF using itextsharp
We are using itextsharp to create a single PDF from multiple PDF files. How do I insert a new page into a PDF file that has multiple pages already in the file? When I use add page it is overwriting the existing pages and only saves the 1 page that was selected.

Here is the code that I am using to add the page to the existing PDF:

```<code>PdfReader reader = new PdfReader(sourcePdfPath);
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                PdfCopy pdfCopy = new PdfCopy(document, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
                MemoryStream memoryStream = new MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.AddDocListener(writer);
                document.Open();

                for (int p = 1; p <= reader.NumberOfPages; p++)
                {
                    if (pagesToExtract.FindIndex(s => s == p) == -1) continue;
                    document.SetPageSize(reader.GetPageSize(p));
                    document.NewPage();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage pageImport = writer.GetImportedPage(reader, p);

                    int rot = reader.GetPageRotation(p);
                    if (rot == 90 || rot == 270)
                    {
                        cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
                    }
                    else
                    {
                        cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0);
                    }

                    pdfCopy.AddPage(pageImport);
                }

                pdfCopy.Close();
</code>```

答:
I know I'm really late to the part here, but I mixed a bit of the two best answers and created a method if anyone needs it that adds a list of source PDF documents to a single document using itextsharp.</p>

```<code>private static void appendToDocument(List<string> sourcePDFList, string outputPdfPath)
{
    //Output document name and creation
    FileStream destinationDocumentStream = new FileStream(outputPdfPath, FileMode.Create);
     //Object to concat source pdf's to output pdf
     PdfConcatenate pdfConcat = new PdfConcatenate(destinationDocumentStream);

     //For each source pdf in list...
     foreach (string sourcePdfPath in sourcePDFList)
     {
         //If file exists...
         if (File.Exists(sourcePdfPath))
         {
             //Open the document
             FileStream sourceDocumentStream = new FileStream(sourcePdfPath, FileMode.Open);
             //Read the document
             PdfReader pdfReader = new PdfReader(sourceDocumentStream);

             //Create an int list
             List<int> pages = new List<int>();
             //for each page in pdfReader
             for (int i = 1; i < pdfReader.NumberOfPages + 1; i++)
             {
                 //Add that page to the list
                 pages.Add(i);
             }

             //Add that page to the pages to add to ouput document
             pdfReader.SelectPages(pages);
             //Add pages to output page
             pdfConcat.AddPages(pdfReader);

             //Close reader
             pdfReader.Close();
         }
     }

    //Close pdfconcat
    pdfConcat.Close();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are using itextsharp to create a single PDF from multiple PDF files. How do I insert a new page into a PDF file that has multiple pages already in the file? When I use add page it is overwriting the existing pages and only saves the 1 page that was selected.

Here is the code that I am using to add the page to the existing PDF:

PdfReader reader = new PdfReader(sourcePdfPath);
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                PdfCopy pdfCopy = new PdfCopy(document, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
                MemoryStream memoryStream = new MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.AddDocListener(writer);
                document.Open();

                for (int p = 1; p <= reader.NumberOfPages; p++)
                {
                    if (pagesToExtract.FindIndex(s => s == p) == -1) continue;
                    document.SetPageSize(reader.GetPageSize(p));
                    document.NewPage();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage pageImport = writer.GetImportedPage(reader, p);

                    int rot = reader.GetPageRotation(p);
                    if (rot == 90 || rot == 270)
                    {
                        cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
                    }
                    else
                    {
                        cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0);
                    }

                    pdfCopy.AddPage(pageImport);
                }

                pdfCopy.Close();

Body:
I know I'm really late to the part here, but I mixed a bit of the two best answers and created a method if anyone needs it that adds a list of source PDF documents to a single document using itextsharp.

private static void appendToDocument(List<string> sourcePDFList, string outputPdfPath)
{
    //Output document name and creation
    FileStream destinationDocumentStream = new FileStream(outputPdfPath, FileMode.Create);
     //Object to concat source pdf's to output pdf
     PdfConcatenate pdfConcat = new PdfConcatenate(destinationDocumentStream);

     //For each source pdf in list...
     foreach (string sourcePdfPath in sourcePDFList)
     {
         //If file exists...
         if (File.Exists(sourcePdfPath))
         {
             //Open the document
             FileStream sourceDocumentStream = new FileStream(sourcePdfPath, FileMode.Open);
             //Read the document
             PdfReader pdfReader = new PdfReader(sourceDocumentStream);

             //Create an int list
             List<int> pages = new List<int>();
             //for each page in pdfReader
             for (int i = 1; i < pdfReader.NumberOfPages + 1; i++)
             {
                 //Add that page to the list
                 pages.Add(i);
             }

             //Add that page to the pages to add to ouput document
             pdfReader.SelectPages(pages);
             //Add pages to output page
             pdfConcat.AddPages(pdfReader);

             //Close reader
             pdfReader.Close();
         }
     }

    //Close pdfconcat
    pdfConcat.Close();
}


问:
How to convert string to floating point number inside a Perl hash?
My motive is to convert the string number into floating point number while creating a hash.

I have placed my entire code and error below. Please help me to solve this issue.

Sample code

```<code>use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);
</code>```

Current output

```<code>$VAR1 = {
          'get' => '8.50'
        };
</code>```

Expected output

```<code>$VAR1 = {
          'get' => 8.50
        };
</code>```

答:
```<code>use Scalar::Util 'looks_like_number';
.
.
print Dumper($g) =~ s/'(.*?)'/looks_like_number($1)?$1:"'$1'"/ger;
</code>```

Which changes the output from Dumper before it's printed. It removes both 's of every single quoted string if it looks like a number according to Scalar::Util.

Body:
My motive is to convert the string number into floating point number while creating a hash.

I have placed my entire code and error below. Please help me to solve this issue.

Sample code

use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);

Current output

$VAR1 = {
          'get' => '8.50'
        };

Expected output

$VAR1 = {
          'get' => 8.50
        };

Body:
use Scalar::Util 'looks_like_number';
.
.
print Dumper($g) =~ s/'(.*?)'/looks_like_number($1)?$1:"'$1'"/ger;

Which changes the output from Dumper before it's printed. It removes both 's of every single quoted string if it looks like a number according to Scalar::Util.


问:
fast full text search on windows phone 7
How can I do very fast full text search on windows phone 7?

I know of C libraries that can do this- is there any way I can interface to a C library for this?

Are there any databases for windows phone 7 that offer full text searching capability? Besides the databases mentioned in the answers, I have also come across RavenDB and FileDB, which don't have full text search.

Are there options for a .NET library for full text searching? I have come across a .NET port of the Lucene project, which would have to be ported to use Isolated Storage. There is a port that uses Azure, but that isn't what I am looking for.

答:
In most applications it would be best to have the documents stored on a server and use a web service to perform the full text search server-side. The phone is severely limited in terms of processing power, storage space, and IO speed, so unless you are using a very small data set you may quickly outgrow the resources available on the device.

That being said, it does not appear that any of the existing database solutions for Windows Phone support full text searching. The Sterling database engine is one of the more popular options with many standard database features, but as of right now it does not support full text searching. Rapid Repository and siaqodb are other options, however they also do not currently support full text searching. Someone has ported SQLite to Windows Phone 7, but it is based on the csharp-sqlite project, which does not support the SQLITE_ENABLE_FTS3 compiler option that is required for Full Text Searching. The next Windows Phone release code named Mango will provide developers with access to Microsoft SQL Server Compact edition, however this also does not support full text searching.

I believe your only option would be to take a .NET managed full text search engine like Lucene.net and try to port it to work in Silverlight. You would need to do a lot of refactoring, since Silverlight only allows access to Isolated Storage and not direct access to the file system. There also is strict limits on memory usage (90MB max RAM usage per app), which again will limit the size of the data-set you can use on the phone.


问:
LEFT OUTER JOIN in LINQ
How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause?
Correct problem:
For inner join is easy and I have a solution like this

```<code>List<JoinPair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})
</code>```

but for left outer join I need a solution. Mine is something like this but it's not working

```<code>List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair {
                                            LeftId = l.Id,
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })
</code>```

where JoinPair is a class:

```<code>public class JoinPair { long leftId; long rightId; }
</code>```

答:
Overview: In this code snippet, I demonstrate how to group by ID where Table1 and Table2 have a one to many relationship.  I group on
Id, Field1, and Field2.   The subquery is helpful, if a third Table lookup is required and it would have required a left join relationship.
I show a left join grouping and a subquery linq.  The results are equivalent.</p>

```<code>class MyView
{
public integer Id {get,set};
    public String Field1  {get;set;}
public String Field2 {get;set;}
    public String SubQueryName {get;set;}
}

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=
                                                   (from chv in _dbContext.Table3 where chv.Id==pg.Key.Id select chv.Field1).FirstOrDefault()
                                               }).ToListAsync<MyView>();

 Compared to using a Left Join and Group new

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                       join chv in _dbContext.Table3
                                                  on cii.Id equals chv.Id into lf_chv
                                                from chv in lf_chv.DefaultIfEmpty()

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2, chv.FieldValue}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=pg.Key.FieldValue
                                               }).ToListAsync<MyView>();
</code>```

Title: LEFT OUTER JOIN in LINQ

Body:
How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause?
Correct problem:
For inner join is easy and I have a solution like this

List<JoinPair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})

but for left outer join I need a solution. Mine is something like this but it's not working

List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair {
                                            LeftId = l.Id,
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })

where JoinPair is a class:

public class JoinPair { long leftId; long rightId; }

Body:
Overview: In this code snippet, I demonstrate how to group by ID where Table1 and Table2 have a one to many relationship.  I group on
Id, Field1, and Field2.   The subquery is helpful, if a third Table lookup is required and it would have required a left join relationship.
I show a left join grouping and a subquery linq.  The results are equivalent.

class MyView
{
public integer Id {get,set};
    public String Field1  {get;set;}
public String Field2 {get;set;}
    public String SubQueryName {get;set;}
}

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=
                                                   (from chv in _dbContext.Table3 where chv.Id==pg.Key.Id select chv.Field1).FirstOrDefault()
                                               }).ToListAsync<MyView>();

 Compared to using a Left Join and Group new

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                       join chv in _dbContext.Table3
                                                  on cii.Id equals chv.Id into lf_chv
                                                from chv in lf_chv.DefaultIfEmpty()

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2, chv.FieldValue}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=pg.Key.FieldValue
                                               }).ToListAsync<MyView>();


问:
Cannot generate SOAP client on .net core 3 from WCF
I have a web service written on WCF. I am trying to generate the client by using "Microsoft WCF Web Service Reference Provider". My project is .net core 3 web api.
But I get this error
Warning: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Could not load type 'System.Web.PreApplicationStartMethodAttribute' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:portType[@name='ILiveViewService']

Why is it trying to reference System.Web? It is a framework library. It is not part of the CORE

答:
I had the same problem, trying to include a new WCF, but it didn't work, with the same error above.

The conflict was between the references System.Web and Microsoft.AspNetCore.Mvc, probably when adding. It was giving conflict between both.

The solution was to remove any references from System.Web that I had on my controller.

Controller with error:

```<code>[ApiController]
public class TesteController: ControllerBase {}
</code>```

Controller without error:

```<code>public class TesteController: Controller {}
</code>```

Body:
I had the same problem, trying to include a new WCF, but it didn't work, with the same error above.

The conflict was between the references System.Web and Microsoft.AspNetCore.Mvc, probably when adding. It was giving conflict between both.

The solution was to remove any references from System.Web that I had on my controller.

Controller with error:

[ApiController]
public class TesteController: ControllerBase {}

Controller without error:

public class TesteController: Controller {}


问:
Edit visudo using vim called from a script
I created an automated install script and while executing from the chroot I would like to uncomment the wheel group line. I could do it using sed -i "s/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/g" /etc/sudoers but I read that is not the best practice. So, how to do it with vim?

The command is :82 s/# // I tried to use pipe, redirect stdin or use vim +" command file" but the former ones do not work and the latter one works but indicates that it is a readonly file...

Thank you!

答:
One possibility would be to pipe the output of your sed command (without the <code>-i</code> flag) into this script to overwrite the sudoers file if it is safe to do so, without having to try to run the editor non-interactively. </p>

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

#
# Replaces /etc/sudoers with a new version supplied
# on standard input, but first performs safety checks
# including with "visudo -c"
#

sudoers=/etc/sudoers
tmp_sudoers=$sudoers.tmp  # same tmp file as used by visudo

if [ -e $tmp_sudoers ]
then
    echo "someone is editing sudoers"
    exit 1
fi

# make new version from data on stdin, preserving permissions
# by creating a copy and then overwriting it
cp $sudoers $tmp_sudoers
cat > $tmp_sudoers

# install the new version if it passes checks
succeeded=0
if [ ! -s $tmp_sudoers ]
then
    echo "replacement file is empty"
elif diff -q $sudoers $tmp_sudoers > /dev/null
then
    echo "there were no changes"
elif ! visudo -q -c -f $tmp_sudoers
then
    echo "replacement file is invalid"
else
    mv $tmp_sudoers $sudoers
    succeeded=1
fi

if [ $succeeded -eq 0 ]
then
    rm $tmp_sudoers
    exit 1
fi
</code>```

Body:
One possibility would be to pipe the output of your sed command (without the -i flag) into this script to overwrite the sudoers file if it is safe to do so, without having to try to run the editor non-interactively.

#!/bin/sh

#
# Replaces /etc/sudoers with a new version supplied
# on standard input, but first performs safety checks
# including with "visudo -c"
#

sudoers=/etc/sudoers
tmp_sudoers=$sudoers.tmp  # same tmp file as used by visudo

if [ -e $tmp_sudoers ]
then
    echo "someone is editing sudoers"
    exit 1
fi

# make new version from data on stdin, preserving permissions
# by creating a copy and then overwriting it
cp $sudoers $tmp_sudoers
cat > $tmp_sudoers

# install the new version if it passes checks
succeeded=0
if [ ! -s $tmp_sudoers ]
then
    echo "replacement file is empty"
elif diff -q $sudoers $tmp_sudoers > /dev/null
then
    echo "there were no changes"
elif ! visudo -q -c -f $tmp_sudoers
then
    echo "replacement file is invalid"
else
    mv $tmp_sudoers $sudoers
    succeeded=1
fi

if [ $succeeded -eq 0 ]
then
    rm $tmp_sudoers
    exit 1
fi


问:
Filtering SQLite database with SearchBar
i´ve been able to generate and show a SQList database and now i wanna filter it with a Search Bar, i´ve been reading many tutorials, but i´m not able to make it work...

I have an SQLite Model with this code:

```<code>using SQLite;
namespace AppListo
{
public class Employee
  {
    [PrimaryKey, AutoIncrement]
    public long EmpId
    { get; set; }
    [NotNull]
    public string EmpName
    { get; set; }

  }
}
</code>```

...and i retrieve a datalist from the database with:

```<code>public List<Employee> GetAllEmployees()
    {
        return dbConn.Query<Employee>("Select * From [Employee]");
    }
</code>```

...and i show the list in a ContentPage with this xaml code:

```<code><ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" Padding="5,5,5,5">
                            <Label Text="{Binding EmpName}" FontSize="Medium" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>
</code>```

...and this code behind:

```<code>var vList = App.DAUtil.GetAllEmployees();
lstData.ItemsSource = vList;
</code>```

...but i don´t know how to filter this list with a searchbar.
Could you help me to achieve it?

Thanks in advance

答:
use LINQ</p>

```<code>var vList = App.DAUtil.GetAllEmployees();
lstData.ItemsSource = vList.Where(e => e.Name.Contains(mySearchString));
</code>```

Body:
i´ve been able to generate and show a SQList database and now i wanna filter it with a Search Bar, i´ve been reading many tutorials, but i´m not able to make it work...

I have an SQLite Model with this code:

using SQLite;
namespace AppListo
{
public class Employee
  {
    [PrimaryKey, AutoIncrement]
    public long EmpId
    { get; set; }
    [NotNull]
    public string EmpName
    { get; set; }

  }
}

...and i retrieve a datalist from the database with:

public List<Employee> GetAllEmployees()
    {
        return dbConn.Query<Employee>("Select * From [Employee]");
    }

...and i show the list in a ContentPage with this xaml code:

<ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" Padding="5,5,5,5">

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

...and this code behind:

var vList = App.DAUtil.GetAllEmployees();
lstData.ItemsSource = vList;

...but i don´t know how to filter this list with a searchbar.
Could you help me to achieve it?

Thanks in advance

Body:
use LINQ

var vList = App.DAUtil.GetAllEmployees();
lstData.ItemsSource = vList.Where(e => e.Name.Contains(mySearchString));


问:
CNN model not working well on 4 species but works well with 2 species
I tried CNN model on two classes and got 80% but when i tried the same model with 4 classes i got very bad result. What is the reason pls help.
The model of CNN i used is:

```<code>model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

#opt = SGD( lr=0.01)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)
</code>```

The result of 2 classes something like this i lost the actual result of it:

```<code>Epoch 29/35
46/46 [==============================] - 188s 4s/step - loss: 0.6511 - accuracy: 0.5880 - val_loss: 0.7534 - val_accuracy: 0.5175

</code>```

The result with 4 classes is:

```<code>46/46 [==============================] - 367s 8s/step - loss: -10550614391401.7266 - accuracy: 0.2541 - val_loss: -15023441182720.0000 - val_accuracy: 0.2354
</code>```

答:
You network with 4 classes should look like this

model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(4 activation='softmax'))

#opt = SGD( lr=0.01)

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

```

loss should be categorical_crossentropy and last layer should be softmax with 4 possible outcomes.

Body:
I tried CNN model on two classes and got 80% but when i tried the same model with 4 classes i got very bad result. What is the reason pls help.
The model of CNN i used is:

model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

#opt = SGD( lr=0.01)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)

The result of 2 classes something like this i lost the actual result of it:

Epoch 29/35
46/46 [==============================] - 188s 4s/step - loss: 0.6511 - accuracy: 0.5880 - val_loss: 0.7534 - val_accuracy: 0.5175

The result with 4 classes is:

46/46 [==============================] - 367s 8s/step - loss: -10550614391401.7266 - accuracy: 0.2541 - val_loss: -15023441182720.0000 - val_accuracy: 0.2354

Body:
You network with 4 classes should look like this

model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(4 activation='softmax'))

#opt = SGD( lr=0.01)

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

loss should be categorical_crossentropy and last layer should be softmax with 4 possible outcomes.


问:
Number items in loop
Here's the code

```<code>river_and_countries = {
    'Nile' : 'egypt',
    'Amazon' : 'Brazil',
    'yangtze' : 'china',
    'mississippi' : 'united states of america',
    'yenisei' : 'russia',
    'ob' : 'russia',
    'huang' : 'china',
}
num = len(river_and_countries) + 1
n = [value for value in range(1, num)]

print(f"Following are the longest rivers in the world and their countries (by order):\n")
for x in n:
    for river, country in river_and_countries.items():
        if country == 'united states of america':
            print(f"{x}. River {river.title()} is in the {country.title()}.")
        else:
            print(f"{x}. River {river.title()} in {country.title()}.")
</code>```

I want to print a list of top seven longest rivers and also add a number to them at the front, but for every number it keeps repeating the list.

How can I assign a number to a each river once?

Current output:

Following are the longest rivers in the world and their countries (by order):
    1. River Nile in Egypt.
    1. River Amazon in Brazil.
    1. River Yangtze in China.
    1. River Mississippi is in the United States Of America.
    1. River Yenisei in Russia.
    1. River Ob in Russia.
    1. River Huang in China.
    2. River Nile in Egypt.
    2. River Amazon in Brazil.
    2. River Yangtze in China.
    2. River Mississippi is in the United States Of America.
    2. River Yenisei in Russia.
    2. River Ob in Russia.
    2. River Huang in China.
    3. River Nile in Egypt.
    3. River Amazon in Brazil.
    3. River Yangtze in China.
    3. River Mississippi is in the United States Of America.
    3. River Yenisei in Russia.
    3. River Ob in Russia.
    3. River Huang in China.
    4. River Nile in Egypt.
    4. River Amazon in Brazil.
    4. River Yangtze in China.
    4. River Mississippi is in the United States Of America.
    4. River Yenisei in Russia.
    4. River Ob in Russia.
    4. River Huang in China.
    5. River Nile in Egypt.
    5. River Amazon in Brazil.
    5. River Yangtze in China.
    5. River Mississippi is in the United States Of America.
    5. River Yenisei in Russia.
    5. River Ob in Russia.
    5. River Huang in China.
    6. River Nile in Egypt.
    6. River Amazon in Brazil.
    6. River Yangtze in China.
    6. River Mississippi is in the United States Of America.
    6. River Yenisei in Russia.
    6. River Ob in Russia.
    6. River Huang in China.
    7. River Nile in Egypt.
    7. River Amazon in Brazil.
    7. River Yangtze in China.
    7. River Mississippi is in the United States Of America.
    7. River Yenisei in Russia.
    7. River Ob in Russia.
    7. River Huang in China.
    [Finished in 0.2s]
```

答:
Remove that nested for loop and use the enumerate() function to generate the number:</p>

```<code>print(f"Following are the longest rivers in the world and their countries (by order):\n")

for i, (river, country) in enumerate(river_and_countries.items(), start=1):
    if country == 'united states of america':
        print(f"{i}. River {river.title()} is in the {country.title()}.")
    else:
        print(f"{i}. River {river.title()} in {country.title()}.")
</code>```

```<code>Following are the longest rivers in the world and their countries (by order):

1. River Nile in Egypt.
2. River Amazon in Brazil.
3. River Yangtze in China.
4. River Mississippi is in the United States Of America.
5. River Yenisei in Russia.
6. River Ob in Russia.
7. River Huang in China.
</code>```

Title: Number items in loop

Body:
Here's the code

river_and_countries = {
    'Nile' : 'egypt',
    'Amazon' : 'Brazil',
    'yangtze' : 'china',
    'mississippi' : 'united states of america',
    'yenisei' : 'russia',
    'ob' : 'russia',
    'huang' : 'china',
}
num = len(river_and_countries) + 1
n = [value for value in range(1, num)]

print(f"Following are the longest rivers in the world and their countries (by order):\n")
for x in n:
    for river, country in river_and_countries.items():
        if country == 'united states of america':
            print(f"{x}. River {river.title()} is in the {country.title()}.")
        else:
            print(f"{x}. River {river.title()} in {country.title()}.")

I want to print a list of top seven longest rivers and also add a number to them at the front, but for every number it keeps repeating the list.

How can I assign a number to a each river once?

Current output:

Following are the longest rivers in the world and their countries (by order):
    1. River Nile in Egypt.
    1. River Amazon in Brazil.
    1. River Yangtze in China.
    1. River Mississippi is in the United States Of America.
    1. River Yenisei in Russia.
    1. River Ob in Russia.
    1. River Huang in China.
    2. River Nile in Egypt.
    2. River Amazon in Brazil.
    2. River Yangtze in China.
    2. River Mississippi is in the United States Of America.
    2. River Yenisei in Russia.
    2. River Ob in Russia.
    2. River Huang in China.
    3. River Nile in Egypt.
    3. River Amazon in Brazil.
    3. River Yangtze in China.
    3. River Mississippi is in the United States Of America.
    3. River Yenisei in Russia.
    3. River Ob in Russia.
    3. River Huang in China.
    4. River Nile in Egypt.
    4. River Amazon in Brazil.
    4. River Yangtze in China.
    4. River Mississippi is in the United States Of America.
    4. River Yenisei in Russia.
    4. River Ob in Russia.
    4. River Huang in China.
    5. River Nile in Egypt.
    5. River Amazon in Brazil.
    5. River Yangtze in China.
    5. River Mississippi is in the United States Of America.
    5. River Yenisei in Russia.
    5. River Ob in Russia.
    5. River Huang in China.
    6. River Nile in Egypt.
    6. River Amazon in Brazil.
    6. River Yangtze in China.
    6. River Mississippi is in the United States Of America.
    6. River Yenisei in Russia.
    6. River Ob in Russia.
    6. River Huang in China.
    7. River Nile in Egypt.
    7. River Amazon in Brazil.
    7. River Yangtze in China.
    7. River Mississippi is in the United States Of America.
    7. River Yenisei in Russia.
    7. River Ob in Russia.
    7. River Huang in China.
    [Finished in 0.2s]

Body:
Remove that nested for loop and use the enumerate() function to generate the number:

print(f"Following are the longest rivers in the world and their countries (by order):\n")

for i, (river, country) in enumerate(river_and_countries.items(), start=1):
    if country == 'united states of america':
        print(f"{i}. River {river.title()} is in the {country.title()}.")
    else:
        print(f"{i}. River {river.title()} in {country.title()}.")

Following are the longest rivers in the world and their countries (by order):

1. River Nile in Egypt.
2. River Amazon in Brazil.
3. River Yangtze in China.
4. River Mississippi is in the United States Of America.
5. River Yenisei in Russia.
6. River Ob in Russia.
7. River Huang in China.


问:
Asp.Net MVC Binding. Get List<Model> at controller
I've got view:

```<code>    @using (Html.BeginForm("ProcessRoute", "Calculator"))
    {

            @Html.TextBox("CityArrival", null, new { @style = "width: 300px;" })
            @Html.TextBox("CityDeparture", null, new { @style = "width: 300px;" })
            @{ Html.RenderPartial("BusModelList", @Model.BusModels);  }
            <input id="submit" type="submit" value="Поиск" />
    }
</code>```

partial view:

```<code>@model List<ViewModels.GroupedBusModelsSelectable>
<table>
    @foreach (var item in Model)
    {
        <tr>
            <td colspan="3" align="left">@item.BusType.Name</td>
        </tr>
       foreach (var bus in item.BusModels.OrderBy(c => c.Bus.NumPlaces).ToList())
       {
            @Html.EditorFor(x=>bus);
       }
    }
</table>
</code>```

and editor:

```<code>@model ViewModels.BusModelSelectable
<tr>
    <td>
        @Html.HiddenFor(x => x.Bus.Id)
        @Html.HiddenFor(x => x.Bus.FullName)
        @Html.CheckBoxFor(x => x.IsSelected)
    </td>
    <td>
        <img>
    <td>
        @Model.Bus.FullName
    </td>
</tr>
</code>```

Now I would like to get all busModels(with selected) at controller:

```<code>   [HttpPost]
   public ActionResult ProcessRoute(string CityArrival, string CityDeparture, IEnumerable<GroupedBusModelsSelectable> BusModels)
</code>```

By some reason BusModels is null

At HttpContext.Request.Form

I see list of (bus.IsSelected, bus.Bus.Id). How can I get it at controller?

DECISION

After Nick Larsen advice I understand that I should have indexed names at my html. Because I have two-level collection, I should do it  twice.

PartialView:

```<code>@model List<Avtobus66.ViewModels.GroupedBusModelsSelectable>
<table>
        @for (int j = 0; j < Model.Count(); j++)
        {
            <tr>
                <td colspan="3" align="left">@Model[j].BusType.Name</td>
            </tr>
            for (int i = 0; i < Model[j].BusModels.Count(); i++)
            {
               @Html.EditorFor(x => Model[j].BusModels[i]);
            }
        }
</table>
</code>```

Let's see html now:

```<code><input name="[0].BusModels[0].Bus.Id" type="hidden" value="1" />
<input name="[0].BusModels[0].IsSelected" type="checkbox" value="true" />
<input name="[0].BusModels[0].IsSelected" type="hidden" value="false" />

<input name="[0].BusModels[1].Bus.Id" type="hidden" value="2" />
<input name="[0].BusModels[1].IsSelected" type="checkbox" value="true" />
<input name="[0].BusModels[1].IsSelected" type="hidden" value="false" />

<input name="[0].BusModels[2].Bus.Id" type="hidden" value="3" />
<input name="[0].BusModels[2].IsSelected" type="checkbox" value="true" />
<input name="[0].BusModels[2].IsSelected" type="hidden" value="false" />

<input name="[1].BusModels[0].Bus.Id" type="hidden" value="4" />
<input name="[1].BusModels[0].IsSelected" type="checkbox" value="true" />
<input name="[1].BusModels[0].IsSelected" type="hidden" value="false" />
</code>```

At controller I'm ready get 2level collection now. At my case

```<code>IEnumerable<GroupedBusModelsSelectable> BusModels
</code>```

it works. Now I'm agree with Nick, I should refactoring my table markup spaghetti.

答:
You need to look at what you are sending to the browser.  In order for the BusModels parameter to be populated, you need to send to the browser something like:

```<code><input type="hidden" name="BusModels[0].someProperty" value="whatever" />
<input type="hidden" name="BusModels[0].someOtherProperty" value="whatever" />
<input type="checkbox" name="BusModels[0].someBoolean" />

<input type="hidden" name="BusModels[1].someProperty" value="whatever" />
<input type="hidden" name="BusModels[1].someOtherProperty" value="whatever" />
<input type="checkbox" name="BusModels[1].someBoolean" />
</code>```

Notice that the only thing that changed in the name is the value inside of the square brackets.  There are other ways to do this, but they are all variants on this method and you can find out more about them here.  Since you list no controls to dynamically add new elements, I suggest the rewriting the editor as a template and using the built in functionality to build your inputs.

To achieve this, pass your model to the partial view already sorted, then instead of using a foreach, use a plain for loop and call an editor for indexes of your model.

View:

```<code>@using (Html.BeginForm("ProcessRoute", "Calculator"))
{
    @Html.TextBox("CityArrival", null, new { @style = "width: 300px;" })
    @Html.TextBox("CityDeparture", null, new { @style = "width: 300px;" })
    @{ Html.RenderPartial("BusModelList", Model.BusModels.OrderBy(c => c.Bus.NumPlaces).ToList());  }
    <input id="submit" type="submit" value="Поиск" />
}
</code>```

Partial View:

```<code>@model List<ViewModels.GroupedBusModelsSelectable>

<table>
@foreach (var item in Model)
{
    <tr>
        <td colspan="3" align="left">@item.BusType.Name</td>
    </tr>
    for (int i = 0; i < Model.Count; i++)
    {
        @Html.EditorFor(x => x[i]);
    }
}
</table>
</code>```

That should do the trick.  The only thing other than this that I would mention is that you have split up the table and the rows of the table which creates a tight coupling between the view and the partial view.  A better way to handle this is to remove the coupling and put all related constructs in the same place.  The easiest and cleanest way to do this is to use a razor inline template, or move away from the table altogether because semantically editors are not tabular data.

Body:
I've got view:

    @using (Html.BeginForm("ProcessRoute", "Calculator"))
    {

            @Html.TextBox("CityArrival", null, new { @style = "width: 300px;" })
            @Html.TextBox("CityDeparture", null, new { @style = "width: 300px;" })
            @{ Html.RenderPartial("BusModelList", @Model.BusModels);  }
            <input id="submit" type="submit" value="Поиск" />
    }

partial view:

@model List<ViewModels.GroupedBusModelsSelectable>

    @foreach (var item in Model)
    {

            @item.BusType.Name

       foreach (var bus in item.BusModels.OrderBy(c => c.Bus.NumPlaces).ToList())
       {
            @Html.EditorFor(x=>bus);
       }
    }

and editor:

@model ViewModels.BusModelSelectable

        @Html.HiddenFor(x => x.Bus.Id)
        @Html.HiddenFor(x => x.Bus.FullName)
        @Html.CheckBoxFor(x => x.IsSelected)

        @Model.Bus.FullName

Now I would like to get all busModels(with selected) at controller:

   [HttpPost]
   public ActionResult ProcessRoute(string CityArrival, string CityDeparture, IEnumerable<GroupedBusModelsSelectable> BusModels)

By some reason BusModels is null

At HttpContext.Request.Form

I see list of (bus.IsSelected, bus.Bus.Id). How can I get it at controller?

DECISION

After Nick Larsen advice I understand that I should have indexed names at my html. Because I have two-level collection, I should do it  twice.

PartialView:

@model List<Avtobus66.ViewModels.GroupedBusModelsSelectable>

        @for (int j = 0; j < Model.Count(); j++)
        {

                @Model[j].BusType.Name

            for (int i = 0; i < Model[j].BusModels.Count(); i++)
            {
               @Html.EditorFor(x => Model[j].BusModels[i]);
            }
        }

Let's see html now:

<input name="[0].BusModels[0].Bus.Id" type="hidden" value="1" />
<input name="[0].BusModels[0].IsSelected" type="checkbox" value="true" />
<input name="[0].BusModels[0].IsSelected" type="hidden" value="false" />

<input name="[0].BusModels[1].Bus.Id" type="hidden" value="2" />
<input name="[0].BusModels[1].IsSelected" type="checkbox" value="true" />
<input name="[0].BusModels[1].IsSelected" type="hidden" value="false" />

<input name="[0].BusModels[2].Bus.Id" type="hidden" value="3" />
<input name="[0].BusModels[2].IsSelected" type="checkbox" value="true" />
<input name="[0].BusModels[2].IsSelected" type="hidden" value="false" />

<input name="[1].BusModels[0].Bus.Id" type="hidden" value="4" />
<input name="[1].BusModels[0].IsSelected" type="checkbox" value="true" />
<input name="[1].BusModels[0].IsSelected" type="hidden" value="false" />

At controller I'm ready get 2level collection now. At my case

IEnumerable<GroupedBusModelsSelectable> BusModels

it works. Now I'm agree with Nick, I should refactoring my table markup spaghetti.

Body:
You need to look at what you are sending to the browser.  In order for the BusModels parameter to be populated, you need to send to the browser something like:

<input type="hidden" name="BusModels[0].someProperty" value="whatever" />
<input type="hidden" name="BusModels[0].someOtherProperty" value="whatever" />
<input type="checkbox" name="BusModels[0].someBoolean" />

<input type="hidden" name="BusModels[1].someProperty" value="whatever" />
<input type="hidden" name="BusModels[1].someOtherProperty" value="whatever" />
<input type="checkbox" name="BusModels[1].someBoolean" />

Notice that the only thing that changed in the name is the value inside of the square brackets.  There are other ways to do this, but they are all variants on this method and you can find out more about them here.  Since you list no controls to dynamically add new elements, I suggest the rewriting the editor as a template and using the built in functionality to build your inputs.

To achieve this, pass your model to the partial view already sorted, then instead of using a foreach, use a plain for loop and call an editor for indexes of your model.

View:

@using (Html.BeginForm("ProcessRoute", "Calculator"))
{
    @Html.TextBox("CityArrival", null, new { @style = "width: 300px;" })
    @Html.TextBox("CityDeparture", null, new { @style = "width: 300px;" })
    @{ Html.RenderPartial("BusModelList", Model.BusModels.OrderBy(c => c.Bus.NumPlaces).ToList());  }
    <input id="submit" type="submit" value="Поиск" />
}

Partial View:

@model List<ViewModels.GroupedBusModelsSelectable>

<table>
@foreach (var item in Model)
{
    <tr>
        <td colspan="3" align="left">@item.BusType.Name</td>
    </tr>
    for (int i = 0; i < Model.Count; i++)
    {
        @Html.EditorFor(x => x[i]);
    }
}
</table>

That should do the trick.  The only thing other than this that I would mention is that you have split up the table and the rows of the table which creates a tight coupling between the view and the partial view.  A better way to handle this is to remove the coupling and put all related constructs in the same place.  The easiest and cleanest way to do this is to use a razor inline template, or move away from the table altogether because semantically editors are not tabular data.


问:
Java + SOAP: Unexpected IndexOutOfBoundsException when executing the same SOAP service twice
I'm using the Jakarta SOAP API (jakarta.xml.soap) Maven library in conjunction with Java. I'm attempting to execute the same SOAP service (let's call this service A) twice in a row to retrieve a session ID of some sort. I'm using a Mac.

I'm able to do this operation twice in a row in SOAP UI 5.5.0, but am unable to reproduce the same result in Java 12:

```<code>responseMessage = SOAPConnectionFactory.newInstance().createConnection().call(
MessageFactory.newInstance().createMessage(new MimeHeaders(), someSoapByteStream), targetURL);
</code>```

This is the SOAP body I provide:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:user="redacted">
<soapenv:Header/>
<soapenv:Body>
    <user:getSessionId>
        <!--Optional:-->
        <userCode>?</userCode>
        <!--Optional:-->
        <ipAddress>?</ipAddress>
    </user:getSessionId>
</soapenv:Body>
</soapenv:Envelope>
</code>```

I am calling a POST URL ON some URL https:{redacted}, and getting this back on the first service call:

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
    <ns2:getSessionIdResponse xmlns:ns2="redacted">
        <sessionId>1caf23db-a04c-11ea-8511-e1c09ad12ebb</sessionId>
    </ns2:getSessionIdResponse>
</soap:Body>
</soap:Envelope>
</code>```

When I attempt to execute this service A twice in a row in SOAP using Java, the first call is successful but the second one returns the following Exception:

```<code>    Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl:
    com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
    at
    com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:127)
    at utils.plugins.LocalSOAPUtils.callMessage(LocalSOAPUtils.java:115)
    ... 3 more
Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
    at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:259)
    at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:123)
    ... 4 more
    Caused by: java.lang.IndexOutOfBoundsException: Range [0, 0 + -1) out of bounds for length 1024
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82)
    at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343)
    at java.base/java.util.Objects.checkFromIndexSize(Objects.java:424)
    at java.base/java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:155)
    at java.base/sun.net.www.http.PosterOutputStream.write(PosterOutputStream.java:78)
    at com.sun.xml.messaging.saaj.soap.MessageImpl.writeTo(MessageImpl.java:1396)
    at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:216)
... 5
</code>```

The only way I can get this service to execute successfully again is to run the code from the very beginning, in which case the first call will succeed again but the second will not.

What could possibly be going on here to cause this behaviour? Are there some static variables being set within Jakarta SOAP that is causing the first call to always succeed but the second to always fail? What exactly about the second service call is out of bounds?

答:
OK, so it turns out I was calling the above method on the same byte stream, which meant that the second time I called it, the position of the stream had moved, therefore causing the above error.

I fixed the issue by simply initializing a new ByteStream:

responseMessage = SOAPConnectionFactory.newInstance().createConnection().call(
MessageFactory.newInstance().createMessage(new MimeHeaders(), new ByteArrayInputStream(someSoapByteStreamAsString.getBytes())), targetURL);

Body:
I'm using the Jakarta SOAP API (jakarta.xml.soap) Maven library in conjunction with Java. I'm attempting to execute the same SOAP service (let's call this service A) twice in a row to retrieve a session ID of some sort. I'm using a Mac.

I'm able to do this operation twice in a row in SOAP UI 5.5.0, but am unable to reproduce the same result in Java 12:

responseMessage = SOAPConnectionFactory.newInstance().createConnection().call(
MessageFactory.newInstance().createMessage(new MimeHeaders(), someSoapByteStream), targetURL);

This is the SOAP body I provide:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:user="redacted">
<soapenv:Header/>
<soapenv:Body>
    <user:getSessionId>

        <userCode>?</userCode>

        <ipAddress>?</ipAddress>
    </user:getSessionId>
</soapenv:Body>
</soapenv:Envelope>

I am calling a POST URL ON some URL https:{redacted}, and getting this back on the first service call:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
    <ns2:getSessionIdResponse xmlns:ns2="redacted">
        <sessionId>1caf23db-a04c-11ea-8511-e1c09ad12ebb</sessionId>
    </ns2:getSessionIdResponse>
</soap:Body>
</soap:Envelope>

When I attempt to execute this service A twice in a row in SOAP using Java, the first call is successful but the second one returns the following Exception:

    Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl:
    com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
    at
    com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:127)
    at utils.plugins.LocalSOAPUtils.callMessage(LocalSOAPUtils.java:115)
    ... 3 more
Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Message send failed
    at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:259)
    at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:123)
    ... 4 more
    Caused by: java.lang.IndexOutOfBoundsException: Range [0, 0 + -1) out of bounds for length 1024
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82)
    at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343)
    at java.base/java.util.Objects.checkFromIndexSize(Objects.java:424)
    at java.base/java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:155)
    at java.base/sun.net.www.http.PosterOutputStream.write(PosterOutputStream.java:78)
    at com.sun.xml.messaging.saaj.soap.MessageImpl.writeTo(MessageImpl.java:1396)
    at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:216)
... 5

The only way I can get this service to execute successfully again is to run the code from the very beginning, in which case the first call will succeed again but the second will not.

What could possibly be going on here to cause this behaviour? Are there some static variables being set within Jakarta SOAP that is causing the first call to always succeed but the second to always fail? What exactly about the second service call is out of bounds?


问:
How to compare two enums?
I have two enums:

```<code>public enum UserType {
    USER,
    EMPLOYER

}
</code>```

```<code>public enum UserDetails {
    USER,
    EMPLOYER
}
</code>```

I try to compare this by this:

```<code>if(UserType.USER.equals(UserDetails.USER)){
    return true;
}
</code>```

but i can't because, my equals() throw me this:

```<code>equals() between objects of inconvertible types 'UserType' and 'UserDetails'
</code>```

so, how can I compare two values from two diffrent enums?

答:
Try to compare their names

```<code>if(UserType.USER.name().equals(UserDetails.USER.name())){
    return true;
}
</code>```

Reading other answers i've decided to give more extended answer. I have to agree thats such solution is not good enough, cause it's not about enums - it's about string comparing. Enums may be changed and everythig will not work properly. Ok.
I think that there could be better solutions - of course:

Use only one type of enum - it's perfect i think(but author has different enums)

Compare names of enums - well it's working but realy not "clever" use of enum

Make some mapping - why not - but its hard linking of two different enums and it is not good enough

```<code>enum UserType {
   USER,
   EMPLOYER;

   public boolean isLike(UserDetails details) {
       switch (this) {
           case USER:
               return details == UserDetails.USER;
           case EMPLOYER:
               return details == UserDetails.EMPLOYER;
       }
       return false;
   }
}

enum UserDetails {
   USER,
   EMPLOYER;
}

if(UserType.USER.isLike(UserDetails.USER)){
           // do something
}
</code>```

So we see that's there is no better decision than rewrite the code and make only one enum. But everything depends on the issue:

We don't know why there are two enums - perhaps author supporting legacy code

We don't know why author has to compare these different enums

Does proposed decision solve this concrete problem - yes. Is it good - no

Title: How to compare two enums?

Body:
I have two enums:

public enum UserType {
    USER,
    EMPLOYER

}

public enum UserDetails {
    USER,
    EMPLOYER
}

I try to compare this by this:

if(UserType.USER.equals(UserDetails.USER)){
    return true;
}

but i can't because, my equals() throw me this:

equals() between objects of inconvertible types 'UserType' and 'UserDetails'

so, how can I compare two values from two diffrent enums?

Body:
Try to compare their names

if(UserType.USER.name().equals(UserDetails.USER.name())){
    return true;
}

Reading other answers i've decided to give more extended answer. I have to agree thats such solution is not good enough, cause it's not about enums - it's about string comparing. Enums may be changed and everythig will not work properly. Ok.
I think that there could be better solutions - of course:

Use only one type of enum - it's perfect i think(but author has different enums)

Compare names of enums - well it's working but realy not "clever" use of enum

Make some mapping - why not - but its hard linking of two different enums and it is not good enough

enum UserType {
   USER,
   EMPLOYER;

   public boolean isLike(UserDetails details) {
       switch (this) {
           case USER:
               return details == UserDetails.USER;
           case EMPLOYER:
               return details == UserDetails.EMPLOYER;
       }
       return false;
   }
}

enum UserDetails {
   USER,
   EMPLOYER;
}

if(UserType.USER.isLike(UserDetails.USER)){
           // do something
}

So we see that's there is no better decision than rewrite the code and make only one enum. But everything depends on the issue:

We don't know why there are two enums - perhaps author supporting legacy code

We don't know why author has to compare these different enums

Does proposed decision solve this concrete problem - yes. Is it good - no


问:
GzipHandler in Jetty 9.4 - increased wait times
Recently we switched to Jetty 9.4 from Jetty 9.0. Jetty 9.4 comes with GzipHandler so we used that. At the request processing time we flush out response to send back (link) headers to browser early, by doing response.flushBuffer(), this is done on purpose. In jetty 9.0's GzipFilter response used to be flushed right away but in GzipHandler it isn't flushed immediately. This is causing increase in wait time in browser as headers are received little late on browser side. I was wondering how can we make this response flush immediately in GzipHanlder in Jetty9.4 ?

BTW - we are talking about ~40Ms wait increased wait time here!

答:
This was a bug in GzipHandler related to flush of empty initial buffers (a flush before attempting to send any data).

Issue https://github.com/eclipse/jetty.project/issues/4835 has been closed.

The fix is present in Jetty 9.4.29.v20200521 (now available on https://eclipse.org/jetty/ and maven central)


问:
SQLite - Getting SUM from a Identical ID

I am wanting to get the subtotal for each Unique Order ID. For example, 3 orders made by OrderID 10248 would total to

$168.0 + $98.0 + $174.0 = $440.0.

This is what I have so far in SQLite

```<code>SELECT OrderID, UnitPrice, Quantity,
       Discount, '$' || ((UnitPrice * Quantity) - (Discount * (UnitPrice * Quantity)))
    AS Subtotal
  FROM OrderDetail
</code>```

I have tried GROUP BY OrderID, but that only gets the first Subtotal of each OrderID.

Any hints to getting the total would be appreciated.

答:
Getting subtotals for each OrderID can be emulated by this query :

```<code>WITH OD AS
(
 SELECT OrderID,
        UnitPrice, Quantity, Discount,
       (UnitPrice * Quantity) * ( 1 - Discount ) AS Subtotal
   FROM OrderDetail
)
SELECT * FROM OD
UNION ALL
SELECT OrderID, Null, Null, Null, '$' || SUM( Subtotal )
  FROM OD
 GROUP BY OrderID
 ORDER BY OrderID
</code>```

Indeed, some other DB Management Systems use some functions and methods such as Cube(), Rollup() and GROUPING SETS().

Demo

Body:
I am wanting to get the subtotal for each Unique Order ID. For example, 3 orders made by OrderID 10248 would total to

$168.0 + $98.0 + $174.0 = $440.0.

This is what I have so far in SQLite

SELECT OrderID, UnitPrice, Quantity,
       Discount, '$' || ((UnitPrice * Quantity) - (Discount * (UnitPrice * Quantity)))
    AS Subtotal
  FROM OrderDetail

I have tried GROUP BY OrderID, but that only gets the first Subtotal of each OrderID.

Any hints to getting the total would be appreciated.

Body:
Getting subtotals for each OrderID can be emulated by this query :

WITH OD AS
(
 SELECT OrderID,
        UnitPrice, Quantity, Discount,
       (UnitPrice * Quantity) * ( 1 - Discount ) AS Subtotal
   FROM OrderDetail
)
SELECT * FROM OD
UNION ALL
SELECT OrderID, Null, Null, Null, '$' || SUM( Subtotal )
  FROM OD
 GROUP BY OrderID
 ORDER BY OrderID

Indeed, some other DB Management Systems use some functions and methods such as Cube(), Rollup() and GROUPING SETS().

Demo


问:
jquery animate scrolltop callback
I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

```<code>$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});
</code>```

答:
```<code>if( $(window).scrollTop() > 0 ) {
    $('html').animate({scrollTop:0}, 1000, 'swing', function(){

        //callback after animate

    });
} else {
    // callback right now (no wait)
}
</code>```

Title: jquery animate scrolltop callback

Body:
I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});


问:
I can't generate ejbDeploy with Bean Validation
I can't generate the folder ejbDeploy when I am using Bean Validation Annotations. My project use EJB 2.1 and JEE 7 with IBM Websphere Application Server 9. I tried to use Bean Validation in 1.1.0.FINAL and 2.0.0FINAL, but when I am generate the ejbDeploy, I get the following error.

Can anyone help please?

答:
The error suggests your application indirectly references the class com.ibm.wsspi.cluster.Identity, so that class will need to be added to the classpath for the ejbDeploy step.  The ejbdeploy command does have a -cp option for this purpose.  That particular class is made available in the WebSphere thin client JARs. For example, if this is a JAX-WS application, then you might include <WAS_INSTALL>/runtimes/com.ibm.jaxws.thinclient_9.0.jar to the ejbdeploy classpath.

Alternatively, beginning with WebSphere Application Sever v9.0.5.0 the EJBDeploy step is no longer required if the application does not contain EJB Entity beans. The deployment artifacts will be generated for you dynamically at runtime, as needed. Note that since your application does include remote EJB interfaces, you may still need to generate RMI Stub classes if using a thin client. The Stub classes may be generated using RMIC from the JDK (with the -iiop option s) or the createEJBStubs command from WebSphere.


问:
flex-wrap not working as expected in Safari
On the homepage of http://www.shopifyexperte.de/ there are two flex-box modules, one under "Kundenstimmen" and one under "Neueste Beiträge...". The inner boxes are supposed to wrap when they go below 220px and not grow above 30% width. This works in latest Chrome, FF and Opera (all on Mac), but in Safari 8.0.5 (Mac) and any iOS browser the boxes never form a row even if there's enough room. They always wrap, each one on a row of its own.

The CSS for the container:

.homepage-testimonial-container {
 display: flex;
 display: -webkit-flex;
 -webkit-flex: 1;
 flex: 1;
 -webkit-flex-direction: row;
 flex-direction: row;
 -webkit-flex-wrap: wrap;
 flex-wrap: wrap;
 -webkit-justify-content: space-between;
 justify-content: space-between;
 -webkit-align-items: flex-start;
 align-items: flex-start;
 margin-top: 1em;
}```
</div>
</div>
</p>

<p>The CSS for the boxes inside the container:</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.homepage-testimonial {
 margin-bottom: 1em;
 min-width: 220px;
 max-width: 30%;
 -webkit-flex: 1 1 auto;
 flex: 1 1 auto;
}</code>```

If I disable -webkit-flex-wrap (effectively setting it to nowrap), all boxes line up in a row but eventually overflow the container when the browser window gets too narrow.

Is this some kind of bug in Safari/Webkit or am I doing something wrong here?

答:
There are other solutions that work for me.

In the .row container before and after are gets added with these properties:

```<code>row:before, .row:after {
 content: " ";
 display: table;
}
</code>```

so setting up the display: none or display: inline will solve the problem or setting up the content: none will also solve it.

```<code>.row:before, .row:after {
   display: none;
}
or
.row:before, .row:after {
   display: inline;
}

or
.row:before, .row:after {
   content: none
}
</code>```

Body:
On the homepage of http://www.shopifyexperte.de/ there are two flex-box modules, one under "Kundenstimmen" and one under "Neueste Beiträge...". The inner boxes are supposed to wrap when they go below 220px and not grow above 30% width. This works in latest Chrome, FF and Opera (all on Mac), but in Safari 8.0.5 (Mac) and any iOS browser the boxes never form a row even if there's enough room. They always wrap, each one on a row of its own.

The CSS for the container:

.homepage-testimonial-container {
 display: flex;
 display: -webkit-flex;
 -webkit-flex: 1;
 flex: 1;
 -webkit-flex-direction: row;
 flex-direction: row;
 -webkit-flex-wrap: wrap;
 flex-wrap: wrap;
 -webkit-justify-content: space-between;
 justify-content: space-between;
 -webkit-align-items: flex-start;
 align-items: flex-start;
 margin-top: 1em;
}

The CSS for the boxes inside the container:

.homepage-testimonial {
 margin-bottom: 1em;
 min-width: 220px;
 max-width: 30%;
 -webkit-flex: 1 1 auto;
 flex: 1 1 auto;
}

If I disable -webkit-flex-wrap (effectively setting it to nowrap), all boxes line up in a row but eventually overflow the container when the browser window gets too narrow.

Is this some kind of bug in Safari/Webkit or am I doing something wrong here?

Body:
There are other solutions that work for me.

In the .row container before and after are gets added with these properties:

row:before, .row:after {
 content: " ";
 display: table;
}

so setting up the display: none or display: inline will solve the problem or setting up the content: none will also solve it.

.row:before, .row:after {
   display: none;
}
or
.row:before, .row:after {
   display: inline;
}

or
.row:before, .row:after {
   content: none
}


问:
Query with DynamoDB Secondary Index AWS SDK 2 Java exception creating DynamoDbIndex object
I'm having trouble running a query against a secondary index, getting an exception:

Ex getting dynamodb scan: java.lang.IllegalArgumentException: Attempt to execute an operation that requires a secondary index without defining the index attributes in the table metadata. Index name: category-timestamp-index

Can someone guide me on how I'm doing this wrong?

My table is idIT_RSS_Sources and I've created an index category-timestamp-index.

screenshot attached of index

My code is:

```<code>DynamoDbEnhancedClient enhancedClient = getEnhancedDBClient(region);

 // Create a DynamoDbTable object

logger.debug("getting RSS Source category-timestamp-index");

//this throws the exception
DynamoDbIndex<RSS_Source> catIndex =
        enhancedClient.table("idIT_RSS_Sources",
        TableSchema.fromBean(RSS_Source.class))
         .index("category-timestamp-index");

                logger.debug("building query attributes");

                AttributeValue att = AttributeValue.builder()
                        .s(theCategory)
                        .build();

                Map<String, AttributeValue> expressionValues = new HashMap<>();
                expressionValues.put(":value", att);

                Expression expression = Expression.builder()
                        .expression("category = :value")
                        .expressionValues(expressionValues)
                        .build();

                // Create a QueryConditional object that's used in the query operation
                QueryConditional queryConditional = QueryConditional
                        .keyEqualTo(Key.builder().partitionValue(theCategory)
                        .build());

                logger.debug("calling catIndex.query in getRSS...ForCategory");

                Iterator<Page<RSS_Source>> dbFeedResults =  (Iterator<Page<RSS_Source>>) catIndex.query(
                        QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());
</code>```

答:
My working code is as below:
sortKey-index = GSI in dynamo db

```<code>List<Flow> flows = new ArrayList<>();
        DynamoDbIndex<Flow> flowBySortKey = table().index("sortKey-index");
        // Create a QueryConditional object that's used in the query operation
        QueryConditional queryConditional = QueryConditional
                        .keyEqualTo(Key.builder()
                        .partitionValue(sortKey)
                        .build());

        SdkIterable<Page<Flow>> dbFeedResults = flowBySortKey.query(
                        QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());

        dbFeedResults.forEach(flowPage -> {
            flows.addAll(flowPage.items());
        });
</code>```

Body:
I'm having trouble running a query against a secondary index, getting an exception:

Ex getting dynamodb scan: java.lang.IllegalArgumentException: Attempt to execute an operation that requires a secondary index without defining the index attributes in the table metadata. Index name: category-timestamp-index

Can someone guide me on how I'm doing this wrong?

My table is idIT_RSS_Sources and I've created an index category-timestamp-index.

screenshot attached of index

My code is:

DynamoDbEnhancedClient enhancedClient = getEnhancedDBClient(region);

 // Create a DynamoDbTable object

logger.debug("getting RSS Source category-timestamp-index");

//this throws the exception
DynamoDbIndex<RSS_Source> catIndex =
        enhancedClient.table("idIT_RSS_Sources",
        TableSchema.fromBean(RSS_Source.class))
         .index("category-timestamp-index");

                logger.debug("building query attributes");

                AttributeValue att = AttributeValue.builder()
                        .s(theCategory)
                        .build();

                Map<String, AttributeValue> expressionValues = new HashMap<>();
                expressionValues.put(":value", att);

                Expression expression = Expression.builder()
                        .expression("category = :value")
                        .expressionValues(expressionValues)
                        .build();

                // Create a QueryConditional object that's used in the query operation
                QueryConditional queryConditional = QueryConditional
                        .keyEqualTo(Key.builder().partitionValue(theCategory)
                        .build());

                logger.debug("calling catIndex.query in getRSS...ForCategory");

                Iterator<Page<RSS_Source>> dbFeedResults =  (Iterator<Page<RSS_Source>>) catIndex.query(
                        QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());

Body:
My working code is as below:
sortKey-index = GSI in dynamo db

List<Flow> flows = new ArrayList<>();
        DynamoDbIndex<Flow> flowBySortKey = table().index("sortKey-index");
        // Create a QueryConditional object that's used in the query operation
        QueryConditional queryConditional = QueryConditional
                        .keyEqualTo(Key.builder()
                        .partitionValue(sortKey)
                        .build());

        SdkIterable<Page<Flow>> dbFeedResults = flowBySortKey.query(
                        QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());

        dbFeedResults.forEach(flowPage -> {
            flows.addAll(flowPage.items());
        });


问:
Unit Testing on a NodeJS + Typescript AWS Lambda
Which one is the best way to unit test a lambda implemented in NodeJS using TypeScript like this dummy one:

import {Callback} from "aws-lambda";

export interface BinaryEvent {
  number1: number
  number2: number
}

export interface Result {
  result: number
}

export type BinaryOperation = (number1: number, number2: number) => number;

export type BinaryOperationHandler = ({number1, number2}: BinaryEvent, context: any, callback: Callback<Result>) => void;

export const addition: BinaryOperationHandler = ({number1, number2}, context, callback) => {
  setTimeout(() => callback(null, {result: (number1 + number2)}), 1000);
}
```

答:
I managed to find a way to unit testing using jest using jest.fn() like this:

import {addition} from "./index";

it('Sums 2 numbers', async() => {
  const number1 = 3, number2 = 2, callback = jest.fn();
  await addition({number1, number2}, {}, callback);
  expect(callback.mock.calls.length).toBe(1);
  expect(callback.mock.calls[0][1].result).toBe(number1 + number2);
})
```

A complete working dummy example is available in the github repo: https://github.com/jvillane/aws-sam-lambda-jest-unit-test

Body:
I managed to find a way to unit testing using jest using jest.fn() like this:

import {addition} from "./index";

it('Sums 2 numbers', async() => {
  const number1 = 3, number2 = 2, callback = jest.fn();
  await addition({number1, number2}, {}, callback);
  expect(callback.mock.calls.length).toBe(1);
  expect(callback.mock.calls[0][1].result).toBe(number1 + number2);
})

A complete working dummy example is available in the github repo: https://github.com/jvillane/aws-sam-lambda-jest-unit-test


问:
Deploy a simple Python bot
Code:

```<code>    import requests as rq
    from bs4 import BeautifulSoup as bs

    url = "https://apod.nasa.gov/apod/astropix.html"
    page = rq.get(url).content
    soup = bs(page, 'html.parser')
    response = soup.find('img')
    if response == None:
        imglink = soup.find('iframe')['src']
    else:
        imglink = 'https://apod.nasa.gov/apod/' + response['src']
    def main():
        sess = rq.Session()
        cid='**************'
        turl = 'https://api.telegram.org/bot*******************/'
        if response == None:
            imglink = soup.find('iframe')['src']
            params = {'chat_id':cid,'text':imglink}
            sess.post(turl + 'sendMessage', data=params)
        else:
            imglink = 'https://apod.nasa.gov/apod/' + response['src']
            title = soup.find('b').get_text()
            params = {'chat_id':cid,'photo':imglink,'caption':title}
           sess.post(turl + 'sendPhoto', data=params)

    if __name__ == '__main__':
        main()
</code>```

This is a simple bot for sending Nasa picture to my telegram channel. I will be modifying this script to make it happen everyday. But he Question is where do I host them, So that it will run all the time (free) . What is the correct way of doing it.

答:
I don't know of any providers that would host this for free. For cheap, AWS and Google Cloud all have simple solutions.

Ex: https://cloud.google.com/blog/products/application-development/how-to-schedule-a-recurring-python-script-on-gcp

Title: Deploy a simple Python bot

Body:
Code:

    import requests as rq
    from bs4 import BeautifulSoup as bs

    url = "https://apod.nasa.gov/apod/astropix.html"
    page = rq.get(url).content
    soup = bs(page, 'html.parser')
    response = soup.find('img')
    if response == None:
        imglink = soup.find('iframe')['src']
    else:
        imglink = 'https://apod.nasa.gov/apod/' + response['src']
    def main():
        sess = rq.Session()
        cid='**************'
        turl = 'https://api.telegram.org/bot*******************/'
        if response == None:
            imglink = soup.find('iframe')['src']
            params = {'chat_id':cid,'text':imglink}
            sess.post(turl + 'sendMessage', data=params)
        else:
            imglink = 'https://apod.nasa.gov/apod/' + response['src']
            title = soup.find('b').get_text()
            params = {'chat_id':cid,'photo':imglink,'caption':title}
           sess.post(turl + 'sendPhoto', data=params)

    if __name__ == '__main__':
        main()

This is a simple bot for sending Nasa picture to my telegram channel. I will be modifying this script to make it happen everyday. But he Question is where do I host them, So that it will run all the time (free) . What is the correct way of doing it.


问:
Microsoft Excel 2003 | IF Statements
Firstly I'd like to say my knowledge on Excel is fairly limited, and I'm learning as I go, so feel free to input/correct on anything.

I have a set of information formated as follows:

```<code>0.7 9.0 598287
0.7 10.0 598288
0.9 36.0 9186264
4.5 298.0 4071637
4.3 287.0 13896286
0.9 18.0 4011248
</code>```

I need a to create a formula, that takes each peice of data, the first decimal number, the second, and the final string of numbers. I've created a very long - and seemingly good statement, but it doesn't do exactly as I need. My Formula, and the outputs are as follows

```<code>=IF(LEN(J194)=14,RIGHT(J194,6),IF(LEN(J194)=15,RIGHT(J194,6),IF(LEN(J194)=16,RIGHT(J194,6),IF(LEN(J194)=17,RIGHT(J194,7),IF(LEN(J194)=18,RIGHT(J194,8),RIGHT(J194,8))))))

   **DATA**             **OUTPUT**       **LENGTH**

0.7 9.0 598287          598287               14
0.7 10.0 598288         598288               15
0.9 36.0 9186264        186264               16
4.5 298.0 4071637       4071637              17
4.3 287.0 13896286      13896286             18
0.9 18.0 4011248        011248               16
</code>```

The last column is the string length, as you can see - although the lengths of the strings are the same, I get a different output because the characters preceeding are shorter (1 digit,2 digit and 3 digit numbers)

What I need the formula to do, because my strings range from 14-18 characters in length, is to take the last digits no matter the overall cell length. I am also adding an E to the front of each of these numbers via =CONCATENATE - so I cannot overcount.

I'll gladly awnser any questions regarding my problem if clarifaction is needed.

Thanks for taking the time to read over my post!

Title: Microsoft Excel 2003 | IF Statements

Body:
Firstly I'd like to say my knowledge on Excel is fairly limited, and I'm learning as I go, so feel free to input/correct on anything.

I have a set of information formated as follows:

0.7 9.0 598287
0.7 10.0 598288
0.9 36.0 9186264
4.5 298.0 4071637
4.3 287.0 13896286
0.9 18.0 4011248

I need a to create a formula, that takes each peice of data, the first decimal number, the second, and the final string of numbers. I've created a very long - and seemingly good statement, but it doesn't do exactly as I need. My Formula, and the outputs are as follows

=IF(LEN(J194)=14,RIGHT(J194,6),IF(LEN(J194)=15,RIGHT(J194,6),IF(LEN(J194)=16,RIGHT(J194,6),IF(LEN(J194)=17,RIGHT(J194,7),IF(LEN(J194)=18,RIGHT(J194,8),RIGHT(J194,8))))))

   **DATA**             **OUTPUT**       **LENGTH**

0.7 9.0 598287          598287               14
0.7 10.0 598288         598288               15
0.9 36.0 9186264        186264               16
4.5 298.0 4071637       4071637              17
4.3 287.0 13896286      13896286             18
0.9 18.0 4011248        011248               16

The last column is the string length, as you can see - although the lengths of the strings are the same, I get a different output because the characters preceeding are shorter (1 digit,2 digit and 3 digit numbers)

What I need the formula to do, because my strings range from 14-18 characters in length, is to take the last digits no matter the overall cell length. I am also adding an E to the front of each of these numbers via =CONCATENATE - so I cannot overcount.

I'll gladly awnser any questions regarding my problem if clarifaction is needed.

Thanks for taking the time to read over my post!

Body: =RIGHT(J194,LEN(J194)-FIND(" ",J194,FIND(" ",J194)+1))


问:
How to set a button for changing color?
I am new to js and here I have a function changeColor() that I want to change the color of an image when a button is clicked, but it seems the function is not defined. Someone help?

Here is just a simple button in html, and I want to change img's color by clicking button:

  <button name="color" value="#33FFBD" type="button" onclick="changeColor();">
    Change
  </button>

```

<p>My js file, I want to get the value of the button and change to specified color for the img:</p>

```var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;

function getPixels(img) {
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}
function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
    R: (long >>> 16) & 0xff,
    G: (long >>> 8) & 0xff,
    B: long & 0xff
 };
}
Object.onclick = function changeColor()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementByName("color").value);

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}
```

答:
Change

```<code>var newColor = hexToRGB(document.getElementByName("color").value);
</code>```

To

```<code>var newColor = hexToRGB(document.getElementById("color").value);
</code>```

Title: How to set a button for changing color?

Body:
I am new to js and here I have a function changeColor() that I want to change the color of an image when a button is clicked, but it seems the function is not defined. Someone help?

Here is just a simple button in html, and I want to change img's color by clicking button:

  <button name="color" value="#33FFBD" type="button" onclick="changeColor();">
    Change
  </button>

My js file, I want to get the value of the button and change to specified color for the img:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;

function getPixels(img) {
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}
function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
    R: (long >>> 16) & 0xff,
    G: (long >>> 8) & 0xff,
    B: long & 0xff
 };
}
Object.onclick = function changeColor()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementByName("color").value);

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

Body:
Change

var newColor = hexToRGB(document.getElementByName("color").value);

To

var newColor = hexToRGB(document.getElementById("color").value);


问:
Host do not have forwarding table?
Suppose there are three routers between a source host and a destination host. Ignoring
fragmentation, an IP datagram sent from the source host to the destination host will travel
over how many interfaces? How many forwarding tables will be indexed to move the
datagram from the source to the destination?

answer: 8 interfaces; 3 forwarding tables

I cant understand, as I know the host also have a forwarding tables. because host also has a routing table

but why this answer is 3 forwarding tables. other people also saying 3 forwarding tables.

Could you explain this to me?

I understand in this case through 4 forwarding tables.

答:
I´d personally say this question has no answer in gereral.
Just think about the following:

Router Eth0 has two networks configured, 192.168.1.0/24 and 192.168.2.0/24
The packet has to travel from host with IP 192.168.1.5 to the host with ip 192.168.2.10

In this case your packet enters your router at Eth0 and leaves at Eth0 again so your number of interfaces in use is 7.

Regarding forwarding tables, many sources online confuse them with routing tables so things don´t get easier at all.
I know in Win 2000 you could show information about your routing table and also the information about the forwarding table.
For me this means that, at lease windows 2000, had an own forwarding table also meaning that it should be 4.

Anyways, since you could build some device that does not have routing nor forwarding tables this question cannot be answered.

Title: Host do not have forwarding table?


问:
How can I filter an object based upon value in ReactJS?
I have the below objects. Whose value is YES, I need to filter it and store it in variable.</p>

```<code>"CalcResult": {
        "result": [
            {
                "IS_RPOP": "YES",
                "IS_ENE": "NO",
                "IS_SLO": "YES",
                "STATUS": "INCOMPLETE"
            }
        ],
        "Info": {
            "STATUS": [
                "INCOMPLETE"
            ]
        }
    }
</code>```

答:
let CalcResult = {
  "result": [{
    "IS_RPOP": "YES",
    "IS_ENE": "NO",
    "IS_SLO": "YES",
    "STATUS": "INCOMPLETE"
  }],
  "Info": {
    "STATUS": [
      "INCOMPLETE"
    ]
  }
};
let arr = [];
Object.entries(CalcResult.result[0]).map((property, value) => {
  if (property[1].toUpperCase() === "YES")
    arr.push({
      [property[0]]: property[1]
    })
});
console.log(CalcResult.result[0], 'json');
console.log(arr, 'arr');```

Body:
I have the below objects. Whose value is YES, I need to filter it and store it in variable.

"CalcResult": {
        "result": [
            {
                "IS_RPOP": "YES",
                "IS_ENE": "NO",
                "IS_SLO": "YES",
                "STATUS": "INCOMPLETE"
            }
        ],
        "Info": {
            "STATUS": [
                "INCOMPLETE"
            ]
        }
    }