问:
Beginner: How to return user input?
I'm new to Java and I'm having trouble with this bit of code:

```<code>import java.util.Scanner;

public class BattleshipLogic {

    private final int rows;
    private final int cols;

    private final boolean[][] hits;
    private final boolean[][] ships;

    public BattleshipLogic(int numRows, int numCols) {
        this.rows = numRows;
        this.cols = numCols;

        this.hits = new boolean[rows][cols];
        this.ships = new boolean[rows][cols];
    }

    public void startGame() {
        placeShips();
        boolean gameOver = false;
        // draw field for the first time
        drawUI();

        while (!gameOver) {
            Target target = askForTarget();
            processTarget(target);
            drawUI();
        }
    }

    private Target askForTarget() {
        Target t = new Target();
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter your target:");
        t = input.nextInt();
        return t;
    }

    /*
     * This is just an example. You have to draw the ships by yourself.
     * If you don't like the way the UI is drawn, make your own stuff!
     */
    private void drawUI() {
        // draw the ui, see blatt01/oberflÃ¤che.txt for an example
        System.out.println("Schiffeversenken");
        System.out.println("================");
        System.out.println();

        // columns
        System.out.print("    ");
        for (int col = 0; col < this.cols; col++) {
            System.out.print(col + " ");
        }
        System.out.println();
        System.out.print("   _");
        for (int col = 0; col < this.cols; col++) {
            System.out.print("__");
        }
        System.out.println();
        for (int row = 0; row < this.rows; row++) {
            System.out.print(Character.toChars(3 + row));
            System.out.print(" |");

            System.out.println();
        }
    }

    private void placeShips() {
        // do useful stuff to place the ships here
        // see Blatt01 for rules
    }

    private void processTarget(Target target) {

    }

    /**
     * This class only holds the position
     * of a target.
     */
    private class Target {

        public int row;
        public int col;
    }
}
</code>```

Everytime I try to compile this error comes up:

error: incompatible types: int cannot be converted to BattleshipLogic.Target

I know that the types are different, but what kind of a type is Target? How can I get the user input to be assigned to t?

Thanks so much in advance!

答:
I think you want to do this.</p>

```<code> private Target askForTarget() {
            Target t = new Target();
            Scanner input = new Scanner(System.in);
            System.out.print("Please enter your target:");
            t.row = input.nextInt();
            t.col = input.nextInt();
            return t;
        }
</code>```

Title: Beginner: How to return user input?

Body:
I'm new to Java and I'm having trouble with this bit of code:

import java.util.Scanner;

public class BattleshipLogic {

    private final int rows;
    private final int cols;

    private final boolean[][] hits;
    private final boolean[][] ships;

    public BattleshipLogic(int numRows, int numCols) {
        this.rows = numRows;
        this.cols = numCols;

        this.hits = new boolean[rows][cols];
        this.ships = new boolean[rows][cols];
    }

    public void startGame() {
        placeShips();
        boolean gameOver = false;
        // draw field for the first time
        drawUI();

        while (!gameOver) {
            Target target = askForTarget();
            processTarget(target);
            drawUI();
        }
    }

    private Target askForTarget() {
        Target t = new Target();
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter your target:");
        t = input.nextInt();
        return t;
    }

    /*
     * This is just an example. You have to draw the ships by yourself.
     * If you don't like the way the UI is drawn, make your own stuff!
     */
    private void drawUI() {
        // draw the ui, see blatt01/oberflÃ¤che.txt for an example
        System.out.println("Schiffeversenken");
        System.out.println("================");
        System.out.println();

        // columns
        System.out.print("    ");
        for (int col = 0; col < this.cols; col++) {
            System.out.print(col + " ");
        }
        System.out.println();
        System.out.print("   _");
        for (int col = 0; col < this.cols; col++) {
            System.out.print("__");
        }
        System.out.println();
        for (int row = 0; row < this.rows; row++) {
            System.out.print(Character.toChars(3 + row));
            System.out.print(" |");

            System.out.println();
        }
    }

    private void placeShips() {
        // do useful stuff to place the ships here
        // see Blatt01 for rules
    }

    private void processTarget(Target target) {

    }

    /**
     * This class only holds the position
     * of a target.
     */
    private class Target {

        public int row;
        public int col;
    }
}

Everytime I try to compile this error comes up:

error: incompatible types: int cannot be converted to BattleshipLogic.Target

I know that the types are different, but what kind of a type is Target? How can I get the user input to be assigned to t?

Thanks so much in advance!

Body:
I think you want to do this.

 private Target askForTarget() {
            Target t = new Target();
            Scanner input = new Scanner(System.in);
            System.out.print("Please enter your target:");
            t.row = input.nextInt();
            t.col = input.nextInt();
            return t;
        }


来源: stackexchange

问:
Printing image displayed in WPF picture box
I am trying to print the image that displayed in ImageBox. I found this solution but when I tried it I got the following error:

What am I missing?

Thanks in advance.

答:
You could use the PrintDialog.PrintVisual method to print out an Image in WPF:

```<code>PrintDialog pd = new PrintDialog();
myPrintDialog.PrintVisual(imagebox, "Image");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could use the PrintDialog.PrintVisual method to print out an Image in WPF:

PrintDialog pd = new PrintDialog();
myPrintDialog.PrintVisual(imagebox, "Image");


问:
SoapUI error on request - NoClassDefFoundError
I am new to web services and I have deployed a web service locally ( I am able to see the wsdl)
I tried to query the web service by creating a request in SOAPUI.
The response I got back was

```<code>     <env:Fault>
     <faultcode>env:Server</faultcode>
     <faultstring>java.lang.NoClassDefFoundError: org/apache/commons/lang/StringEscapeUtils
     </faultstring>
  </env:Fault>
</code>```

I see a bunch of errors in the jboss console in eclipse...

```<code>11:53:06,226 ERROR [SOAPFaultHelperJAXWS]
SOAP requestexceptionjava.lang.RuntimeException:
java.lang.NoClassDefFoundError:org/apache/commons/lang/StringEscapeUtils
</code>```

Can someone help me in figuring out what the problem could be?

Is something wrong with the way I setup my SOAPUI or is it I missed something in my project(web service server)

答:
How do you exactly deploy the web service? For example, if you create an .aar archive, please verify that the corresponding jar (commons-lang.jar?) is available into the lib folder of the archive. For example:</p>

```<code>your_service_root
  ->META-INF
  ->lib
     ->commons-lang.jar
  -> com
     ->bla
        ->bla
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am new to web services and I have deployed a web service locally ( I am able to see the wsdl)
I tried to query the web service by creating a request in SOAPUI.
The response I got back was

     <env:Fault>
     <faultcode>env:Server</faultcode>
     <faultstring>java.lang.NoClassDefFoundError: org/apache/commons/lang/StringEscapeUtils
     </faultstring>
  </env:Fault>

I see a bunch of errors in the jboss console in eclipse...

11:53:06,226 ERROR [SOAPFaultHelperJAXWS]
SOAP requestexceptionjava.lang.RuntimeException:
java.lang.NoClassDefFoundError:org/apache/commons/lang/StringEscapeUtils

Can someone help me in figuring out what the problem could be?

Is something wrong with the way I setup my SOAPUI or is it I missed something in my project(web service server)

Body:
How do you exactly deploy the web service? For example, if you create an .aar archive, please verify that the corresponding jar (commons-lang.jar?) is available into the lib folder of the archive. For example:

your_service_root
  ->META-INF
  ->lib
     ->commons-lang.jar
  -> com
     ->bla
        ->bla


问:
CoreData ERROR : Class not found, using default NSManagedObject instead
I can't fix this error:

Class not found, using default NSManagedObject instead.

The problem is that the properties of the file xcdatamodeld file are set correctly

Look at this:

I don't understand the problem

答:
The problem is that you specify the Core Data entity Questions to be of class Questions (rather than NSManagedObject).  This is often done to add convenience property accessors and methods.

So you need to provide a Questions subclass of NSManagedObject (or just null the class name in the Core Data editor).

P.S. You probably want to label the class as Question (singular) rather than Questions (plural).


问:
Why does C++ vector size start out at 4294967296 yet the debugger reads it as 0?
From this sample code:

```<code>    vector<int> v;

    // cout << v.size() << endl;         // prints 0
    // cout << v.size() - 1 << endl;     // prints

    for (int i = 0; i < v.size() - 1; i++)
        cout << v[i] << endl;
</code>```

I got an out of range error. A few questions:

Why did the code go into the for loop?

Why did the 2nd cout print 4294967295?

Why is the 1st cout printing 0 when it's actually using 4294967296? The Visual Studio 2015 debugger is showing 0 for some reason.

答:
In your for loop condition, vals.size() - 1 will have its result be of an unsigned type aka std::vector<int>::size_type because that is the common type in the expression.

You have in effect:

```<code>std::vector<int>::size_type(0) - std::vector<int>::size_type(1)
</code>```

which will wrap around and produce a very large number...

Solution: You can use some little maths theory to achieve this thing (move the -1 to the other side of the inequality):

```<code>for (int i = 0; i + 1 < v.size(); i++)
     cout << v[i] << endl;
</code>```

Body:
From this sample code:

    vector<int> v;

    // cout << v.size() << endl;         // prints 0
    // cout << v.size() - 1 << endl;     // prints

    for (int i = 0; i < v.size() - 1; i++)
        cout << v[i] << endl;

I got an out of range error. A few questions:

Why did the code go into the for loop?

Why did the 2nd cout print 4294967295?

Why is the 1st cout printing 0 when it's actually using 4294967296? The Visual Studio 2015 debugger is showing 0 for some reason.

Body:
In your for loop condition, vals.size() - 1 will have its result be of an unsigned type aka std::vector<int>::size_type because that is the common type in the expression.

You have in effect:

std::vector<int>::size_type(0) - std::vector<int>::size_type(1)

which will wrap around and produce a very large number...

Solution: You can use some little maths theory to achieve this thing (move the -1 to the other side of the inequality):

for (int i = 0; i + 1 < v.size(); i++)
     cout << v[i] << endl;


问:
CRUD filtering/sorting doesnt work in asp.net
I have this database that I need to sort/filter. My current code shows no errors, but it does nothing as well.

ApplicationUsersController.cs

```<code>// GET: ApplicationUsers
        public ActionResult Index(string sortOrder, string searchString)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "email_desc" : "Email";
            var users = from c in db.Users
                           select c;
            if (!String.IsNullOrEmpty(searchString))
            {
                users = users.Where(c => c.Name.ToUpper().Contains(searchString.ToUpper())
                                       || c.Email.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    users = users.OrderByDescending(c => c.Name);
                    break;
                case "Email":
                    users = users.OrderBy(c => c.Email);
                    break;
                case "email_desc":
                    users = users.OrderByDescending(c => c.Email);
                    break;
                default:
                    users = users.OrderBy(c => c.Name);
                    break;
            }

            return View(db.Users.ToList());
        }
</code>```

Index.cshtml

```<code>@using (Html.BeginForm())
{
    <p>
        Find by name: @Html.TextBox("SearchString")
        <input type="submit" value="Search" />
    </p>
}

<table class="table">
    <tr>
        <th>
            @Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm })
        </th>
        <th>
            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
</code>```

Neither sorting, nor filtering seems to work. When sorting, address bar changes to

/ApplicationUsers?sortOrder=name_desc

but the order doesn't change at all. Maybe someone can see where is the problem?

EDIT:

Can it be 'var users = from c in db.Users select c; ' that the letter 'c' is wrong? How can I know for sure?

答:
you need to pass two params to the action Index:

```<code>@Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm, searchString = null })
</code>```

Body:
I have this database that I need to sort/filter. My current code shows no errors, but it does nothing as well.

ApplicationUsersController.cs

// GET: ApplicationUsers
        public ActionResult Index(string sortOrder, string searchString)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "email_desc" : "Email";
            var users = from c in db.Users
                           select c;
            if (!String.IsNullOrEmpty(searchString))
            {
                users = users.Where(c => c.Name.ToUpper().Contains(searchString.ToUpper())
                                       || c.Email.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    users = users.OrderByDescending(c => c.Name);
                    break;
                case "Email":
                    users = users.OrderBy(c => c.Email);
                    break;
                case "email_desc":
                    users = users.OrderByDescending(c => c.Email);
                    break;
                default:
                    users = users.OrderBy(c => c.Name);
                    break;
            }

            return View(db.Users.ToList());
        }

Index.cshtml

@using (Html.BeginForm())
{

        Find by name: @Html.TextBox("SearchString")
        <input type="submit" value="Search" />

}

            @Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm })

            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })

Neither sorting, nor filtering seems to work. When sorting, address bar changes to

/ApplicationUsers?sortOrder=name_desc

but the order doesn't change at all. Maybe someone can see where is the problem?

EDIT:

Can it be 'var users = from c in db.Users select c; ' that the letter 'c' is wrong? How can I know for sure?

Body:
you need to pass two params to the action Index:

@Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm, searchString = null })


问:
Four-part formula syntax in R
I am using the lfe package for high dimenaional fixed effects in R. I am having trouble when trying to run with no covariates. That is, only with fixed effects. My code is:

```<code>library(lfe)
data=read.csv("path_to//my_data.csv")

y <- cbind(col1)
x <- cbind(col2)

est <- felm(y ~ 0|x, data)
</code>```

However, the last line gives the error:

```<code>Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :
  variable lengths differ (found for 'x')
</code>```

Notice that I am calling it with proper syntax, according to the four-part formula formatting, as can be seen in page 20 of the documentation, where it says:

The formula specification is a response variable followed by a four part formula. The first part
consists of ordinary covariates, the second part consists of factors to be projected out. The third
part is an IV-specification. The fourth part is a cluster specification for the standard errors. I.e.
something like y ~ x1 + x2 | f1 + f2 | (Q|W ~ x3+x4) | clu1 + clu2 where y is the
response, x1,x2 are ordinary covariates, f1,f2 are factors to be projected out, Q and W are covariates
which are instrumented by x3 and x4, and clu1,clu2 are factors to be used for computing cluster
robust standard errors. Parts that are not used should be specified as 0, except if it’s at the end of the
formula, where they can be omitted.

答:
It turns out that it was a syntax problem, as suggested by @lmo. If I do:

```<code>est <- felm(col1 ~ 0|col1data)
</code>```

then there is no error and it works

ContentLicense: CC BY-SA 4.0

Title: Four-part formula syntax in R

Body:
I am using the lfe package for high dimenaional fixed effects in R. I am having trouble when trying to run with no covariates. That is, only with fixed effects. My code is:

library(lfe)
data=read.csv("path_to//my_data.csv")

y <- cbind(col1)
x <- cbind(col2)

est <- felm(y ~ 0|x, data)

However, the last line gives the error:

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :
  variable lengths differ (found for 'x')

Notice that I am calling it with proper syntax, according to the four-part formula formatting, as can be seen in page 20 of the documentation, where it says:

The formula specification is a response variable followed by a four part formula. The first part
consists of ordinary covariates, the second part consists of factors to be projected out. The third
part is an IV-specification. The fourth part is a cluster specification for the standard errors. I.e.
something like y ~ x1 + x2 | f1 + f2 | (Q|W ~ x3+x4) | clu1 + clu2 where y is the
response, x1,x2 are ordinary covariates, f1,f2 are factors to be projected out, Q and W are covariates
which are instrumented by x3 and x4, and clu1,clu2 are factors to be used for computing cluster
robust standard errors. Parts that are not used should be specified as 0, except if it’s at the end of the
formula, where they can be omitted.

Body:
It turns out that it was a syntax problem, as suggested by @lmo. If I do:

est <- felm(col1 ~ 0|col1data)

then there is no error and it works


问:
MATLAB string 2 number of table
I have a 3-year data in a string tableformat.txt. Three of its lines are given below:

```<code>12-13 Jan -10.5
14-15 Jan -9.992
15-16 Jan -8
</code>```

How to change the 3rd column (-10.5, -9.992 and -8) of string to be (-10.500, -9.992 and -8.000) of number?

I have made the following script:

```<code>clear all; clc;
filename='tableformat.txt';
fid = fopen(filename);
N = 3;
for i = [1:N]
    line = fgetl(fid)
    a = line(10:12);
    na = str2num(a);
    ma(i) = na;
end
ma
</code>```

which gives:

```<code>ma = -1    -9    -8
</code>```

When I did this change: a = line(10:15);, I got:

Error message: Index exceeds matrix dimensions.

答:
This will work for you.</p>

```<code>clear all;

clc;

filename='tableformat.txt';
filename2='tableformat2.txt';

fid = fopen(filename);
fid2 = fopen(filename2,'w');

formatSpec = '%s %s %6.4f\n';

N = 3;

for row = [1:N]

line = fgetl(fid);
a = strsplit(line,' ');
a{3}=cellfun(@str2num,a(3));
fprintf(fid2, formatSpec,a{1,:});

end

fclose(fid);

fclose(fid2);
</code>```

Title: MATLAB string 2 number of table

Body:
I have a 3-year data in a string tableformat.txt. Three of its lines are given below:

12-13 Jan -10.5
14-15 Jan -9.992
15-16 Jan -8

How to change the 3rd column (-10.5, -9.992 and -8) of string to be (-10.500, -9.992 and -8.000) of number?

I have made the following script:

clear all; clc;
filename='tableformat.txt';
fid = fopen(filename);
N = 3;
for i = [1:N]
    line = fgetl(fid)
    a = line(10:12);
    na = str2num(a);
    ma(i) = na;
end
ma

which gives:

ma = -1    -9    -8

When I did this change: a = line(10:15);, I got:

Error message: Index exceeds matrix dimensions.

Body:
This will work for you.

clear all;

clc;

filename='tableformat.txt';
filename2='tableformat2.txt';

fid = fopen(filename);
fid2 = fopen(filename2,'w');

formatSpec = '%s %s %6.4f\n';

N = 3;

for row = [1:N]

line = fgetl(fid);
a = strsplit(line,' ');
a{3}=cellfun(@str2num,a(3));
fprintf(fid2, formatSpec,a{1,:});

end

fclose(fid);

fclose(fid2);


问:
SQL server return only single row or null
I have a SQL query which I only ever want to return 1 row. If there are multiple rows, I want to return null.

I guess I can do it with something like

```<code>SELECT whatever FROM MyTable
 WHERE something = myQuery
   AND ( COUNT(SELECT whatever FROM MyTable
             WHERE something = myQuery) = 1)
</code>```

but that's pretty nasty and I wondered if there as a neater way of doing it.

答:
set rowcount 1

Before the select statement.

Later,

set rowcount 0

Body:
I have a SQL query which I only ever want to return 1 row. If there are multiple rows, I want to return null.

I guess I can do it with something like

SELECT whatever FROM MyTable
 WHERE something = myQuery
   AND ( COUNT(SELECT whatever FROM MyTable
             WHERE something = myQuery) = 1)

but that's pretty nasty and I wondered if there as a neater way of doing it.


答: I think I found the problem.  size() returns an unsigned number.  So subtracting 1 from it in the for loop and the cout makes it loop around to the largest number of that data size.  Not sure why it's 4294967295 though.</p>

Title: Why does C++ vector size start out at 4294967296 yet the debugger reads it as 0?


答: v.size() returns a size_t which is an unsigned type. Once you subtract one from that - given that its current value is 0 - it wraps around to become a bit pattern representing a large positive number.


问:
Sort 'ls' output by name
Can you sort an ls listing by name?</p>

答:
```<code>In Debian Jessie, this works nice:

ls -lah --group-directories-first

# l=use a long listing format
# a=do not ignore entries starting with .
# h=human readable
# --group-directories-first=(obvious)
# Note: add -r for reverse alpha

# You might consider using lh by appending to ~/.bashrc as the alias:
~$ echo "alias lh='ls -lah --group-directories-first'" >>~/.bashrc
# -- restart your terminal before using lh command --
</code>```

Title: Sort 'ls' output by name

Body: Can you sort an ls listing by name?


问:
Hide/Show Panels inside the Repeater Item Template using JavaScript
I added a (Read More...) Div to my repeater's item template, that doesn't contain any information.

I want to add a text button or an anchor to my item template..when it's clicked it should call a javascript method that writes information to the Div and it will take the content to write as a parameter, the content will be passed as an Eval method, for example it will eval("education")...and when it's clicked again it will hide the Div

I tried various and near approaches but it all worked outside the repeater and item template tags, but if I placed the identical code to the repeater and my javascript to the head tag it won't function!

I don't want to post my code, because I'm sure it's an easy and essential trick for any developer...so I was hoping for an original example not an edit to my test code(beginners logic)! =)

Thanks in advance!

答: Try the jQuery UI Accordion. It works well with the asp:Repeater.</p>


问:
Icons in overflow menu
I have an overflow menu with 3 items in it.  I have an icon for one of the items by creating a method and then calling that method.  The only thing is that it gives me one icon.  How can I put more than one icon next to the items in my overflow menu?  Here is my code for the method of the one I have (which is a settings icon:

```<code>private void setIconInMenu(Menu menu, int menuItemID, int labelId, int iconID) {
    MenuItem item = menu.findItem(menuItemID);
    SpannableStringBuilder builder =
            new SpannableStringBuilder("          " + getResources().getString(labelId));
    builder.setSpan(new ImageSpan(this, iconID), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    item.setTitle(builder);
</code>```

This is the code that calls the method:

```<code>setIconInMenu(menu, R.id.action_preferences, R.string.menu_action_preferences,
            R.drawable.ic_settings_white_24dp);
</code>```

So I want to some icons for other items in the menu.

Thanks.
Robert

答: have you tried just using an array list with a custom adapter that takes in a drawable parameter?</p>

Title: Icons in overflow menu

Body:
I have an overflow menu with 3 items in it.  I have an icon for one of the items by creating a method and then calling that method.  The only thing is that it gives me one icon.  How can I put more than one icon next to the items in my overflow menu?  Here is my code for the method of the one I have (which is a settings icon:

private void setIconInMenu(Menu menu, int menuItemID, int labelId, int iconID) {
    MenuItem item = menu.findItem(menuItemID);
    SpannableStringBuilder builder =
            new SpannableStringBuilder("          " + getResources().getString(labelId));
    builder.setSpan(new ImageSpan(this, iconID), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    item.setTitle(builder);

This is the code that calls the method:

setIconInMenu(menu, R.id.action_preferences, R.string.menu_action_preferences,
            R.drawable.ic_settings_white_24dp);

So I want to some icons for other items in the menu.

Thanks.
Robert


问:
Change plotly chart y variable based on selectInput
I'm creating a simple line chart which renders correctly in Shiny.

I've now added a selectInput with the names of 2 different measures, written as they appear in my data set. I'd like my y variable to change accordingly.

```<code>p <- plot_ly(data = LineChartData(), x= Calendar.Month, y = input$Measure, type = "line", group = Calendar.Year, col = Calendar.Year)
</code>```

Unfortunately, the chart renders with just one point. It's not taking input$Measure and finding that field in my data set.

I know when using ggplot, i'd switch my aes to aes_string. Is there a similar solution in plotly?

EDIT: here's some reproducible code

Here's the ui.R file

```<code>    #ui.R

shinyUI(
  fluidPage(
    titlePanel("Inbound Intermediary Performance"),

  sidebarLayout(
    sidebarPanel(
    h4("Parameters"),
    br(),
    selectInput("Measure", "Measure", c("Var1","Var2"))
    ),
    mainPanel(

      plotlyOutput("lineChart")

      )

  )

        )

)
</code>```

server.R

```<code>#server.R
library(plotly)
library(shiny)
library(ggplot2)

#Create data
data <- data.frame(Month = c(1,2,3,4,5,6,7,8,9,10,11,12), Var1 = c(36,33,30,27,24,21,18,15,12,9,6,3), Var2 = c(4,8,12,16,20,24,28,32,36,40,44,48))

shinyServer(function(input, output) {

  #Create plot

  output$lineChart <- renderPlotly({

    #using ggplot
    p <- ggplot(data=data, aes_string(x='Month', y = input$Measure)) +geom_line(size = 1.5) + theme_minimal()
    ggplotly(p)

    #Using PLotly
    #p <- plot_ly(data = data, x= Month, y = input$Measure, type = "line")

  })

})
</code>```

In the example above, I can use my drop down to switch between Var1 and Var2. My plot changes accordingly. The code uses ggplot and it's aes_string function to take an input. This is then converted into a plotly interactive plot using the ggplotly function.

Is there a way I can do this natively with plotly?

答:
Use base::get() function:

```<code>p <- plot_ly(data = data, x = ~Month, y = ~get(input$Measure), type = "line")
</code>```

or the same using ggplot:

```<code>p <- ggplot(data = data, aes(x = Month, y = get(input$Measure))) +
geom_line(size = 1.5) +
theme_minimal()
ggplotly(p)
</code>```

Body:
I'm creating a simple line chart which renders correctly in Shiny.

I've now added a selectInput with the names of 2 different measures, written as they appear in my data set. I'd like my y variable to change accordingly.

p <- plot_ly(data = LineChartData(), x= Calendar.Month, y = input$Measure, type = "line", group = Calendar.Year, col = Calendar.Year)

Unfortunately, the chart renders with just one point. It's not taking input$Measure and finding that field in my data set.

I know when using ggplot, i'd switch my aes to aes_string. Is there a similar solution in plotly?

EDIT: here's some reproducible code

Here's the ui.R file

    #ui.R

shinyUI(
  fluidPage(
    titlePanel("Inbound Intermediary Performance"),

  sidebarLayout(
    sidebarPanel(
    h4("Parameters"),
    br(),
    selectInput("Measure", "Measure", c("Var1","Var2"))
    ),
    mainPanel(

      plotlyOutput("lineChart")

      )

  )

        )

)

server.R

#server.R
library(plotly)
library(shiny)
library(ggplot2)

#Create data
data <- data.frame(Month = c(1,2,3,4,5,6,7,8,9,10,11,12), Var1 = c(36,33,30,27,24,21,18,15,12,9,6,3), Var2 = c(4,8,12,16,20,24,28,32,36,40,44,48))

shinyServer(function(input, output) {

  #Create plot

  output$lineChart <- renderPlotly({

    #using ggplot
    p <- ggplot(data=data, aes_string(x='Month', y = input$Measure)) +geom_line(size = 1.5) + theme_minimal()
    ggplotly(p)

    #Using PLotly
    #p <- plot_ly(data = data, x= Month, y = input$Measure, type = "line")

  })

})

In the example above, I can use my drop down to switch between Var1 and Var2. My plot changes accordingly. The code uses ggplot and it's aes_string function to take an input. This is then converted into a plotly interactive plot using the ggplotly function.

Is there a way I can do this natively with plotly?

Body:
Use base::get() function:

p <- plot_ly(data = data, x = ~Month, y = ~get(input$Measure), type = "line")

or the same using ggplot:

p <- ggplot(data = data, aes(x = Month, y = get(input$Measure))) +
geom_line(size = 1.5) +
theme_minimal()
ggplotly(p)


问:
In Java, why can we use the String class as if it were a primitive?
In Java we usually do:

```<code>Class myObject = new Class();
</code>```

because the new keyword returns an address.

But why can we do this?:

```<code>String myString = "Hello";
</code>```

as if String were a primitive?

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Is "Hello" stored in an instance variable of the class String?

答:
The fact that you can use a literal expression doesn't mean that the expression results in a primitive type! That is simply a misconception on your end.

You see:

```<code> Integer[] numbers = { 1, 2, 3 };
</code>```

is also a literal (well, "almost"; as you can only use it for such kind of array init statements); but it is not a primitive type!

And to ask the why part in your question: chances are - simply for convenience. When Java was created, it was meant to be "better" than the C and C++ of those days. And guess what: dealing with strings was pretty annoying and error prone in those languages.

In that sense: introducing string literals could be seen as unique selling point to differentiate Java from its competition!

Body:
In Java we usually do:

Class myObject = new Class();

because the new keyword returns an address.

But why can we do this?:

String myString = "Hello";

as if String were a primitive?

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Is "Hello" stored in an instance variable of the class String?

Body:
The fact that you can use a literal expression doesn't mean that the expression results in a primitive type! That is simply a misconception on your end.

You see:

 Integer[] numbers = { 1, 2, 3 };

is also a literal (well, "almost"; as you can only use it for such kind of array init statements); but it is not a primitive type!

And to ask the why part in your question: chances are - simply for convenience. When Java was created, it was meant to be "better" than the C and C++ of those days. And guess what: dealing with strings was pretty annoying and error prone in those languages.

In that sense: introducing string literals could be seen as unique selling point to differentiate Java from its competition!


答:
The size of vector is unsigned type, it is the same if you write

```<code>size_t x = -1;
std::cout << x << std::endl;
</code>```

and if you assign -1 to it will be transfered to the maximum value of size_t

Body:
The size of vector is unsigned type, it is the same if you write

size_t x = -1;
std::cout << x << std::endl;

and if you assign -1 to it will be transfered to the maximum value of size_t


问:
IQKeyboardManager - Shifting UITextView up too far
I'm using IQKeyboardManager to make keyboard management simple for a notes view controller I have (contains a large UITextView). Once the keyboard is active, however, the screen is shifted up unnecessarily. I'd like for the screen to stay how it is before the keyboard is active (see image below), and only have the UITextView scroll once the user's typing would be covered by the keyboard.

Before keyboard is active

When the keyboard is active (view scrolled up, covering "Notes" and Navigation Bar)

I don't want the Navigation Bar or the "Notes" label to be covered up, but I couldn't find a setting in IQKeyboardManager to stop the UITextView from being pushed all the way to the top.

How can I prevent the view from shifting up so far when the keyboard is made active?

EDIT: I should note that I'm not opposed to removing IQKeyboardManager, I just thought it would make dealing with this either. I mainly just need a way for my UITextView to automatically scroll when the user types something that would go underneath the keyboard.

UPDATE: I solved my problem without IQKeyboardManager by adjusting the contentInset of my UITextView depending on whether or not the keyboard is visible.

答: Is you navigation bar translucent? It's common bug in IQKeyboardManager. Try to uncheck "Translucent" property in navigation bar. It's not perfect solution but should works. </p>


问:
How does java.util.Arrays handle sorting an ArrayList (length vs size)?
I've been looking through the source code for java.util.Arrays and when sorting it always refers to the length of the array (which for an ArrayList I assume refers to the length of the E[] data (transient) field.
But shouldn't it actually refer to the size field, given that they aren't always equal to each other.</p>

答: Found the answer in Collections, it calls toArray() which returns an array of the ArrayList whose length is equal to the size, Arrays sorts the copy and Collections uses that to sort the actual ArrayList.


问:
How to count how many JButtons have been clicked from a 10 x 10 java JButton grid
I want to count the number of JButtons that has been clicked on from a 10 x 10 JButton grid.

This is what I am talking about

Anyways, I don't know how to count how many JButtons have been clicked. I thought about making 100 JButtons but that seems silly.

Also how do I prevent more than 14 buttons from being clicked?

```<code>ActionListener al = new ActionListener()
{
        public void actionPerformed(ActionEvent e)
        {
             JButton button = (JButton)e.getSource();
             button.setEnabled( false );

        }
};

    for(int row = 0; row < 10; row++)
    {
       for(int col = 0; col < 10; col++)
       {
               button = new JButton();
               button.addActionListener( al );
               panel_1.add(button);
       }
    }
</code>```

This is my forLoops for making 100 buttons and giving each of them an actionListener so when a JButton is clicked, it becomes unclickable.

```<code>    ActionListener al = new ActionListener()
    {
        int clicked = 0;

        public void actionPerformed(ActionEvent e)
        {
            button = (JButton)e.getSource();

             if(clicked != 14)
             {
                 clicked++;
             }
             else

                button = (JButton)e.getSource();
                button.setEnabled( false );

        }
    };

    for(int row = 0; row < 10; row++)
    {
        for(int col = 0; col < 10; col++)
        {
                button = new JButton();
                button.addActionListener( al );
                panel_1.add(button);

        }
    }
</code>```

I have tried putting in a counter but it is obviously not correct. Can I even compared e.getSource() to an int or something?

答:
If you want to count the number of clicks you will need to create an int (or long) variable to store them in, and simply add a ++ statement in the actionPerformed method:

```<code>private int buttonClicks = 0; // Or public
public void actionPerformed(ActionEvent e)
        {
             if(buttonClicks == 14){
               System.exit(0); // Or a different script
             }else{
             JButton button = (JButton)e.getSource();
             button.setEnabled( false );
             buttonClicks++; // Record click
             }
        }
</code>```

and if you want to count the number of clicks on a specific button, you will need to create a string array containing all the button names which are found in the constructors:

```<code>   JButton jbtn = new JButton("Button") // Button is the name
</code>```

and a separate int array which will store the clicks. Then you can use a for loop to figure out which button was pressed, and increase it's click in the int array.

Consider the following example:

```<code>aClass(){

    JFrame jfrm = new JFrame("Example");
    jfrm.setSize(200, 200);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jfrm.setLayout(new FlowLayout());
    jfrm.setLocationRelativeTo(null);

    JButton jbtn1 = new JButton("Push");
    JButton jbtn2 = new JButton("Click");
    JButton jbtn3 = new JButton("Press");

    jbtn1.addActionListener(this);
    jbtn2.addActionListener(this);
    jbtn3.addActionListener(this);

    jfrm.add(jbtn1);
    jfrm.add(jbtn2);
    jfrm.add(jbtn3);
}

public static String[] buttonNames = {"Push", "Click", "Press"}; // Put button names in an array
public static int[] buttonClicks = {0, 0, 0}; // Set the clicks to default

    public void actionPerformed(ActionEvent ae)
            {
                 for(int i = 0; i < buttons.length; i++){
                    if(ae.getActionCommand().equals(buttonNames[i])){
                    buttonClicks[i] =  buttonClicks[i] + 1; // Record the clicks. I think you can use buttonClicks[i]++, but I'm not sure
                    }
                 }
            }
</code>```

and anytime you need to access the number of clicks for a specific button, you could use something like the following:

```<code>public static int getClicks(String buttonName){
       for(int i = 0; i < aClass.buttonNames.length; i++){
           if(buttonName.equals(aClass.buttonNames[i])){
           return aClass.buttonClicks[i];
           }
       }
}
</code>```

and when you call that method, all you have to do is pass the button name to it as a string.
getClicks("Push");

Body:
I want to count the number of JButtons that has been clicked on from a 10 x 10 JButton grid.

This is what I am talking about

Anyways, I don't know how to count how many JButtons have been clicked. I thought about making 100 JButtons but that seems silly.

Also how do I prevent more than 14 buttons from being clicked?

ActionListener al = new ActionListener()
{
        public void actionPerformed(ActionEvent e)
        {
             JButton button = (JButton)e.getSource();
             button.setEnabled( false );

        }
};

    for(int row = 0; row < 10; row++)
    {
       for(int col = 0; col < 10; col++)
       {
               button = new JButton();
               button.addActionListener( al );
               panel_1.add(button);
       }
    }

This is my forLoops for making 100 buttons and giving each of them an actionListener so when a JButton is clicked, it becomes unclickable.

    ActionListener al = new ActionListener()
    {
        int clicked = 0;

        public void actionPerformed(ActionEvent e)
        {
            button = (JButton)e.getSource();

             if(clicked != 14)
             {
                 clicked++;
             }
             else

                button = (JButton)e.getSource();
                button.setEnabled( false );

        }
    };

    for(int row = 0; row < 10; row++)
    {
        for(int col = 0; col < 10; col++)
        {
                button = new JButton();
                button.addActionListener( al );
                panel_1.add(button);

        }
    }

I have tried putting in a counter but it is obviously not correct. Can I even compared e.getSource() to an int or something?

Body:
If you want to count the number of clicks you will need to create an int (or long) variable to store them in, and simply add a ++ statement in the actionPerformed method:

private int buttonClicks = 0; // Or public
public void actionPerformed(ActionEvent e)
        {
             if(buttonClicks == 14){
               System.exit(0); // Or a different script
             }else{
             JButton button = (JButton)e.getSource();
             button.setEnabled( false );
             buttonClicks++; // Record click
             }
        }

and if you want to count the number of clicks on a specific button, you will need to create a string array containing all the button names which are found in the constructors:

   JButton jbtn = new JButton("Button") // Button is the name

and a separate int array which will store the clicks. Then you can use a for loop to figure out which button was pressed, and increase it's click in the int array.

Consider the following example:

aClass(){

    JFrame jfrm = new JFrame("Example");
    jfrm.setSize(200, 200);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jfrm.setLayout(new FlowLayout());
    jfrm.setLocationRelativeTo(null);

    JButton jbtn1 = new JButton("Push");
    JButton jbtn2 = new JButton("Click");
    JButton jbtn3 = new JButton("Press");

    jbtn1.addActionListener(this);
    jbtn2.addActionListener(this);
    jbtn3.addActionListener(this);

    jfrm.add(jbtn1);
    jfrm.add(jbtn2);
    jfrm.add(jbtn3);
}

public static String[] buttonNames = {"Push", "Click", "Press"}; // Put button names in an array
public static int[] buttonClicks = {0, 0, 0}; // Set the clicks to default

    public void actionPerformed(ActionEvent ae)
            {
                 for(int i = 0; i < buttons.length; i++){
                    if(ae.getActionCommand().equals(buttonNames[i])){
                    buttonClicks[i] =  buttonClicks[i] + 1; // Record the clicks. I think you can use buttonClicks[i]++, but I'm not sure
                    }
                 }
            }

and anytime you need to access the number of clicks for a specific button, you could use something like the following:

public static int getClicks(String buttonName){
       for(int i = 0; i < aClass.buttonNames.length; i++){
           if(buttonName.equals(aClass.buttonNames[i])){
           return aClass.buttonClicks[i];
           }
       }
}

and when you call that method, all you have to do is pass the button name to it as a string.
getClicks("Push");


问:
AngularJS Promises and $http.get
Im trying to use the $q.defer, $q.all and promises in order to wait for a list of http requests

i uses this code to call the $q.all

```<code>$q.all(promises).then(function(data) {
      console.log('All promises have resolved', data);

      var retVal = Utils.DoStep2();
      console.log(retVal);
});
</code>```

this function is never called altough i checked and the $http.get is called for all of the values.

```<code>            var deferred = $q.defer();
           $http.get(requestUrl).
           then(function (data) {
               var p = {
                   data: data,
                   name: name
               };
               pData.push(p);
               deferred.resolve(p);
               return p;
           })
           .catch(function (status) {
               deferred.reject(status);
           });

           promisesList.push(deferred.promise);
</code>```

Im printing on DoStep2 the length of pData and also the pData using console.log
and what i get is the length of 0 and Looking like 0 objects but when i open it it looks like all of the objects are initalized within the $http.get call for each specific call which made me sure that the $http.get response recieved and it's a valid response.

Also the $all isn't called at all what could be wrong?

Thanks for your assistance

答:
OK Managed to fix it up
I used service function getService() and this function returned the promise then in each call i added the getService() promise returned to the promisesList this list i waited for using $all and it worked
thanks alot for your assistance.</p>

Title: AngularJS Promises and $http.get

Body:
Im trying to use the $q.defer, $q.all and promises in order to wait for a list of http requests

i uses this code to call the $q.all

$q.all(promises).then(function(data) {
      console.log('All promises have resolved', data);

      var retVal = Utils.DoStep2();
      console.log(retVal);
});

this function is never called altough i checked and the $http.get is called for all of the values.

            var deferred = $q.defer();
           $http.get(requestUrl).
           then(function (data) {
               var p = {
                   data: data,
                   name: name
               };
               pData.push(p);
               deferred.resolve(p);
               return p;
           })
           .catch(function (status) {
               deferred.reject(status);
           });

           promisesList.push(deferred.promise);

Im printing on DoStep2 the length of pData and also the pData using console.log
and what i get is the length of 0 and Looking like 0 objects but when i open it it looks like all of the objects are initalized within the $http.get call for each specific call which made me sure that the $http.get response recieved and it's a valid response.

Also the $all isn't called at all what could be wrong?

Thanks for your assistance


问:
Save own Class with NSCoder
I'm trying to store some custom class/data to a file in my iPhone/iPad app.

I have a Class RSHighscoreList

```<code>@interface RSHighscoreList : NSObject {
    NSMutableArray *list;
}
</code>```

which contains objects of RSHighscore in the list

```<code>@interface RSHighscore : NSObject {
    NSString *playerName;
    NSInteger points;
}
</code>```

When I try to store all to file

```<code>- (void)writeDataStore {
    RSDataStore *tmpStore = [[RSDataStore alloc] init];
    _tmpStore.highscorelist = self.highscorelist.list;
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:tmpStore forKey:kDataKey];
    [archiver finishEncoding];
    [data writeToFile:[self dataFilePath] atomically:YES];

    [archiver release];
    [data release];
}

@interface RSDataStore : NSObject <NSCoding, NSCopying> {
    NSMutableArray *highscorelist;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:highscorelist forKey:@"Highscorelist"];
}
</code>```

The app will crash with an error message

```-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20'```

I wonder why the error tells about RSHighscore, even if that is 'wrapped'. Does anyone have a good idea?

答:
The class you're going to encode or initWithCoder should conform to <NSCoding> protocol
So you just should add this in your interface, otherwise indeed the runtime will not recognize the selector as it's the part of <NSCoding> protocol

Title: Save own Class with NSCoder

Body:
I'm trying to store some custom class/data to a file in my iPhone/iPad app.

I have a Class RSHighscoreList

@interface RSHighscoreList : NSObject {
    NSMutableArray *list;
}

which contains objects of RSHighscore in the list

@interface RSHighscore : NSObject {
    NSString *playerName;
    NSInteger points;
}

When I try to store all to file

- (void)writeDataStore {
    RSDataStore *tmpStore = [[RSDataStore alloc] init];
    _tmpStore.highscorelist = self.highscorelist.list;
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:tmpStore forKey:kDataKey];
    [archiver finishEncoding];
    [data writeToFile:[self dataFilePath] atomically:YES];

    [archiver release];
    [data release];
}

@interface RSDataStore : NSObject <NSCoding, NSCopying> {
    NSMutableArray *highscorelist;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:highscorelist forKey:@"Highscorelist"];
}

The app will crash with an error message

-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20'

I wonder why the error tells about RSHighscore, even if that is 'wrapped'. Does anyone have a good idea?


答:
Why did the 2nd cout print 4294967295?

Because std::vector::size_type is unsigned. Negative numbers are not representable by unsigned integers. When you subtract one from an unsigned integer of value zero, the number "wraps around" and will become the largest value representable by that type. For a 32 bit integer, that number is 232 - 1, which is 4294967295.

More generally, if the result of a calculation is not representable by the unsigned type, the result will be congruent (with the actual, unrepresentable result) modulo the largest representable value + 1.

Why did the go into the for loop?

Because 0 is less than 4294967295.

Why is the 1st cout printing 0 when it's actually using 4294967296? The Visual Studio 2015 debugger is showing 0 for some reason.

The size is actually 0. 4294967296 is a value too large to be representable by the std::vector::size_type on your system.

Body:
From this sample code:

    vector<int> v;

    // cout << v.size() << endl;         // prints 0
    // cout << v.size() - 1 << endl;     // prints

    for (int i = 0; i < v.size() - 1; i++)
        cout << v[i] << endl;

I got an out of range error. A few questions:

Why did the code go into the for loop?

Why did the 2nd cout print 4294967295?

Why is the 1st cout printing 0 when it's actually using 4294967296? The Visual Studio 2015 debugger is showing 0 for some reason.


问:
Parallax not working in materialize css
I am using the Materialize Framework to create a PhoneGap app.

http://materializecss.com

They have a parallax setting which you can see their notation here:

http://materializecss.com/parallax.html

When I run it, my image does not show up at all. My html looks like this:

```<code><div class="row">
  <div class="col s12 m7">
    <div class="card">

      <div class="parallax-container" style = "height:100px;">
        <div class="parallax"><img src="/img.png"></div>
      </div>

      <div class="card-content">
        <h5> test</h5>
        <h6> test</h6>
        <h6> test </h6>
        </br>
        <p> test</p>
      </div>

      <div class="card-action">
        <a href="#">This is a link</a>
      </div>

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

答: make sure you used "\" and not "/" while mentioning path of image</p>

Title: Parallax not working in materialize css

Body:
I am using the Materialize Framework to create a PhoneGap app.

http://materializecss.com

They have a parallax setting which you can see their notation here:

http://materializecss.com/parallax.html

When I run it, my image does not show up at all. My html looks like this:

 test

 test

 test

 test

        This is a link


答:
All literals are not primitives.

From JLS 3.10

3.10. Literals

A literal is the source code representation of a value of a primitive
type (§4.2), the String type (§4.3.3), or the null type (§4.1).

Literal:

IntegerLiteral

FloatingPointLiteral

BooleanLiteral

CharacterLiteral

StringLiteral

NullLiteral

So String literals are not primitives but objects.

The JLS references it and you can also deduce it because String instances have methods while primitive cannot have methods.

String literals (String myString = "Hello") have very likely been introduced by the language to ease the declaration of String that is a type as common as primitive types such as int or boolean.
Imagine a String concatenation such as :

```<code>new String("hello ") + new String (nameInput) + new String (" and welcome!");
</code>```

This is clearly more verbose, less readable and therefore more error prone than :

```<code> "hello " + nameInput +" and welcome!";
</code>```

Title: In Java, why can we use the String class as if it were a primitive?

Body:
All literals are not primitives.

From JLS 3.10

3.10. Literals

A literal is the source code representation of a value of a primitive
type (§4.2), the String type (§4.3.3), or the null type (§4.1).

Literal:

IntegerLiteral

FloatingPointLiteral

BooleanLiteral

CharacterLiteral

StringLiteral

NullLiteral

So String literals are not primitives but objects.

The JLS references it and you can also deduce it because String instances have methods while primitive cannot have methods.

String literals (String myString = "Hello") have very likely been introduced by the language to ease the declaration of String that is a type as common as primitive types such as int or boolean.
Imagine a String concatenation such as :

new String("hello ") + new String (nameInput) + new String (" and welcome!");

This is clearly more verbose, less readable and therefore more error prone than :

 "hello " + nameInput +" and welcome!";


问:
What can go wrong (what are the risks) if i don't escape the data and insert it to database?
I am using codeigniter and in security section it suggest that: Escape the data before submitting it into your database or outputting it to a browser.

What could really go wrong if I don't escape it, what are the risks?

Thank you.

答:
If you're using Active Record, you don't need to escape the data before inserting into the database. You should still be validating it, though.

If you later echo()/print() the values in a view, however, you should escape to avoid XSS: $this->security->xss_clean().

Global XSS filtering is deprecated and should no longer be used.

You should also enable CSRF protection in your config if you have any forms on your application.

You can read more about all of this here: https://codeigniter.com/user_guide/general/security.html


问:
Route URL such as http://www.example.com/{userId}
I would like my MVC website to be able to route the following URLs:

http://www.example.com/{userId}

  http://www.example.com/{userId}/enroll

Note: userId is a string of letters, numbers and/or hyphens.

I realize this is problematic because the URL does not specify a controller name. However, it should be possible in theory. I can use reflection to get a list of all the controllers in my application. If {userId} does not match any of those controllers, then it should be redirected to a particular controller/action.

My first question is how would you specify a map like this? I can specify a string value, I can even specify a regular expression. But how can I filter based on whether or not it matches a list of strings?

Beyond that, just wondered if anyone else has thought of doing things and if they have any other creative ideas on how I might accomplish it.

答:
If I understand your question right:

```<code>routes.MapRoute(
  name: "Default",
  url: "{id}/{action}",
  defaults: new { controller = "Custom", action = "Index" },
  constraint: new { id = new MyRouteConstraint()});
</code>```

In custom MyRouteConstraint: IRouteConstraint you can match your parameter with list of strings

Body:
If I understand your question right:

routes.MapRoute(
  name: "Default",
  url: "{id}/{action}",
  defaults: new { controller = "Custom", action = "Index" },
  constraint: new { id = new MyRouteConstraint()});

In custom MyRouteConstraint: IRouteConstraint you can match your parameter with list of strings


问:
Passing date value by Ajax
I have two pass my calendar value through Ajax. The problem is, date value passing only after second try of selecting date and it is passing the first try value!!

The current result as an Example:

On first try I will select: 2017-03-01

selectvalueds = ‘ ‘

On second try I will select: 2015-05-30

Selectvalueds = ‘2017-03-01’

Important:!
Due to some calculation i have to first copy the value of calendar to #start and then pass #start through Ajax to my php code.
Javascript:

```<code>$('#calendar').change(function() {
    $('#start').val($(this).val());
});
    $('#calendar’).change(function(){
            var selectvalueds = $('#start').val();
            Unit_id.html('<option value="">Loading...</option>');
            if (selectvalueds == '')
            {Unit_id.html(initial_Unit_html);}
            else
            {
                $.ajax({
                    url: 'index.php',
                    data:'option=com_myapp&task=getUnitsHTML&dsvalue='+selectvalueds,
                    success: function(output) {
                        Unit_id.html(output);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status + ' ' + thrownError);
                    }
                });
            }
         });
</code>```

php:

```<code> public function getUnitsHTML() {
         $jinput = JFactory::getApplication()->input;
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         $sdate = date_create($jinput->get ('dsvalue'));
         $mystartdate = date_format($sdate, "Y-m-d");
         echo '<div>'.$mystartdate.'</div></br>';
        }
</code>```

答:
You are binding 2 change events to the #calendar. Instead, try something like this:

```<code>function yourCalculation(start_val) {
    execute_whatever_you_want;
};
$('#calendar').change(function() {
    value = $(this).val()
    yourCalculation(value);

    var selectvalueds = value;
    Unit_id.html('<option value="">Loading...</option>');
    if (selectvalueds == '') {
       Unit_id.html(initial_Unit_html);
    } else {
       $.ajax({
              url: 'index.php',
              data:'option=com_myapp&task=getUnitsHTML&dsvalue='+selectvalueds,
              success: function(output) {
                   Unit_id.html(output);
              },
              error: function (xhr, ajaxOptions, thrownError) {
                   alert(xhr.status + ' ' + thrownError);
              }
       });
    }
 });
</code>```

This will first get the value, execute your calculation function, then add the Loading option, check if the value is not empty and if it's not empty, start Ajax call.

Title: Passing date value by Ajax

Body:
I have two pass my calendar value through Ajax. The problem is, date value passing only after second try of selecting date and it is passing the first try value!!

The current result as an Example:

On first try I will select: 2017-03-01

selectvalueds = ‘ ‘

On second try I will select: 2015-05-30

Selectvalueds = ‘2017-03-01’

Important:!
Due to some calculation i have to first copy the value of calendar to #start and then pass #start through Ajax to my php code.
Javascript:

$('#calendar').change(function() {
    $('#start').val($(this).val());
});
    $('#calendar’).change(function(){
            var selectvalueds = $('#start').val();
            Unit_id.html('<option value="">Loading...</option>');
            if (selectvalueds == '')
            {Unit_id.html(initial_Unit_html);}
            else
            {
                $.ajax({
                    url: 'index.php',
                    data:'option=com_myapp&task=getUnitsHTML&dsvalue='+selectvalueds,
                    success: function(output) {
                        Unit_id.html(output);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status + ' ' + thrownError);
                    }
                });
            }
         });

php:

 public function getUnitsHTML() {
         $jinput = JFactory::getApplication()->input;
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         $sdate = date_create($jinput->get ('dsvalue'));
         $mystartdate = date_format($sdate, "Y-m-d");
         echo '
'.$mystartdate.'

';
        }

Body:
You are binding 2 change events to the #calendar. Instead, try something like this:

function yourCalculation(start_val) {
    execute_whatever_you_want;
};
$('#calendar').change(function() {
    value = $(this).val()
    yourCalculation(value);

    var selectvalueds = value;
    Unit_id.html('<option value="">Loading...</option>');
    if (selectvalueds == '') {
       Unit_id.html(initial_Unit_html);
    } else {
       $.ajax({
              url: 'index.php',
              data:'option=com_myapp&task=getUnitsHTML&dsvalue='+selectvalueds,
              success: function(output) {
                   Unit_id.html(output);
              },
              error: function (xhr, ajaxOptions, thrownError) {
                   alert(xhr.status + ' ' + thrownError);
              }
       });
    }
 });

This will first get the value, execute your calculation function, then add the Loading option, check if the value is not empty and if it's not empty, start Ajax call.


问:
jQuery PHP only works with 3 parameters
Heyho,

I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.

Maybe someone could figure out where the mistake is...

This is my code:

index.php

```<code>    <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
    <div class="container">
      <div class="">
        <h1>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</h1>
        <div class="col-sm-8">
        <div class="well clearfix">
            <div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
            <span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
        <table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
            <thead>
                <tr>
                    <th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
                    <th data-column-id="employee_name">Name</th>
                    <th data-column-id="employee_salary">Salary</th>
                    <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
                </tr>
            </thead>
        </table>
    </div>
      </div>
    </div>

<div id="add_model" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Add Employee</h4>
            </div>
            <div class="modal-body">
                <form method="post" id="frm_add">
                <input type="hidden" value="add" name="action" id="action">
                  <div class="form-group">
                    <label for="name" class="control-label">Name:</label>
                    <input type="text" class="form-control" id="name" name="name"/>
                  </div>
                  <div class="form-group">
                    <label for="salary" class="control-label">Salary:</label>
                    <input type="text" class="form-control" id="salary" name="salary"/>
                  </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_add" class="btn btn-primary">Save</button>
            </div>
            </form>
        </div>
    </div>
</div>
<div id="edit_model" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Edit Employee</h4>
            </div>
            <div class="modal-body">
                <form method="post" id="frm_edit">
                <input type="hidden" value="edit" name="action" id="action">
                <input type="hidden" value="0" name="edit_id" id="edit_id">
                  <div class="form-group">
                    <label for="name" class="control-label">Name:</label>
                    <input type="text" class="form-control" id="edit_name" name="edit_name"/>
                  </div>
                  <div class="form-group">
                    <label for="salary" class="control-label">Salary:</label>
                    <input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
                  </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_edit" class="btn btn-primary">Save</button>
            </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
    var grid = $("#employee_grid").bootgrid({
        ajax: true,
        rowSelect: true,
        post: function ()
        {
            /* To accumulate custom parameter with the request object */
            return {
                id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
            };
        },

        url: "response.php",
        formatters: {
                "commands": function(column, row)
                {
                    return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
                        "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
                }
            }
   }).on("loaded.rs.jquery.bootgrid", function()
{
    /* Executes after data is loaded and rendered */
    grid.find(".command-edit").on("click", function(e)
    {
        //alert("You pressed edit on row: " + $(this).data("row-id"));
            var ele =$(this).parent();
            var g_id = $(this).parent().siblings(':first').html();
            var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
                    console.log(g_name);

        //console.log(grid.data());//
        $('#edit_model').modal('show');
                    if($(this).data("row-id") >0) {

                                // collect the data
                                $('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
                                $('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
                                $('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());

                    } else {
                     alert('Now row selected! First select row, then click edit button');
                    }
    }).end().find(".command-delete").on("click", function(e)
    {

        var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
                    alert(conf);
                    if(conf){
                                $.post('response.php', { id: $(this).data("row-id"), action:'delete'}
                                    , function(){
                                        // when ajax returns (callback),
                                        $("#employee_grid").bootgrid('reload');
                                });
                                //$(this).parent('tr').remove();
                                //$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
                    }
    });
});

function ajaxAction(action) {
                data = $("#frm_"+action).serializeArray();
                $.ajax({
                  type: "POST",
                  url: "response.php",
                  data: data,
                  dataType: "json",
                  success: function(response)
                  {
                    $('#'+action+'_model').modal('hide');
                    $("#employee_grid").bootgrid('reload');
                  }
                });
            }

            $( "#command-add" ).click(function() {
              $('#add_model').modal('show');
            });
            $( "#btn_add" ).click(function() {
              ajaxAction('add');
            });
            $( "#btn_edit" ).click(function() {
              ajaxAction('edit');
            });
});
</script>
</code>```

response.php

```<code><?php
    //include connection file
    include_once("connection.php");

    $db = new dbObj();
    $connString =  $db->getConnstring();

    $params = $_REQUEST;

    $action = isset($params['action']) != '' ? $params['action'] : '';
    $empCls = new Employee($connString);

    switch($action) {
     case 'add':
        $empCls->insertEmployee($params);
     break;
     case 'edit':
        $empCls->updateEmployee($params);
     break;
     case 'delete':
        $empCls->deleteEmployee($params);
     break;
     default:
     $empCls->getEmployees($params);
     return;
    }

    class Employee {
    protected $conn;
    protected $data = array();
    function __construct($connString) {
        $this->conn = $connString;
    }

    public function getEmployees($params) {

        $this->data = $this->getRecords($params);

        echo json_encode($this->data);
    }
    function insertEmployee($params) {
        $data = array();;
        $sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' );  ";

        echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");

    }

    function getRecords($params) {
        $rp = isset($params['rowCount']) ? $params['rowCount'] : 10;

        if (isset($params['current'])) { $page  = $params['current']; } else { $page=1; };
        $start_from = ($page-1) * $rp;

        $sql = $sqlRec = $sqlTot = $where = '';

        if( !empty($params['searchPhrase']) ) {
            $where .=" WHERE ";
            $where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";

            $where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
       }
       if( !empty($params['sort']) ) {
            $where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
        }
       // getting total number records without any search
        $sql = "SELECT * FROM `employee` ";
        $sqlTot .= $sql;
        $sqlRec .= $sql;

        //concatenate search sql if value exist
        if(isset($where) && $where != '') {

            $sqlTot .= $where;
            $sqlRec .= $where;
        }
        if ($rp!=-1)
        $sqlRec .= " LIMIT ". $start_from .",".$rp;

        $qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
        $queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");

        while( $row = mysqli_fetch_assoc($queryRecords) ) {
            $data[] = $row;
        }

        $json_data = array(
            "current"            => intval($params['current']),
            "rowCount"            => 10,
            "total"    => intval($qtot->num_rows),
            "rows"            => $data   // total data array
            );

        return $json_data;
    }
    function updateEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."'  WHERE id='".$_POST["edit_id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
    }

    function deleteEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "delete from `employee` WHERE id='".$params["id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
    }
}
?>
</code>```

There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!

Thank you in advance,
Francis

答:
You should use your browsers developer tools to check the 'Network' tab for the XHR requests that get fired and have a look at the responses of those.
I think you can debug your way to a working solution from there.

You can use other tools like postman to test you AJAX "API" (response.php) but the developer tools of your browser should be more then sufficient for this ;)

Title: jQuery PHP only works with 3 parameters

Body:
Heyho,

I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.

Maybe someone could figure out where the mistake is...

This is my code:

index.php

    <!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />

Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX

<button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
             Record</button>

                    Empid
                    Name
                    Salary
                    Commands

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Employee

                <form method="post" id="frm_add">
                <input type="hidden" value="add" name="action" id="action">

                    Name:
                    <input type="text" class="form-control" id="name" name="name"/>

                    Salary:
                    <input type="text" class="form-control" id="salary" name="salary"/>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_add" class="btn btn-primary">Save</button>

            </form>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Employee

                <form method="post" id="frm_edit">
                <input type="hidden" value="edit" name="action" id="action">
                <input type="hidden" value="0" name="edit_id" id="edit_id">

                    Name:
                    <input type="text" class="form-control" id="edit_name" name="edit_name"/>

                    Salary:
                    <input type="text" class="form-control" id="edit_salary" name="edit_salary"/>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btn_edit" class="btn btn-primary">Save</button>

            </form>

response.php

<?php
    //include connection file
    include_once("connection.php");

    $db = new dbObj();
    $connString =  $db->getConnstring();

    $params = $_REQUEST;

    $action = isset($params['action']) != '' ? $params['action'] : '';
    $empCls = new Employee($connString);

    switch($action) {
     case 'add':
        $empCls->insertEmployee($params);
     break;
     case 'edit':
        $empCls->updateEmployee($params);
     break;
     case 'delete':
        $empCls->deleteEmployee($params);
     break;
     default:
     $empCls->getEmployees($params);
     return;
    }

    class Employee {
    protected $conn;
    protected $data = array();
    function __construct($connString) {
        $this->conn = $connString;
    }

    public function getEmployees($params) {

        $this->data = $this->getRecords($params);

        echo json_encode($this->data);
    }
    function insertEmployee($params) {
        $data = array();;
        $sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' );  ";

        echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");

    }

    function getRecords($params) {
        $rp = isset($params['rowCount']) ? $params['rowCount'] : 10;

        if (isset($params['current'])) { $page  = $params['current']; } else { $page=1; };
        $start_from = ($page-1) * $rp;

        $sql = $sqlRec = $sqlTot = $where = '';

        if( !empty($params['searchPhrase']) ) {
            $where .=" WHERE ";
            $where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";

            $where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
       }
       if( !empty($params['sort']) ) {
            $where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
        }
       // getting total number records without any search
        $sql = "SELECT * FROM `employee` ";
        $sqlTot .= $sql;
        $sqlRec .= $sql;

        //concatenate search sql if value exist
        if(isset($where) && $where != '') {

            $sqlTot .= $where;
            $sqlRec .= $where;
        }
        if ($rp!=-1)
        $sqlRec .= " LIMIT ". $start_from .",".$rp;

        $qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
        $queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");

        while( $row = mysqli_fetch_assoc($queryRecords) ) {
            $data[] = $row;
        }

        $json_data = array(
            "current"            => intval($params['current']),
            "rowCount"            => 10,
            "total"    => intval($qtot->num_rows),
            "rows"            => $data   // total data array
            );

        return $json_data;
    }
    function updateEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."'  WHERE id='".$_POST["edit_id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
    }

    function deleteEmployee($params) {
        $data = array();
        //print_R($_POST);die;
        $sql = "delete from `employee` WHERE id='".$params["id"]."'";

        echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
    }
}
?>

There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!

Thank you in advance,
Francis


问:
How to exclude/disable a specific auto-configuration in Spring boot 1.4.0 for @DataJpaTest?
I am using the @DataJpaTest from Spring for my test which will then use H2 as in memory database as described here . I'm also using Flyway for production. However once the test starts FLyway kicks in and reads the SQL file. How can I exclude the FlywayAutoConfiguration and keep the rest as described here in spring documentation in order to let Hibernate create the tables in H2 for me? </p>

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private MyRepository triggerRepository;
}
</code>```

答:
Adding the dependency on an in-memory database to my build.gradle

e.g. testRuntime "com.h2database:h2:1.4.194"

And adding flyway.enabled=false to application.properties in src/test/resources worked for me.

Body:
I am using the @DataJpaTest from Spring for my test which will then use H2 as in memory database as described here . I'm also using Flyway for production. However once the test starts FLyway kicks in and reads the SQL file. How can I exclude the FlywayAutoConfiguration and keep the rest as described here in spring documentation in order to let Hibernate create the tables in H2 for me?

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private MyRepository triggerRepository;
}


问:
WKWebView evaluateJavaScript not returning html
I am trying to parse the html returned from a WKWebView load() with evaluateJavaScript but it never prints anything. Am I doing this right? Any other ways? didFinish does print.

```<code>import UIKit
import WebKit

class MyWebViewController: UIViewController, WKNavigationDelegate {

var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView = WKWebView(frame:  self.view.frame)
    webView.navigationDelegate = self

    let url = NSURL (string: "https://google.com");
    let request = NSURLRequest(url: url! as URL)
    webView.load(request as URLRequest)

    self.view.addSubview(webView)

    self.view.sendSubview(toBack: webView)

}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.evaluateJavaScript("document.documentElement.outerHTML.toString()", completionHandler: { (html: AnyObject?, error: NSError?) in
        print(html!)
        } as? (Any?, Error?) -> Void)

    print("didFinish")

}
</code>```

}

答:
Using evaluateJavaScript with a WKWebView is a bit tricky.

Since I think this answer would be useful to many people, rather than address your specific question with a short code snippet and a comment that you need to implement WKScriptMessageHandler, I'm going to post a full, complete example that you can use to see how everything works together.

To use this, create a "Single View Application" iOS project in Xcode and paste this over the default ViewController.swift file.

```<code>//
//  WebViewController.swift
//  WKWebViewExample
//
//  Created by par on 4/2/17.
//  Copyright © 2017 par. All rights reserved.  MIT License.
//

import UIKit
import WebKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let webViewController = WebViewController()

        // install the WebViewController as a child view controller
        addChildViewController(webViewController)

        let webViewControllerView = webViewController.view!

        view.addSubview(webViewControllerView)

        webViewControllerView.translatesAutoresizingMaskIntoConstraints = false
        webViewControllerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webViewControllerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webViewControllerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webViewControllerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

        webViewController.didMove(toParentViewController: self)
    }
}

class WebViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
    private var webView: WKWebView!
    private var webViewContentIsLoaded = false

    init() {
        super.init(nibName: nil, bundle: nil)

        self.webView = {
            let contentController = WKUserContentController()

            contentController.add(self, name: "WebViewControllerMessageHandler")

            let configuration = WKWebViewConfiguration()
            configuration.userContentController = contentController

            let webView = WKWebView(frame: .zero, configuration: configuration)
            webView.scrollView.bounces = false
            webView.navigationDelegate = self

            return webView
        }()
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(webView)

        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if !webViewContentIsLoaded {
            let url = URL(string: "https://stackoverflow.com")!
            let request = URLRequest(url: url)

            webView.load(request)

            webViewContentIsLoaded = true
        }
    }

    private func evaluateJavascript(_ javascript: String, sourceURL: String? = nil, completion: ((_ error: String?) -> Void)? = nil) {
        var javascript = javascript

        // Adding a sourceURL comment makes the javascript source visible when debugging the simulator via Safari in Mac OS
        if let sourceURL = sourceURL {
            javascript = "//# sourceURL=\(sourceURL).js\n" + javascript
        }

        webView.evaluateJavaScript(javascript) { _, error in
            completion?(error?.localizedDescription)
        }
    }

    // MARK: - WKNavigationDelegate

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // This must be valid javascript!  Critically don't forget to terminate statements with either a newline or semicolon!
        let javascript =
            "var outerHTML = document.documentElement.outerHTML.toString()\n" +
            "var message = {\"type\": \"outerHTML\", \"outerHTML\": outerHTML }\n" +
            "window.webkit.messageHandlers.WebViewControllerMessageHandler.postMessage(message)\n"

        evaluateJavascript(javascript, sourceURL: "getOuterHMTL")
    }

    // MARK: - WKScriptMessageHandler

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard let body = message.body as? [String: Any] else {
            print("could not convert message body to dictionary: \(message.body)")
            return
        }

        guard let type = body["type"] as? String else {
            print("could not convert body[\"type\"] to string: \(body)")
            return
        }

        switch type {
        case "outerHTML":
            guard let outerHTML = body["outerHTML"] as? String else {
                print("could not convert body[\"outerHTML\"] to string: \(body)")
                return
            }
            print("outerHTML is \(outerHTML)")
        default:
            print("unknown message type \(type)")
            return
        }
    }
}
</code>```

Body:
I am trying to parse the html returned from a WKWebView load() with evaluateJavaScript but it never prints anything. Am I doing this right? Any other ways? didFinish does print.

import UIKit
import WebKit

class MyWebViewController: UIViewController, WKNavigationDelegate {

var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView = WKWebView(frame:  self.view.frame)
    webView.navigationDelegate = self

    let url = NSURL (string: "https://google.com");
    let request = NSURLRequest(url: url! as URL)
    webView.load(request as URLRequest)

    self.view.addSubview(webView)

    self.view.sendSubview(toBack: webView)

}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.evaluateJavaScript("document.documentElement.outerHTML.toString()", completionHandler: { (html: AnyObject?, error: NSError?) in
        print(html!)
        } as? (Any?, Error?) -> Void)

    print("didFinish")

}

}

Body:
Using evaluateJavaScript with a WKWebView is a bit tricky.

Since I think this answer would be useful to many people, rather than address your specific question with a short code snippet and a comment that you need to implement WKScriptMessageHandler, I'm going to post a full, complete example that you can use to see how everything works together.

To use this, create a "Single View Application" iOS project in Xcode and paste this over the default ViewController.swift file.

//
//  WebViewController.swift
//  WKWebViewExample
//
//  Created by par on 4/2/17.
//  Copyright © 2017 par. All rights reserved.  MIT License.
//

import UIKit
import WebKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let webViewController = WebViewController()

        // install the WebViewController as a child view controller
        addChildViewController(webViewController)

        let webViewControllerView = webViewController.view!

        view.addSubview(webViewControllerView)

        webViewControllerView.translatesAutoresizingMaskIntoConstraints = false
        webViewControllerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webViewControllerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webViewControllerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webViewControllerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

        webViewController.didMove(toParentViewController: self)
    }
}

class WebViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
    private var webView: WKWebView!
    private var webViewContentIsLoaded = false

    init() {
        super.init(nibName: nil, bundle: nil)

        self.webView = {
            let contentController = WKUserContentController()

            contentController.add(self, name: "WebViewControllerMessageHandler")

            let configuration = WKWebViewConfiguration()
            configuration.userContentController = contentController

            let webView = WKWebView(frame: .zero, configuration: configuration)
            webView.scrollView.bounces = false
            webView.navigationDelegate = self

            return webView
        }()
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(webView)

        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if !webViewContentIsLoaded {
            let url = URL(string: "https://stackoverflow.com")!
            let request = URLRequest(url: url)

            webView.load(request)

            webViewContentIsLoaded = true
        }
    }

    private func evaluateJavascript(_ javascript: String, sourceURL: String? = nil, completion: ((_ error: String?) -> Void)? = nil) {
        var javascript = javascript

        // Adding a sourceURL comment makes the javascript source visible when debugging the simulator via Safari in Mac OS
        if let sourceURL = sourceURL {
            javascript = "//# sourceURL=\(sourceURL).js\n" + javascript
        }

        webView.evaluateJavaScript(javascript) { _, error in
            completion?(error?.localizedDescription)
        }
    }

    // MARK: - WKNavigationDelegate

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // This must be valid javascript!  Critically don't forget to terminate statements with either a newline or semicolon!
        let javascript =
            "var outerHTML = document.documentElement.outerHTML.toString()\n" +
            "var message = {\"type\": \"outerHTML\", \"outerHTML\": outerHTML }\n" +
            "window.webkit.messageHandlers.WebViewControllerMessageHandler.postMessage(message)\n"

        evaluateJavascript(javascript, sourceURL: "getOuterHMTL")
    }

    // MARK: - WKScriptMessageHandler

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard let body = message.body as? [String: Any] else {
            print("could not convert message body to dictionary: \(message.body)")
            return
        }

        guard let type = body["type"] as? String else {
            print("could not convert body[\"type\"] to string: \(body)")
            return
        }

        switch type {
        case "outerHTML":
            guard let outerHTML = body["outerHTML"] as? String else {
                print("could not convert body[\"outerHTML\"] to string: \(body)")
                return
            }
            print("outerHTML is \(outerHTML)")
        default:
            print("unknown message type \(type)")
            return
        }
    }
}


问:
Import error with BeautifulSoup
I have downloaded BeautifulSoup using pip3 install beautifulsoup and it worked fine.

But when I try from bs4 import BeautifulSoup or import BeautifulSoup, I get the error ModuleNotFoundError: No module named 'BeautifulSoup' or ModuleNotFoundError: No module named 'bs4' depending on which line of code I use.

I have no idea what's wrong.  Why do I get the error?

答:
pip3 install beautifulsoup will install BeautifulSoup older version (Beautiful Soup 3 to be precise).

You need to do pip3 install beautifulsoup4 or pip3 install bs4 to install BeautifulSoup4

and then you can just use it like this :

```<code>from bs4 import BeautifulSoup
</code>```

You can refer to the download page and documentation of Beautiful Soup for more understanding on this.

Title: Import error with BeautifulSoup

Body:
pip3 install beautifulsoup will install BeautifulSoup older version (Beautiful Soup 3 to be precise).

You need to do pip3 install beautifulsoup4 or pip3 install bs4 to install BeautifulSoup4

and then you can just use it like this :

from bs4 import BeautifulSoup

You can refer to the download page and documentation of Beautiful Soup for more understanding on this.


问:
How to use variables in for loop statements in javascript?
So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?</p>

```<code><!DOCTYPE html>
<html>
<body>

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

<p id="display"></p>

<script>
var random = [];
document.getElementById("display").innerHTML = random;
a = document.getElementById("diceamount").innerHTML;

function FirstFunction() {
for (i=0; i<"a"; i++) {
    x = Math.floor(Math.random() * 4) + 1;
    random.push(x);
    document.getElementById("display").innerHTML = random;
    }
}
</script>

</body>
</html>
</code>```

答:
var random = [];
// not useful? but in your code
document.getElementById("display").innerHTML = random;

function FirstFunction(event) {
    // get local value into a and use it the + avoids parseInt
    let a = Math.abs(+document.getElementById("diceamount").value);
    for (i=0; i<a; i++) {
      // x was not declared and should be
      let x = Math.floor(Math.random() * 4) + 1;
      random.push(x);
    }
    // could be textContent instead...outside loop
    document.getElementById("display").innerHTML = random;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display">x</p></code>```

Body:
So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?

<!DOCTYPE html>

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

Body:
var random = [];
// not useful? but in your code
document.getElementById("display").innerHTML = random;

function FirstFunction(event) {
    // get local value into a and use it the + avoids parseInt
    let a = Math.abs(+document.getElementById("diceamount").value);
    for (i=0; i<a; i++) {
      // x was not declared and should be
      let x = Math.floor(Math.random() * 4) + 1;
      random.push(x);
    }
    // could be textContent instead...outside loop
    document.getElementById("display").innerHTML = random;
}

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display">x</p>