问:
Android- Select CSV file from Google Drive and parse it in java
I am trying to load CSV file from Google drive and parse it in java. But whenever I select the file, it show me the Exception: File not Found.

Below is my implemented code:

Chooser intent code:

```<code>    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("text/csv");   //XML file only
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try
    {
        startActivityForResult(Intent.createChooser(intent, "Select"), 100);
    } catch (android.content.ActivityNotFoundException ex)
    {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Drive Not Found", Toast.LENGTH_SHORT).show();
    }
</code>```

onActivity Result:

```<code>   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode)
    {
        case 100:
            {
            if (resultCode == RESULT_OK)
            {
                //onImport(new File(data.getData().getPath()));
                String filePath = null;
                Uri uri = data.getData();

                File file = new File(uri.toString());
                if (file.exists()) {
                    //Do something
                    System.out.println("Exists");
                    proImportCSV(new File(data.getData().getPath()));
                }
                else
                {
                    System.out.println("Not Exists");
                }

            }
        }
    }
}
</code>```

Parsing of CSV using CSVReader

```<code>   private void proImportCSV(File from)
{
    try
    {
        // reading CSV and writing table
        CSVReader reader = null;
        try
        {
            reader = new CSVReader(new FileReader(from));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String[] nextLine;
        try {
            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                System.out.println(nextLine[0] + nextLine[1] + "etc...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Kindly tell me why I am getting file not found error. Plus, Am I parsing the csv rightly? If not right, Then tell me the right one with detail.

Thanks in advance!

答:
I have parsed it using bufferReader and everything went perfect!</p>

```<code>        Uri uri = data.getData();
            BufferedReader mBufferedReader = null;
            String line;

             try
                {
                    InputStream inputStream = getContentResolver().openInputStream(uri);
                    mBufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    while ((line = mBufferedReader.readLine()) != null)
                    {
                        System.out.println("LLLLL: "+ line);
                    }
                    mBufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
</code>```

Body:
I am trying to load CSV file from Google drive and parse it in java. But whenever I select the file, it show me the Exception: File not Found.

Below is my implemented code:

Chooser intent code:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("text/csv");   //XML file only
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try
    {
        startActivityForResult(Intent.createChooser(intent, "Select"), 100);
    } catch (android.content.ActivityNotFoundException ex)
    {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Drive Not Found", Toast.LENGTH_SHORT).show();
    }

onActivity Result:

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode)
    {
        case 100:
            {
            if (resultCode == RESULT_OK)
            {
                //onImport(new File(data.getData().getPath()));
                String filePath = null;
                Uri uri = data.getData();

                File file = new File(uri.toString());
                if (file.exists()) {
                    //Do something
                    System.out.println("Exists");
                    proImportCSV(new File(data.getData().getPath()));
                }
                else
                {
                    System.out.println("Not Exists");
                }

            }
        }
    }
}

Parsing of CSV using CSVReader

   private void proImportCSV(File from)
{
    try
    {
        // reading CSV and writing table
        CSVReader reader = null;
        try
        {
            reader = new CSVReader(new FileReader(from));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String[] nextLine;
        try {
            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                System.out.println(nextLine[0] + nextLine[1] + "etc...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Kindly tell me why I am getting file not found error. Plus, Am I parsing the csv rightly? If not right, Then tell me the right one with detail.

Thanks in advance!

Body:
I have parsed it using bufferReader and everything went perfect!

        Uri uri = data.getData();
            BufferedReader mBufferedReader = null;
            String line;

             try
                {
                    InputStream inputStream = getContentResolver().openInputStream(uri);
                    mBufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    while ((line = mBufferedReader.readLine()) != null)
                    {
                        System.out.println("LLLLL: "+ line);
                    }
                    mBufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }


来源: stackexchange

问:
Why does D3's focus on an input work only the first time?
It's possible to focus on an input field using D3, without even the need to go through setTimeout (I don't know why, but I'm not complaining).

But this only works the first time. After the second press on Set (i.e.: Set, Reset, Set), the input field does not receive focus. Why?

Setting a callback to focus after the transition is complete gives me an error.

```<code><!DOCTYPE HTML>
<head>
    <style>
        div { width: 300px; }
        div#outerdiv  { height: 500px; background-color: #ccc; }
        div#topdiv    { height: 400px; background-color: #dff; }
        div#bottomdiv { height: 0px;   background-color: #ffd; display: 'none' }
        input:focus { background-color: pink; }
    </style>
</head>
<body>
    <div id="outerdiv">
        <div id="topdiv">
            <button onclick=open_form();>Set</button>
            <button onclick=close_form();>Reset</button>
        </div>

        <div id="bottomdiv">
            <form action="javascript:close_form()">
                Name:
                <input type="text" id="myTextField" name="name">
                <input type="submit" name="submit" value="Submit">
            </form>
        </div>
    </div>

    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

    <script>
        function open_form() {
            d3.select('#topdiv').transition().duration(500)
              .style('height', '100px');
            d3.select('#bottomdiv').transition().duration(500)
              .style('height', '300px').style('display', 'inline-block');

            d3.select("#myTextField").node().focus();
        }
        function close_form() {
            d3.select('#topdiv').transition().duration(500)
              .style('height', '390px');
            d3.select('#bottomdiv').transition().duration(500)
              .style('height', '10px').style('display', 'none');
        }
    </script>
</body>
</code>```

答:
Each time you hit the Reset button, i.e. when close_form() is called, your #bottomdiv is transitioned to display: none:

```<code>d3.select('#bottomdiv').transition().duration(500)
    .style('height', '10px').style('display', 'none');
</code>```

This has some side effects, though. Looking at the HTML5 spec on focus management shows, that an element, which is not being rendered, is also not focusable:

7.4.2 Focus management

An element is focusable if all of the following conditions are met:

[…]

The element is either being rendered or […].

Hence, the next time you hit Set whereby invoking open_form() the input is not focusable because the transition to inline-block has not come to an end yet. The easiest way around this is to listen for the transition's end event which is fired once the transition ends.

```<code>   d3.select('#bottomdiv').transition().duration(500)
       .style('height', '300px').style('display', 'inline-block')
       .on("end", () => d3.select("#myTextField").node().focus());
</code>```

Have a look at the following snippet for a working demo:

function open_form() {
    d3.select('#topdiv').transition().duration(500)
      .style('height', '100px');
    d3.select('#bottomdiv').transition().duration(500)
      .style('height', '300px').style('display', 'inline-block')
      .on("end", () => d3.select("#myTextField").node().focus());

}
function close_form() {
    d3.select('#topdiv').transition().duration(500)
      .style('height', '390px');
    d3.select('#bottomdiv').transition().duration(500)
      .style('height', '10px').style('display', 'none');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { width: 300px; }
div#outerdiv  { height: 500px; background-color: #ccc; }
div#topdiv    { height: 400px; background-color: #dff; }
div#bottomdiv { height: 0px;   background-color: #ffd; display: 'none' }
input:focus { background-color: pink; }</code>```

            <button onclick=open_form();>Set</button>
            <button onclick=close_form();>Reset</button>

            <form action="javascript:close_form()">
                Name:
                <input type="text" id="myTextField" name="name">
                <input type="submit" name="submit" value="Submit">
            </form>

```

ContentLicense: CC BY-SA 3.0

Body:
It's possible to focus on an input field using D3, without even the need to go through setTimeout (I don't know why, but I'm not complaining).

But this only works the first time. After the second press on Set (i.e.: Set, Reset, Set), the input field does not receive focus. Why?

Setting a callback to focus after the transition is complete gives me an error.

<!DOCTYPE HTML>

            <button onclick=open_form();>Set</button>
            <button onclick=close_form();>Reset</button>

            <form action="javascript:close_form()">
                Name:
                <input type="text" id="myTextField" name="name">
                <input type="submit" name="submit" value="Submit">
            </form>

Body:
Each time you hit the Reset button, i.e. when close_form() is called, your #bottomdiv is transitioned to display: none:

d3.select('#bottomdiv').transition().duration(500)
    .style('height', '10px').style('display', 'none');

This has some side effects, though. Looking at the HTML5 spec on focus management shows, that an element, which is not being rendered, is also not focusable:

7.4.2 Focus management

An element is focusable if all of the following conditions are met:

[…]

The element is either being rendered or […].

Hence, the next time you hit Set whereby invoking open_form() the input is not focusable because the transition to inline-block has not come to an end yet. The easiest way around this is to listen for the transition's end event which is fired once the transition ends.

   d3.select('#bottomdiv').transition().duration(500)
       .style('height', '300px').style('display', 'inline-block')
       .on("end", () => d3.select("#myTextField").node().focus());

Have a look at the following snippet for a working demo:

function open_form() {
    d3.select('#topdiv').transition().duration(500)
      .style('height', '100px');
    d3.select('#bottomdiv').transition().duration(500)
      .style('height', '300px').style('display', 'inline-block')
      .on("end", () => d3.select("#myTextField").node().focus());

}
function close_form() {
    d3.select('#topdiv').transition().duration(500)
      .style('height', '390px');
    d3.select('#bottomdiv').transition().duration(500)
      .style('height', '10px').style('display', 'none');
}

div { width: 300px; }
div#outerdiv  { height: 500px; background-color: #ccc; }
div#topdiv    { height: 400px; background-color: #dff; }
div#bottomdiv { height: 0px;   background-color: #ffd; display: 'none' }
input:focus { background-color: pink; }

<body>
    <div id="outerdiv">
        <div id="topdiv">
            <button onclick=open_form();>Set</button>
            <button onclick=close_form();>Reset</button>
        </div>

        <div id="bottomdiv">
            <form action="javascript:close_form()">
                Name:
                <input type="text" id="myTextField" name="name">
                <input type="submit" name="submit" value="Submit">
            </form>
        </div>
    </div>

    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

</body>


问:
Pheatmap Color for Specific Value
I am very new to R and recently I have been playing around with the pheatmap library to generate, well, heatmaps. My problem is that I want to color my heatmap in a specific way. I'll describe below:

Values < 1 should be a color ramp (e.g. dark blue to light blue)

A value exactly equal to 1 should be dark grey

Values > 1 should be a color ramp (e.g. dark red to light red)

I have played around with the breaks parameter and the color parameter with various palettes but I can't seem to nail a good solution. the closest I've come is something like this:

```<code>pheatmap(mtx,
     color =  c('#4444FF','#F4FF4F','#FF4444'),
     breaks = c(0,1,2,3),
     legend_breaks = c(0,1,2) )
</code>```

But this doesn't allow for visualization of the ranges, i.e. 0.1 should look a different shade than 0.9 even though they should both be blue. Can anyone provide suggestions or advice? I did look at This ticket and consider changing 1 to NA, but it's a bit too complex for me. Not to mention I'd have to turn off clustering for pheatmap which is not something I wish to do. Thanks!

答:
You cannot set the color for a specific value but you can go for a very small range like [0.999,1.001]

You should set the breaks for the ranges you mentioned in the question and then assign the colors accordingly;

```<code>library(pheatmap)
bk1 <- c(seq(-2,0.9,by=0.1),0.999)
bk1 <- c(1.001,seq(1.1,3,by=0.1))
bk <- c(bk1,bk2)  #combine the break limits for purpose of graphing

my_palette <- c(colorRampPalette(colors = c("darkblue", "lightblue"))(n = length(bk1)-1),
              "gray38", "gray38",
              c(colorRampPalette(colors = c("darkred", "tomato1"))(n = length(bk2)-1)))

pheatmap(df, color = my_palette, breaks = bk, scale = "none",
             cluster_rows = F, cluster_cols = F, margin = c(5,5))
</code>```

I made an example dataset using rnorm.within:

```<code>   #V1 is random between -2 and 3
   #V2 is equal to 1
   #V3 is random between 0 and 3

   df <- cbind(rnorm.within(1000, -2, 3),rep(1,1000), rnorm.within(1000,0,3))
</code>```

And this will be the heatmap for the data created above;

Title: Pheatmap Color for Specific Value

Body:
I am very new to R and recently I have been playing around with the pheatmap library to generate, well, heatmaps. My problem is that I want to color my heatmap in a specific way. I'll describe below:

Values < 1 should be a color ramp (e.g. dark blue to light blue)

A value exactly equal to 1 should be dark grey

Values > 1 should be a color ramp (e.g. dark red to light red)

I have played around with the breaks parameter and the color parameter with various palettes but I can't seem to nail a good solution. the closest I've come is something like this:

pheatmap(mtx,
     color =  c('#4444FF','#F4FF4F','#FF4444'),
     breaks = c(0,1,2,3),
     legend_breaks = c(0,1,2) )

But this doesn't allow for visualization of the ranges, i.e. 0.1 should look a different shade than 0.9 even though they should both be blue. Can anyone provide suggestions or advice? I did look at This ticket and consider changing 1 to NA, but it's a bit too complex for me. Not to mention I'd have to turn off clustering for pheatmap which is not something I wish to do. Thanks!

Body:
You cannot set the color for a specific value but you can go for a very small range like [0.999,1.001]

You should set the breaks for the ranges you mentioned in the question and then assign the colors accordingly;

library(pheatmap)
bk1 <- c(seq(-2,0.9,by=0.1),0.999)
bk1 <- c(1.001,seq(1.1,3,by=0.1))
bk <- c(bk1,bk2)  #combine the break limits for purpose of graphing

my_palette <- c(colorRampPalette(colors = c("darkblue", "lightblue"))(n = length(bk1)-1),
              "gray38", "gray38",
              c(colorRampPalette(colors = c("darkred", "tomato1"))(n = length(bk2)-1)))

pheatmap(df, color = my_palette, breaks = bk, scale = "none",
             cluster_rows = F, cluster_cols = F, margin = c(5,5))

I made an example dataset using rnorm.within:

   #V1 is random between -2 and 3
   #V2 is equal to 1
   #V3 is random between 0 and 3

   df <- cbind(rnorm.within(1000, -2, 3),rep(1,1000), rnorm.within(1000,0,3))

And this will be the heatmap for the data created above;

ContentLicense: CC BY-SA 4.0


问:
Alexa Skill - How to Retrieve Slot Value in Lambda Function
I am developing an Alexa Skill with one Intent that includes a Slot with several possible values.

My slot is defined with "name" : "Channel", "type" : "LIST_OF_CHANNELS", and values

iqram

ingrid

phil

clyde

How do I retrieve the uttered slot value to use in my Lambda function? It's the "retrieve value of slot from utterance part" I'm looking to have answered. Thanks so much.

```<code> // retrieve value of slot from utterance
 var c = intent.slots.Channel.value;

 // append value to end of URL that references API
 fetchEnseParse("/channel/" + c, function(body) {

 // continuation of this function is below
</code>```

答:
var c = this.event.request.intent.slots.slotname.value

This should give you what you're looking for.

Body:
I am developing an Alexa Skill with one Intent that includes a Slot with several possible values.

My slot is defined with "name" : "Channel", "type" : "LIST_OF_CHANNELS", and values

iqram

ingrid

phil

clyde

How do I retrieve the uttered slot value to use in my Lambda function? It's the "retrieve value of slot from utterance part" I'm looking to have answered. Thanks so much.

 // retrieve value of slot from utterance
 var c = intent.slots.Channel.value;

 // append value to end of URL that references API
 fetchEnseParse("/channel/" + c, function(body) {

 // continuation of this function is below


问:
What is java interface equivalent in Ruby?
Can we expose interfaces in Ruby like we do in java and enforce the Ruby modules or classes to implement the methods defined by interface.

One way is to use inheritance and method_missing to achieve the same but is there any other more appropriate approach available ?

答:
There are no such things as interfaces in the Java way. But there are other things you can enjoy in ruby.

If you want to implement some kind of types and interface - so that the objects can be checked whether they has some methods/messages you require from them -, you can then take a look at rubycontracts. It defines a mechanism similar to the PyProtocols. A blog about type checking in ruby is here.

The mentioned approached are not living projects, although the goal seems to be nice at first, it seems that most of the ruby developers can live without strict type checking. But the flexibility of ruby enables to implement type checking.

If you want to extend objects or classes (the same thing in ruby) by certain behaviors or somewhat have the ruby way of multiple inheritance, use the include or extend mechanism. With include you can include methods from another class or module into an object. With extend you can add behavior to a class, so that its instances will have the added methods. That was a very short explanation though.

I my opinion the best way to resolve the Java interface need is to understand the ruby object model (see Dave Thomas lectures for instance). Probably you will forget about Java interfaces. Or you have an exceptional application on your schedule.

ContentLicense: CC BY-SA 2.5


问:
In my React webapp, how do I show the right date in a "Website last updated" field?
I'm putting together a demo app in which I frequently add content and new React components. I have just added the component react-timeago for showing when the latest changes were made to the site. Now I want to give that component the right timestamp.

At worst, I suppose I could show the last time that the server was started. I am using webpack-dev-server locally. I haven't yet gone live with this site, but it will probably (like webpack-dev-server) be an express-based solution when I do. So one option is perhaps to do a grep on an express-generated logfile for server start entries. Solving that would solve the question to an extent. It's worth noting though that adding content would not require a restart, so this solution is perhaps not ideal. Presumably, I could use some kind of middleware (logger or otherwise) in express for this.

Another possible approach might be some kind of directory watch mechanism that records the last time a change was made. Should I somehow hook this into a redux state, for example? There are so many components available that it's difficult to know which ones to put together (with my limited experience in this area) to achieve this.

My site is a lightweight single pager and I'm loath to add any kind of datastore behind it at this stage as it seems like overkill to me.

I can also mention that I'm using webpack 2. Aside from that it's a really basic React app with a couple of components.

To summarize, I am after some way of looking for added content (eg. mp3 files) or changed code files, and getting that timestamp into my react-timeago component.

答:
As @Joe Clay suggested, I used Webpack.DefinePlugin to fill a constant with the current time at restart. This worked fine, I added the following lines into my webpack.config.js:

    var dateString = new Date().toDateString();
    ...
    new webpack.DefinePlugin({
        LAST_UPDATED: JSON.stringify(dateString)
    })```
</div>
</div>
</p>

<p>And was able to access the the constant in my React component: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style={{marginTop:120}}>A sinewave440hz demo site.<br/>
  This site was updated
  <TimeAgo date={LAST_UPDATED} formatter={formatter}/>.
</div></code>```

Recording changes in the assets could also be done at startup if the previous state of the assets was recorded somewhere.

Body:
As @Joe Clay suggested, I used Webpack.DefinePlugin to fill a constant with the current time at restart. This worked fine, I added the following lines into my webpack.config.js:

    var dateString = new Date().toDateString();
    ...
    new webpack.DefinePlugin({
        LAST_UPDATED: JSON.stringify(dateString)
    })

And was able to access the the constant in my React component:

<div style={{marginTop:120}}>A sinewave440hz demo site.<br/>
  This site was updated
  <TimeAgo date={LAST_UPDATED} formatter={formatter}/>.
</div>

Recording changes in the assets could also be done at startup if the previous state of the assets was recorded somewhere.


问:
How to get the $_POST from specific <select> in PHP form selected by a checkbox?
I have a form that displays more than one record (usernames) and has a 'checkbox' for each one of them. When the user clicks on the SUBMIT button, I want to grab the information from the selected record or records. Here is what I have...

```<code><SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function jqCheckAll3( id, pID )
{
   $( "#" + pID + " :checkbox").attr('checked', $('#' + id).is(':checked'));
}
//  End -->
</script>
<form name='myForm' action='adminprocess.php' method='POST'>
<table id='left' style='margin-bottom:5px;'>
<tr>
<th class='sortable'>Username</th><th class='sortable'>Name</th>
<th class='sortable'>Email</th><th class='sortable'>Level</th><th>Department</th><th class='sortable'>Registered</th><th>
<input type="checkbox" id="checkL" onclick="jqCheckAll3(this.id, 'left');"/></th>
</tr>
<?php
 while($row = $result->fetch())
 {
    $regdate = $row['regdate'];
    $reg  = date("j M, y, g:i a", $regdate);
    echo "<tr><td><a href='".$config['WEB_ROOT']."admin/index.php?id=6&usertoedit=".$username."'>".$username."</a></td>\n";

    echo "<td>".$fname." ".$lname."</td>\n";
    echo "<td>".$Uemail."</td>\n";
    echo "<td>";
    ?>
    <select name="ulevel" id="ulevel">
      <option value="8">Supervisor</option>
      <option value="6">Regular user</option>
      <option value="5">Reports Only</option>
    </select>

    <?PHP
    echo "</td>\n";
    echo "<td>\n\t";
    ?>
    <select name="departmentid" id="departmentid">
         <option value="1">North East</option>
         <option value="2">South</option>
         <option value="3">Central</option>
    </select>
    <?PHP
    echo "</td>\n";
    echo "<td>".$reg."</td>\n";
    echo "echo "</td>\n";
echo "<td>".$reg."</td>\n";
echo "</td><td><input name='user_name[]' type='checkbox' value='".$row['username']."' />";
echo "</td>\n</tr>";
    echo "</td>\n</tr>";
}
?>
</table>
<input type="hidden" name="activateusers" value="1">
<input type="submit" value="Activate Selected Users">
<br>
</form>
</code>```

and my adminprocess.php looks like this...

```<code>function procActivateUsers(){
    global $session, $database, $mailer;
    $config = $database->getConfigs();
    /* Account edit attempt */

    foreach($_POST['user_name'] as $username) {
        $sql = $database->connection->prepare("UPDATE ".TBL_USERS." SET USERLEVEL = '".$_POST['ulevel']."', DEPTID = '".$_POST['departmentid']."' WHERE username = '$username'");
        $sql->execute();
        $req_user_info = $database->getUserInfo($username);
        $email = $req_user_info['email'];
        $mailer->adminActivated($username,$email,$config);
    }
    header("Location: ../admin/index.php?id=3");
    }
</code>```

DO NOT worry about sanitizing or anything else at the moment, I am doing all that before. Just need to grab something like:

User 1 -> ulevel = 6 -> departmentid = 3,

User 2 -> ulevel = 4 -> departmentid = 1

Thanks for any help

答:
You need to use array-style names for the <select> fields, so you'll get an array of all the selections.

You can put the username inside the brackets, so they'll be associated with the checkboxes. Also, you need to give them unique IDs, you can put the username there as well (but are you sure these elements need IDs in the first place?).

```<code>?>
<select name="ulevel[<?php echo $row['username'];?>]" id="ulevel-<?php echo $row['username'];?>">
  <option value="8">Supervisor</option>
  <option value="6">Regular user</option>
  <option value="5">Reports Only</option>
</select>

<?PHP
echo "</td>\n";
echo "<td>\n\t";
?>
<select name="departmentid[<?php echo $row['username'];?>]" id="departmentid-<?php echo $row['username'];?>">
     <option value="1">North East</option>
     <option value="2">South</option>
     <option value="3">Central</option>
</select>
</code>```

Then in the PHP code, you can do:

```<code>$sql = $database->connection->prepare("UPDATE ".TBL_USERS." SET USERLEVEL = :ulevel, DEPTID = :departmentid WHERE username = :username");
$sql->bindParam($ulevel, $deptid, $username);
foreach ($_POST['user_name'] as $username) {
    $ulevel = $_POST['ulevel'][$username];
    $deptid = $_POST]['departmentid'][$username];
    $sql->execute();
    $req_user_info = $database->getUserInfo($username);
    $email = $req_user_info['email'];
    $mailer->adminActivated($username,$email,$config);
}
</code>```

If you have an ID field in the user table, I suggest you use that instead of the username, as you then don't have to worry about potential problems from special characters (I assumed above that usernames won't contain any characters that need special encoding in HTML).

Body:
I have a form that displays more than one record (usernames) and has a 'checkbox' for each one of them. When the user clicks on the SUBMIT button, I want to grab the information from the selected record or records. Here is what I have...

<form name='myForm' action='adminprocess.php' method='POST'>

Username	Name
Email	Level	Department	Registered
<input type="checkbox" id="checkL" onclick="jqCheckAll3(this.id, 'left');"/>

<?php
 while($row = $result->fetch())
 {
    $regdate = $row['regdate'];
    $reg  = date("j M, y, g:i a", $regdate);
    echo "
".$username."	\n";

    echo "".$fname." ".$lname."	\n";
    echo "".$Uemail."	\n";
    echo "";
    ?>
    <select name="ulevel" id="ulevel">
      <option value="8">Supervisor</option>
      <option value="6">Regular user</option>
      <option value="5">Reports Only</option>
    </select>

    <?PHP
    echo "	\n";
    echo "\n\t";
    ?>
    <select name="departmentid" id="departmentid">
         <option value="1">North East</option>
         <option value="2">South</option>
         <option value="3">Central</option>
    </select>
    <?PHP
    echo "	\n";
    echo "".$reg."	\n";
    echo "echo "	\n";
echo "".$reg."	\n";
echo "	<input name='user_name[]' type='checkbox' value='".$row['username']."' />";
echo "	\n
";
    echo "	\n
";
}
?>

<input type="hidden" name="activateusers" value="1">
<input type="submit" value="Activate Selected Users">

</form>

and my adminprocess.php looks like this...

function procActivateUsers(){
    global $session, $database, $mailer;
    $config = $database->getConfigs();
    /* Account edit attempt */

    foreach($_POST['user_name'] as $username) {
        $sql = $database->connection->prepare("UPDATE ".TBL_USERS." SET USERLEVEL = '".$_POST['ulevel']."', DEPTID = '".$_POST['departmentid']."' WHERE username = '$username'");
        $sql->execute();
        $req_user_info = $database->getUserInfo($username);
        $email = $req_user_info['email'];
        $mailer->adminActivated($username,$email,$config);
    }
    header("Location: ../admin/index.php?id=3");
    }

DO NOT worry about sanitizing or anything else at the moment, I am doing all that before. Just need to grab something like:

User 1 -> ulevel = 6 -> departmentid = 3,

User 2 -> ulevel = 4 -> departmentid = 1

Thanks for any help

Body:
You need to use array-style names for the <select> fields, so you'll get an array of all the selections.

You can put the username inside the brackets, so they'll be associated with the checkboxes. Also, you need to give them unique IDs, you can put the username there as well (but are you sure these elements need IDs in the first place?).

?>
<select name="ulevel[<?php echo $row['username'];?>]" id="ulevel-<?php echo $row['username'];?>">
  <option value="8">Supervisor</option>
  <option value="6">Regular user</option>
  <option value="5">Reports Only</option>
</select>

<?PHP
echo "</td>\n";
echo "<td>\n\t";
?>
<select name="departmentid[<?php echo $row['username'];?>]" id="departmentid-<?php echo $row['username'];?>">
     <option value="1">North East</option>
     <option value="2">South</option>
     <option value="3">Central</option>
</select>

Then in the PHP code, you can do:

$sql = $database->connection->prepare("UPDATE ".TBL_USERS." SET USERLEVEL = :ulevel, DEPTID = :departmentid WHERE username = :username");
$sql->bindParam($ulevel, $deptid, $username);
foreach ($_POST['user_name'] as $username) {
    $ulevel = $_POST['ulevel'][$username];
    $deptid = $_POST]['departmentid'][$username];
    $sql->execute();
    $req_user_info = $database->getUserInfo($username);
    $email = $req_user_info['email'];
    $mailer->adminActivated($username,$email,$config);
}

If you have an ID field in the user table, I suggest you use that instead of the username, as you then don't have to worry about potential problems from special characters (I assumed above that usernames won't contain any characters that need special encoding in HTML).


问:
What is the difference between HTTP 408 and 504 errors?
These are both timeout errors, but who is timing out in a 408 vs. a 504?

From w3, 408 is defined as:

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

...And 504 is:

The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.

So who is the 'client' in the 408 if not an intermediary server? If it's an actual end user, how does a server know to wait for their request before they have made it?

答:
Amazon documentation tells: http://docs.aws.amazon.com/en_en/elasticloadbalancing/latest/classic/ts-elb-error-message.html#ts-elb-errorcodes-http408

Indicates that the client cancelled the request or failed to send a full request

Mozilla documentation tells: https://developer.mozilla.org/en/docs/Web/HTTP/Status/408

The HTTP 408 Request Timeout response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, even without any previous request by the client


问:
Convert VB.NET Group By expression to C#
I have to convert the following expression from VB.NET to C#:

```<code>Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending
</code>```

I'm confused with Group By section...

答:
Utilize anonymous types after your GroupBy, which will allow you to OrderBy group g's Count().

```<code>.Select(g => new { Group = g.Key.GeofenceLocation, Count = g.Count() })
</code>```

Using LINQ fluent syntax:

```<code>var z = db.GPSdevice
          .Where(d => d.CompanyId == currentuser.CompanyId && d.Type == "Trailer")
          .OrderByDescending(d => d.ListOrder)
          .GroupBy(g => g.GeofenceLocation)
          .Select(g => new { Group = g.Key.GeofenceLocation, Count = g.Count() })
          .OrderByDescending(g => g.Count)
</code>```

Note:

g.Key refers to the d object

g.Count refers to the anonymous type's Count and not LINQ's Count().

Body:
I have to convert the following expression from VB.NET to C#:

Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending

I'm confused with Group By section...

Body:
Utilize anonymous types after your GroupBy, which will allow you to OrderBy group g's Count().

.Select(g => new { Group = g.Key.GeofenceLocation, Count = g.Count() })

Using LINQ fluent syntax:

var z = db.GPSdevice
          .Where(d => d.CompanyId == currentuser.CompanyId && d.Type == "Trailer")
          .OrderByDescending(d => d.ListOrder)
          .GroupBy(g => g.GeofenceLocation)
          .Select(g => new { Group = g.Key.GeofenceLocation, Count = g.Count() })
          .OrderByDescending(g => g.Count)

Note:

g.Key refers to the d object

g.Count refers to the anonymous type's Count and not LINQ's Count().


问:
iPad Splitter - Popup Tint
I am trying to tint my UI to a nice brown. The pop up associated with the splitter is blackish-blue. How do I change its tint to the one I have applied to the rest of the app?

Here's a picture:

When I change the tint in IB it then looks like this:

答:
Unfortunately the border can not be changed from the grey color..only the title. You need to set the tintcolor property on the navigation bar.

myController.navigationBar.tintColor

Title: iPad Splitter - Popup Tint


问:
Passing OpenCV Image as function argument with ctypes
I have written some optimized C++ code for FLANN Matching with SIFT features (OpenCV) that returns the number of good matches (int) found on two images. My code works well when I pass the two image paths (query and train images) as char* via ctypes. I am writing a wrapper class in Python to handle these functions. However, I want to pass the two arguments as image instances and not as char* or std::string, namely the objects that are results of cv2.imread(apath) in Python OpenCV bindings.

My .cpp source code:

```<code>//detectors.cpp
#include <stdio.h>
#include <iostream>
#include "string.h"
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

///* (extern c) Get good matches using SIFT and FLANN Matcher * ///
extern "C" int get_matches_sift_flann(char* img1, char* img2)
{
  Mat img_1 = imread(img1, CV_LOAD_IMAGE_GRAYSCALE );
  Mat img_2 = imread(img2, CV_LOAD_IMAGE_GRAYSCALE );

  //-- Step 1: Detect the keypoints using SIFT Detector
  int minHessian = 400;
  SiftFeatureDetector detector( minHessian );
  std::vector<KeyPoint> keypoints_1, keypoints_2;
  detector.detect( img_1, keypoints_1 );
  detector.detect( img_2, keypoints_2 );
  //-- Step 2: Calculate descriptors (feature vectors)
  SiftDescriptorExtractor extractor;
  Mat descriptors_1, descriptors_2;
  extractor.compute( img_1, keypoints_1, descriptors_1 );
  extractor.compute( img_2, keypoints_2, descriptors_2 );
  //-- Step 3: Matching descriptor vectors using FLANN matcher
  FlannBasedMatcher matcher;
  std::vector< DMatch > matches;
  matcher.match( descriptors_1, descriptors_2, matches );
  double max_dist = 0; double min_dist = 100;
  //-- Quick calculation of max and min distances between keypoints
  for( int i = 0; i < descriptors_1.rows; i++ )
  { double dist = matches[i].distance;
    if( dist < min_dist ) min_dist = dist;
    if( dist > max_dist ) max_dist = dist;
  }
  //-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist,
  //-- or a small arbitary value ( 0.02 ) in the event that min_dist is very
  //-- small)
  //-- PS.- radiusMatch can also be used here.
  vector< DMatch > good_matches;
  for( int i = 0; i < descriptors_1.rows; i++ )
  { if( matches[i].distance <= max(2*min_dist, 0.02) )
    { good_matches.push_back( matches[i]); }
  }
  int n =  (int) good_matches.size();
  return n;
}
</code>```

And my python wrapper.py module

```<code>#wrapper module for libdetectors.so

import os
import ctypes as c

libDETECTORS = c.cdll.LoadLibrary('./libdetectors.so')

class CExternalMatchesFunction:

    def __init__(self, c_func):
        self.c_func = c_func
        self.c_func.argtypes = [c.c_char_p, c.c_char_p]
        self.c_func.restype = c.c_int

    def __call__(self, train_img_filename, query_img_filename):
        r = self.c_func(c.c_char_p(train_img_filename), c.c_char_p(query_img_filename))
        return r

#initialize wrapped functions
get_matches_sift_flann = CExternalMatchesFunction(libDETECTORS.get_matches_sift_flann)
</code>```

All in all, I want to change CExternalMatchesFunction().c_func.argtypes to a list of image objects like these:

```<code>import cv2
img1 = cv2.imread('foo.jpg')
img2 = cv2.imread('boo.jpg')
</code>```

Thanks in advance

答: SOLUTION: Return void* and cast it again to cpp object when passed

Body:
I have written some optimized C++ code for FLANN Matching with SIFT features (OpenCV) that returns the number of good matches (int) found on two images. My code works well when I pass the two image paths (query and train images) as char* via ctypes. I am writing a wrapper class in Python to handle these functions. However, I want to pass the two arguments as image instances and not as char* or std::string, namely the objects that are results of cv2.imread(apath) in Python OpenCV bindings.

My .cpp source code:

//detectors.cpp
#include <stdio.h>
#include <iostream>
#include "string.h"
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

///* (extern c) Get good matches using SIFT and FLANN Matcher * ///
extern "C" int get_matches_sift_flann(char* img1, char* img2)
{
  Mat img_1 = imread(img1, CV_LOAD_IMAGE_GRAYSCALE );
  Mat img_2 = imread(img2, CV_LOAD_IMAGE_GRAYSCALE );

  //-- Step 1: Detect the keypoints using SIFT Detector
  int minHessian = 400;
  SiftFeatureDetector detector( minHessian );
  std::vector<KeyPoint> keypoints_1, keypoints_2;
  detector.detect( img_1, keypoints_1 );
  detector.detect( img_2, keypoints_2 );
  //-- Step 2: Calculate descriptors (feature vectors)
  SiftDescriptorExtractor extractor;
  Mat descriptors_1, descriptors_2;
  extractor.compute( img_1, keypoints_1, descriptors_1 );
  extractor.compute( img_2, keypoints_2, descriptors_2 );
  //-- Step 3: Matching descriptor vectors using FLANN matcher
  FlannBasedMatcher matcher;
  std::vector< DMatch > matches;
  matcher.match( descriptors_1, descriptors_2, matches );
  double max_dist = 0; double min_dist = 100;
  //-- Quick calculation of max and min distances between keypoints
  for( int i = 0; i < descriptors_1.rows; i++ )
  { double dist = matches[i].distance;
    if( dist < min_dist ) min_dist = dist;
    if( dist > max_dist ) max_dist = dist;
  }
  //-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist,
  //-- or a small arbitary value ( 0.02 ) in the event that min_dist is very
  //-- small)
  //-- PS.- radiusMatch can also be used here.
  vector< DMatch > good_matches;
  for( int i = 0; i < descriptors_1.rows; i++ )
  { if( matches[i].distance <= max(2*min_dist, 0.02) )
    { good_matches.push_back( matches[i]); }
  }
  int n =  (int) good_matches.size();
  return n;
}

And my python wrapper.py module

#wrapper module for libdetectors.so

import os
import ctypes as c

libDETECTORS = c.cdll.LoadLibrary('./libdetectors.so')

class CExternalMatchesFunction:

    def __init__(self, c_func):
        self.c_func = c_func
        self.c_func.argtypes = [c.c_char_p, c.c_char_p]
        self.c_func.restype = c.c_int

    def __call__(self, train_img_filename, query_img_filename):
        r = self.c_func(c.c_char_p(train_img_filename), c.c_char_p(query_img_filename))
        return r

#initialize wrapped functions
get_matches_sift_flann = CExternalMatchesFunction(libDETECTORS.get_matches_sift_flann)

All in all, I want to change CExternalMatchesFunction().c_func.argtypes to a list of image objects like these:

import cv2
img1 = cv2.imread('foo.jpg')
img2 = cv2.imread('boo.jpg')

Thanks in advance


问:
Java, Spring, JSP, <form>. Neither BindingResult nor plain target object for bean name 'command' available as request attribute
Hey, everyone!

I can't understand why it happens when I try to open webapp:

```<code>Neither BindingResult nor plain target object for bean name 'command' available as request attribute
</code>```

and

```<code>org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 53
</code>```

Here is form from index.jsp

```<code>51 <c:url var="addAction" value="/email/add.form"/>
52 <form:form action="${addAction}" commandName="command">
53    <form:input path="email" type="email" placeholder="Enter email" class="cell"/>
54    <input type="submit" class="button" value="<spring:message text="Send"/>"/>
55 </form:form>
</code>```

Here is Controller

```<code>@Controller
public class EmailController {
    private EmailService emailService;

    @Autowired
    @Qualifier("emailService")
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }

    @RequestMapping(value = "/email/add", method = RequestMethod.POST)
    public String addEmail(@ModelAttribute("email") EmailEntity emailEntity) {
        this.emailService.addEmail(emailEntity);
        return "redirect:/email.form";
    }
}
</code>```

The following is Stacktrace and Root Cause

```<code>Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
    org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
    org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
    org.apache.jsp.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:323)
    org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:271)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:184)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</code>```

Sorry, if something has been missed.
Thanks!

答:
Why does this happen?

The complete answer is here. This is just my easier explanation for Spring beginners.

The short answer is, that the Spring form does not work without a "form backing object" or "command object", as it is also called in the Spring docs.

The index.jsp should be returned by a controller method, that makes a "bean name 'command' available to the form as request attribute" as stated in the exception.

--- Long answer ---

The Spring form documentation reads:

"...form:form tag renders an HTML 'form' tag and exposes a binding path to inner tags for binding. It puts the command object in the PageContext
so that the command object can be accessed by inner tags..."

This means, that the inner tags (like form:input) need a 'command object' because they want to bind to it.

So, what is this "command object" (also known as the form backing object) and where does it come from?

Read this a couple of times:

The form backing object is the bean/entity that the form is dealing with - like for example the form addItem.jsp is dealing with an entity "Item". The entity/command object comes from the the method in the form controller which returns the form.

The form backing object/bean/entity is going to have its properties set in the form, but it needs to be available already when we show the empty form.

We will solve our problem in two steps:

add the form backing object to the model in controller method that shows the form, to make it accessible for the form - (for example) addItem.jsp

```<code>   @RequestMapping("/add-item")
   public String showAddItemForm(Model model) {
       // adding the form backing object/entity - here for example named item
       // to the model "as request attribute" (see the exception in the question)
       model.addAttribute("item", new Item());
       return "item/addItem";
   }
</code>```

add the name of the form backing object to the form:form tag in the addItem.jsp like this:

<form:form modelAttribute="item">

To understand what is happening in the step 2., read the explanation below:

If we run the app after step 1, normally we should still get the same exception:
IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute

(It is possible, that after adding an entity named 'command' to the code in the question above, it starts to work, because the commandName="command" works the same way as the modelAttribute="command" - see explanation below.)

What is this - bean named 'command'? Read the docs or the excerpt:

...docs.spring.io/spring/docs/current/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag

...

```<code><form:form>
  ...
</form:form>
</code>```

... The preceding JSP assumes that the variable name of the form backing object is 'command'.
If you have put the form backing object into the model under another name (definitely a best practice),
then you can bind the form to the named variable like so:

<form:form modelAttribute="user">

...

This means:

A: a form:form will try to find a form backing object named 'command' in the model, even if it is not explicitly writen in the form:form tag

<form:form> really means <form:form  modelAttribute="command">

In this case, the form will not work if the form backing object/entity named 'command' is not available in the model.

B: When sending the form backing object/bean/entity to the form (packaged in the model), we must either:

name it 'command'

or - (definitely a best practice) -

name it whatewer we want, like in the sample code above model.addAttribute("item", new Item()); but then we must explicitly write the name of the form backing object in the form:form tag like this:

<form:form modelAttribute="item">

The reason for the "Neither BindingResult nor plain target object..." exception may be:

we did not put our form backing object named 'command' into the model in the controller method that shows the form

we did not name our form backing object 'command' when we put it into the model and we did not tell the form to look in the model for the form backing object named 'item', 'user', or whatever 'myFormBackingObjectName' we used, when we put the form backing object/bean/entity into the model.

That happens in the step 2:

add the name of our form backing object to the form:form tag like this:

<form:form modelAttribute="myFormBackingObjectName">

This means, tell the form, what name we used for our entity/form backing object.

Your index.jsp is probably not being returned by a method in the controller. At least, the code is not showing it. But that alone would still not be enough, that method would also have to make available a form backing object/entity, named 'command', in other words, save an object named 'command' in the model.

Since you have commandName="command" in your form:form tag (that is the older way of saying modelAttribute="command") the form is trying to find the 'command' object in the model as a request attribute. But the calling method in controller must first save this entity in the model, to make it available for the form.

If this is clear, further reading is this answer to the same question.

Body:
Hey, everyone!

I can't understand why it happens when I try to open webapp:

Neither BindingResult nor plain target object for bean name 'command' available as request attribute

and

org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 53

Here is form from index.jsp

51 <c:url var="addAction" value="/email/add.form"/>
52 <form:form action="${addAction}" commandName="command">
53    <form:input path="email" type="email" placeholder="Enter email" class="cell"/>
54    <input type="submit" class="button" value="<spring:message text="Send"/>"/>
55 </form:form>

Here is Controller

@Controller
public class EmailController {
    private EmailService emailService;

    @Autowired
    @Qualifier("emailService")
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }

    @RequestMapping(value = "/email/add", method = RequestMethod.POST)
    public String addEmail(@ModelAttribute("email") EmailEntity emailEntity) {
        this.emailService.addEmail(emailEntity);
        return "redirect:/email.form";
    }
}

The following is Stacktrace and Root Cause

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
    org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
    org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
    org.apache.jsp.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:323)
    org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:271)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:184)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Sorry, if something has been missed.
Thanks!

Body:
Why does this happen?

The complete answer is here. This is just my easier explanation for Spring beginners.

The short answer is, that the Spring form does not work without a "form backing object" or "command object", as it is also called in the Spring docs.

The index.jsp should be returned by a controller method, that makes a "bean name 'command' available to the form as request attribute" as stated in the exception.

--- Long answer ---

The Spring form documentation reads:

"...form:form tag renders an HTML 'form' tag and exposes a binding path to inner tags for binding. It puts the command object in the PageContext
so that the command object can be accessed by inner tags..."

This means, that the inner tags (like form:input) need a 'command object' because they want to bind to it.

So, what is this "command object" (also known as the form backing object) and where does it come from?

Read this a couple of times:

The form backing object is the bean/entity that the form is dealing with - like for example the form addItem.jsp is dealing with an entity "Item". The entity/command object comes from the the method in the form controller which returns the form.

The form backing object/bean/entity is going to have its properties set in the form, but it needs to be available already when we show the empty form.

We will solve our problem in two steps:

add the form backing object to the model in controller method that shows the form, to make it accessible for the form - (for example) addItem.jsp

   @RequestMapping("/add-item")
   public String showAddItemForm(Model model) {
       // adding the form backing object/entity - here for example named item
       // to the model "as request attribute" (see the exception in the question)
       model.addAttribute("item", new Item());
       return "item/addItem";
   }

add the name of the form backing object to the form:form tag in the addItem.jsp like this:

<form:form modelAttribute="item">

To understand what is happening in the step 2., read the explanation below:

If we run the app after step 1, normally we should still get the same exception:
IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute

(It is possible, that after adding an entity named 'command' to the code in the question above, it starts to work, because the commandName="command" works the same way as the modelAttribute="command" - see explanation below.)

What is this - bean named 'command'? Read the docs or the excerpt:

...docs.spring.io/spring/docs/current/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag

...

<form:form>
  ...
</form:form>

... The preceding JSP assumes that the variable name of the form backing object is 'command'.
If you have put the form backing object into the model under another name (definitely a best practice),
then you can bind the form to the named variable like so:

<form:form modelAttribute="user">

...

This means:

A: a form:form will try to find a form backing object named 'command' in the model, even if it is not explicitly writen in the form:form tag

<form:form> really means <form:form  modelAttribute="command">

In this case, the form will not work if the form backing object/entity named 'command' is not available in the model.

B: When sending the form backing object/bean/entity to the form (packaged in the model), we must either:

name it 'command'

or - (definitely a best practice) -

name it whatewer we want, like in the sample code above model.addAttribute("item", new Item()); but then we must explicitly write the name of the form backing object in the form:form tag like this:

<form:form modelAttribute="item">

The reason for the "Neither BindingResult nor plain target object..." exception may be:

we did not put our form backing object named 'command' into the model in the controller method that shows the form

we did not name our form backing object 'command' when we put it into the model and we did not tell the form to look in the model for the form backing object named 'item', 'user', or whatever 'myFormBackingObjectName' we used, when we put the form backing object/bean/entity into the model.

That happens in the step 2:

add the name of our form backing object to the form:form tag like this:

<form:form modelAttribute="myFormBackingObjectName">

This means, tell the form, what name we used for our entity/form backing object.

Your index.jsp is probably not being returned by a method in the controller. At least, the code is not showing it. But that alone would still not be enough, that method would also have to make available a form backing object/entity, named 'command', in other words, save an object named 'command' in the model.

Since you have commandName="command" in your form:form tag (that is the older way of saying modelAttribute="command") the form is trying to find the 'command' object in the model as a request attribute. But the calling method in controller must first save this entity in the model, to make it available for the form.

If this is clear, further reading is this answer to the same question.


问:
How to count the length of a tuple in Haskell?
I tried searching in web and stackexchange, but surprisingly no one asked how to calculate length of a tuple in Haskell in the form below.

So suppose you have tuple like (1,2,3,4) or (1,3,5,6,7) in Haskell and wish to write the length function that calculates length of a tuple. How can I do this? For list I know how I will be able to do so using recursion without explicitly invoking built-in functions. But tuple is different, and I can't use "head"-"tail" distinction.

Will the method involve creating a new data type?

答:
One possible answer (using just the base library) is

```<code>import Data.Data
import Data.Functor.Const

length :: Data a => a -> Int
length =
  getConst .
  gfoldl (\(Const c) _ -> Const (c+1)) (const 0)
</code>```

I gave a whole talk on this subject at London Haskell recently. The slides are here, but the video has not been published yet.

Body:
One possible answer (using just the base library) is

import Data.Data
import Data.Functor.Const

length :: Data a => a -> Int
length =
  getConst .
  gfoldl (\(Const c) _ -> Const (c+1)) (const 0)

I gave a whole talk on this subject at London Haskell recently. The slides are here, but the video has not been published yet.


问:
How to loop through one table and then Insert into another based on multiple IF ELSE
I have a table like below with 2 columns. This table already is populated with all the data I need.

Table 1

```<code>ID (int)    TYPE  (string)
</code>```

The other table looks like this and it's empty

Table 2

```<code>ID (int)     Somedetail (int)
</code>```

I need to loop through Table 1 and then insert into Table 2 if TYPE = 'string'
for each row and I have about 5 different string I need to test against.

INSERT WILL BE insert into Table 2 (ID, int). I will provide the int value based on if TYPE = 'string' matches or not.

This is what I have currently.

SELECT ID, TYPE

FROM TABLE1

IF(ID = 'STRING1')

INSERT INTO TABLE2...

ELSE IF (ID = 'STRING2')

INSERT INTO

and so on

答:
You are basically looking for an INSERT INTO SELECT statement (https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql). In your case this would take the form:

```<code>INSERT INTO Table2
SELECT
    id,
    CASE
        WHEN type = 'string1' THEN intvalue1
        WHEN type = 'string2' THEN intvalue2
        WHEN type = 'string3' THEN intvalue3
        WHEN type = 'string4' THEN intvalue4
        WHEN type = 'string5' THEN intvalue5
        END
FROM Table1
WHERE type IN ('string1', 'string2', 'string3', 'string4', 'string5');
</code>```

Where we just take the results of that SELECT statement and shove it into Table2 with the INSERT INTO.

Body:
I have a table like below with 2 columns. This table already is populated with all the data I need.

Table 1

ID (int)    TYPE  (string)

The other table looks like this and it's empty

Table 2

ID (int)     Somedetail (int)

I need to loop through Table 1 and then insert into Table 2 if TYPE = 'string'
for each row and I have about 5 different string I need to test against.

INSERT WILL BE insert into Table 2 (ID, int). I will provide the int value based on if TYPE = 'string' matches or not.

This is what I have currently.

SELECT ID, TYPE

FROM TABLE1

IF(ID = 'STRING1')

INSERT INTO TABLE2...

ELSE IF (ID = 'STRING2')

INSERT INTO

and so on

Body:
You are basically looking for an INSERT INTO SELECT statement (https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql). In your case this would take the form:

INSERT INTO Table2
SELECT
    id,
    CASE
        WHEN type = 'string1' THEN intvalue1
        WHEN type = 'string2' THEN intvalue2
        WHEN type = 'string3' THEN intvalue3
        WHEN type = 'string4' THEN intvalue4
        WHEN type = 'string5' THEN intvalue5
        END
FROM Table1
WHERE type IN ('string1', 'string2', 'string3', 'string4', 'string5');

Where we just take the results of that SELECT statement and shove it into Table2 with the INSERT INTO.


问:
In the context of git (and diff), what is a "hunk"
I was looking for a definition of "hunk" while reading some git documentation.

I know it means a description of the difference between two files and that it has a well defined format, but I couldn't call to mind a succinct definition.

I tried searching with google, but there were a lot of somewhat spurious hits.

答:
The term "hunk" is indeed not specific to Git, and comes from the Gnu diffutil format. Even more succinctly:

Each hunk shows one area where the files differ.

But the challenge for Git is to determine the right boundaries for a hunk.

The rest of the answer helps illustrates what a hunk looks like in Git:

After various heuristics (like the compaction one, which is gone in Git 2.12), Git maintainers settled on the indent one, which was introduced in Sept. 2016 with Git 2.11, commit 433860f.

Some groups of added/deleted lines in diffs can be slid up or down,
because lines at the edges of the group are not unique. Picking good shifts for such groups is not a matter of correctness but definitely has a big effect on aesthetics.
For example, consider the following two diffs.
The first is what standard Git emits:

```<code>--- a/9c572b21dd090a1e5c5bb397053bf8043ffe7fb4:git-send-email.perl
+++ b/6dcfa306f2b67b733a7eb2d7ded1bc9987809edb:git-send-email.perl
@@ -231,6 +231,9 @@ if (!defined $initial_reply_to && $prompting) {
 }

 if (!$smtp_server) {
+       $smtp_server = $repo->config('sendemail.smtpserver');
+}
+if (!$smtp_server) {
        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
                if (-x $_) {
                        $smtp_server = $_;

</code>```

The following diff is equivalent, but is obviously preferable from an
aesthetic point of view:

```<code>--- a/9c572b21dd090a1e5c5bb397053bf8043ffe7fb4:git-send-email.perl
+++ b/6dcfa306f2b67b733a7eb2d7ded1bc9987809edb:git-send-email.perl
@@ -230,6 +230,9 @@ if (!defined $initial_reply_to && $prompting) {
        $initial_reply_to =~ s/(^\s+|\s+$)//g;
 }

+if (!$smtp_server) {
+       $smtp_server = $repo->config('sendemail.smtpserver');
+}
 if (!$smtp_server) {
        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
                if (-x $_) {
</code>```

This patch teaches Git to pick better positions for such "diff sliders" using heuristics that take the positions of nearby blank lines and the indentation of nearby lines into account.

With Git 2.14 (Q3 2017), that indent heuristic will be the default!

See commit 1fa8a66 (08 May 2017) by Jeff King (peff).

See commit 33de716 (08 May 2017) by Stefan Beller (stefanbeller).

See commit 37590ce, commit cf5e772 (08 May 2017) by Marc Branchaud.

(Merged by Junio C Hamano -- gitster -- in commit 53083f8, 05 Jun 2017)

diff: enable indent heuristic by default

The feature was included in v2.11 (released 2016-11-29) and we got no negative feedback. Quite the opposite, all feedback we got was positive.

Turn it on by default. Users who dislike the feature can turn it off
by setting diff.indentHeuristic.

With Git 2.24 (Q4 2019), the "indent heuristics" that decides where to split
diff hunks has seen its documentation corrected.

See commit 64e5e1f (15 Aug 2019) by SZEDER Gábor (szeder).

(Merged by Junio C Hamano -- gitster -- in commit e115170, 09 Sep 2019)

diff: 'diff.indentHeuristic' is no longer experimental

The indent heuristic started out as experimental, but it's now our
default diff heuristic since 33de716 (diff: enable indent heuristic
by default, 2017-05-08, Git v2.14.0-rc0).

Alas, that commit didn't update the documentation, and the description of the 'diff.indentHeuristic' configuration variable still implies that it's experimental and not the default.

Update the description of 'diff.indentHeuristic' to make it clear that it's the default diff heuristic.

The description of the related '--indent-heuristic' option has already
been updated in this answer.

The documentation will now read:

diff.indentHeuristic:

Set this option to false to disable the default heuristics that shift diff hunk boundaries to make patches easier to read.

With Git 2.25 (Q1 2020), you don't even have to specify --indent-heuristic anymore (since it is the default for quite some times now).

See commit 44ae131 (28 Oct 2019) by SZEDER Gábor (szeder).

(Merged by Junio C Hamano -- gitster -- in commit 532d983, 01 Dec 2019)

builtin/blame.c: remove '--indent-heuristic' from usage string

Signed-off-by: SZEDER Gábor

The indent heuristic is our default diff heuristic since 33de716387 ("diff: enable indent heuristic by default", 2017-05-08, Git v2.14.0-rc0 -- merge listed in batch #7), but the usage string of 'git blame' still mentions it as "experimental heuristic".

We could simply update the short help associated with the option, but according to the comment above the option's declaration it was "only included here to get included in the "-h" output".

That made sense while the feature was still experimental and we wanted to give it more exposure, but nowadays it's unnecessary.

So let's rather remove the '--indent-heuristic' option from 'git blame's usage string.

Note that 'git blame' will still accept this option, as it is parsed in parse_revision_opt().

Astute readers may notice that this patch removes a comment mentioning "the following two options", but it only removes one option.

The reason is that the comment is outdated: that other options was '--compaction-heuristic', and it has already been removed in 3cde4e02ee (diff: retire "compaction" heuristics, 2016-12-23), but that commit forgot to update this comment.

Body:
The term "hunk" is indeed not specific to Git, and comes from the Gnu diffutil format. Even more succinctly:

Each hunk shows one area where the files differ.

But the challenge for Git is to determine the right boundaries for a hunk.

The rest of the answer helps illustrates what a hunk looks like in Git:

After various heuristics (like the compaction one, which is gone in Git 2.12), Git maintainers settled on the indent one, which was introduced in Sept. 2016 with Git 2.11, commit 433860f.

Some groups of added/deleted lines in diffs can be slid up or down,
because lines at the edges of the group are not unique. Picking good shifts for such groups is not a matter of correctness but definitely has a big effect on aesthetics.
For example, consider the following two diffs.
The first is what standard Git emits:

--- a/9c572b21dd090a1e5c5bb397053bf8043ffe7fb4:git-send-email.perl
+++ b/6dcfa306f2b67b733a7eb2d7ded1bc9987809edb:git-send-email.perl
@@ -231,6 +231,9 @@ if (!defined $initial_reply_to && $prompting) {
 }

 if (!$smtp_server) {
+       $smtp_server = $repo->config('sendemail.smtpserver');
+}
+if (!$smtp_server) {
        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
                if (-x $_) {
                        $smtp_server = $_;

The following diff is equivalent, but is obviously preferable from an
aesthetic point of view:

--- a/9c572b21dd090a1e5c5bb397053bf8043ffe7fb4:git-send-email.perl
+++ b/6dcfa306f2b67b733a7eb2d7ded1bc9987809edb:git-send-email.perl
@@ -230,6 +230,9 @@ if (!defined $initial_reply_to && $prompting) {
        $initial_reply_to =~ s/(^\s+|\s+$)//g;
 }

+if (!$smtp_server) {
+       $smtp_server = $repo->config('sendemail.smtpserver');
+}
 if (!$smtp_server) {
        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
                if (-x $_) {

This patch teaches Git to pick better positions for such "diff sliders" using heuristics that take the positions of nearby blank lines and the indentation of nearby lines into account.

With Git 2.14 (Q3 2017), that indent heuristic will be the default!

See commit 1fa8a66 (08 May 2017) by Jeff King (peff).

See commit 33de716 (08 May 2017) by Stefan Beller (stefanbeller).

See commit 37590ce, commit cf5e772 (08 May 2017) by Marc Branchaud.

(Merged by Junio C Hamano -- gitster -- in commit 53083f8, 05 Jun 2017)

diff: enable indent heuristic by default

The feature was included in v2.11 (released 2016-11-29) and we got no negative feedback. Quite the opposite, all feedback we got was positive.

Turn it on by default. Users who dislike the feature can turn it off
by setting diff.indentHeuristic.

With Git 2.24 (Q4 2019), the "indent heuristics" that decides where to split
diff hunks has seen its documentation corrected.

See commit 64e5e1f (15 Aug 2019) by SZEDER Gábor (szeder).

(Merged by Junio C Hamano -- gitster -- in commit e115170, 09 Sep 2019)

diff: 'diff.indentHeuristic' is no longer experimental

The indent heuristic started out as experimental, but it's now our
default diff heuristic since 33de716 (diff: enable indent heuristic
by default, 2017-05-08, Git v2.14.0-rc0).

Alas, that commit didn't update the documentation, and the description of the 'diff.indentHeuristic' configuration variable still implies that it's experimental and not the default.

Update the description of 'diff.indentHeuristic' to make it clear that it's the default diff heuristic.

The description of the related '--indent-heuristic' option has already
been updated in this answer.

The documentation will now read:

diff.indentHeuristic:

Set this option to false to disable the default heuristics that shift diff hunk boundaries to make patches easier to read.

With Git 2.25 (Q1 2020), you don't even have to specify --indent-heuristic anymore (since it is the default for quite some times now).

See commit 44ae131 (28 Oct 2019) by SZEDER Gábor (szeder).

(Merged by Junio C Hamano -- gitster -- in commit 532d983, 01 Dec 2019)

builtin/blame.c: remove '--indent-heuristic' from usage string

Signed-off-by: SZEDER Gábor

The indent heuristic is our default diff heuristic since 33de716387 ("diff: enable indent heuristic by default", 2017-05-08, Git v2.14.0-rc0 -- merge listed in batch #7), but the usage string of 'git blame' still mentions it as "experimental heuristic".

We could simply update the short help associated with the option, but according to the comment above the option's declaration it was "only included here to get included in the "-h" output".

That made sense while the feature was still experimental and we wanted to give it more exposure, but nowadays it's unnecessary.

So let's rather remove the '--indent-heuristic' option from 'git blame's usage string.

Note that 'git blame' will still accept this option, as it is parsed in parse_revision_opt().

Astute readers may notice that this patch removes a comment mentioning "the following two options", but it only removes one option.

The reason is that the comment is outdated: that other options was '--compaction-heuristic', and it has already been removed in 3cde4e02ee (diff: retire "compaction" heuristics, 2016-12-23), but that commit forgot to update this comment.


问:
Soft delete on a intermediate table for many-to-many relationship
How do I set soft delete on an intermediate table which is connecting two different types of entities? I've added  deleted_at column, but the docs say that I need to put this into the model:

```<code>protected $softDelete = true;
</code>```

Of course, I don't have a model for an intermediate table.
Any idea?

答:
You could also use Laravel's Eloquent BelongsToMany method updateExistingPivot.

```<code>$model->relation->updateExistingPivot($relatedId, ['deleted_at' => Carbon\Carbon::now()]);
</code>```

So to use @RonaldHulshof examples you have a User model with a groups relationship which is a belongsToMany relationship.

```<code>public function groups() {
    return $this->belongsToMany(Group::class)->whereNull('groups_users.deleted_at')->withTimestamps();
}
</code>```

Then in order to soft delete the pivot table entry you would do the following.

```<code>$user->groups()->updateExistingPivot($groupId, ['deleted_at' => Carbon\Carbon::now()]);
</code>```

Body:
How do I set soft delete on an intermediate table which is connecting two different types of entities? I've added  deleted_at column, but the docs say that I need to put this into the model:

protected $softDelete = true;

Of course, I don't have a model for an intermediate table.
Any idea?

Body:
You could also use Laravel's Eloquent BelongsToMany method updateExistingPivot.

$model->relation->updateExistingPivot($relatedId, ['deleted_at' => Carbon\Carbon::now()]);

So to use @RonaldHulshof examples you have a User model with a groups relationship which is a belongsToMany relationship.

public function groups() {
    return $this->belongsToMany(Group::class)->whereNull('groups_users.deleted_at')->withTimestamps();
}

Then in order to soft delete the pivot table entry you would do the following.

$user->groups()->updateExistingPivot($groupId, ['deleted_at' => Carbon\Carbon::now()]);


问:
Write a loop for my function in r
I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

```<code>z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$rx[i], 2))
}
</code>```

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i],  :
        invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

答:
I am not super familiar with R, but it appears you are trying to increase the index of rx. Is rx a vector with values at different indices?
If not the solution my be to concatenate a string

```<code>for (i in 1:30){
varName <-- "rx"+i
dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$varName, 2))
}
</code>```

Again, I may be way off here, as this if my first post and R is still pretty new to me.

Title: Write a loop for my function in r

Body:
I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$rx[i], 2))
}

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i],  :
        invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

Body:
I am not super familiar with R, but it appears you are trying to increase the index of rx. Is rx a vector with values at different indices?
If not the solution my be to concatenate a string

for (i in 1:30){
varName <-- "rx"+i
dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$varName, 2))
}

Again, I may be way off here, as this if my first post and R is still pretty new to me.


问:
Instagram API - Fetching list of followers for my account
I am making a widget for my iPhone to fetch data about my Instagram followers. I won't be putting it on the App Store, and I won't be fetching any other users' data.

Can I do this? I have tried to figure out what to do but I think I have to register my website, even though I'm not making a website and this won't be shared with anyone else.

答:
As stated in Instagram Developer Documentation, you will have to register your application before using the API.

1. Register

We'll assign an OAuth client_id and client_secret for each of your
  applications.

2. Authenticate

Ask users to authenticate and authorize your application with
  Instagram.

3. Start making requests!

Make requests to our API Endpoints with the users' OAuth credentials.

The takeaway here is that you'll need the OAuth credentials to access the API.


问:
How to pass only Error messages from Model to Controller (Mongoose)?
I'm building my node.js api and want to pass on the callback only messages about errors. Now I need to have a deal with object like this

```<code>{
    "success": false,
    "msg": {
        "errors": {
            "email": {
                "message": "test@tes is not a valid email!",
                "name": "ValidatorError",
                "properties": {
                    "type": "user defined",
                    "message": "{VALUE} is not a valid email!",
                    "path": "email",
                    "value": "test@tes"
                },
                "kind": "user defined",
                "path": "email",
                "value": "test@tes"
            },
            "username": {
                "message": "The Username is not long enough",
                "name": "ValidatorError",
                "properties": {
                    "type": "user defined",
                    "message": "The Username is not long enough",
                    "path": "username",
                    "value": "te"
                },
                "kind": "user defined",
                "path": "username",
                "value": "te"
            }
        },
        "_message": "Users validation failed",
        "name": "ValidationError"
    }
}
</code>```

Here is my code
userModel.js

```<code>/* Custom Validation */
const validator = (v)=> {
    return v.length > 5;
};
/* END of Custom Validation */

const UserSchema = new Schema({
        username: {
            type: String,
            validate: [
                validator,
                'The Username is not long enough'
            ],
            required: [true, 'The Username is required'],
            unique: true,
            lowercase: true
        },
        password: {
            type: String,
            required: [true, 'The Password is required']
        },
        email: {
            type: String,
            validate: [
                (v)=> { return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(v)},
                '{VALUE} is not a valid email!'
            ],
            lowercase: true,
            required: true
        },
        role: {
            type: [{
                type: String,
                enum: ['user', 'manager', 'admin']
            }],
            default: ['user']
        },
        team: {
            type: [{
                type: String,
                enum: ['IHLO', 'ADULT&SH', 'IPJ', 'ISD', '']
            }],
            default: ['']
        },
        created_date: {
            type: Date,
            default: Date.now
        },

    });

    UserSchema.pre('save', ...

    UserSchema.methods.comparePassword = ...

    module.exports = mongoose.model('Users', UserSchema);
**userController.js**

    / Register new user
    exports.signup = (req, res)=> {

        let new_user = new User(req.body);
        new_user.save((err, new_user)=> {
            if (err)
                return res.json({success: false, msg: err});
            res.json({success: true, msg: `Successful created new user ${new_user.username}.`});
        });
    };
</code>```

Of course I can make a function on the frontend that search for 'message' keys but for some records it could be more than 100 errors. Is it anyway how I can do it and do not pass the redundancy data?

答:
You could simply parse the error object before sending it to the frontend.

Here's how you could do it with a loop.

```<code>if (err){
    let messages = [];
    for(let i in err){
        messages.push({
            field: i,
            message: err[i].message
        });
    }

    return res.json({success: false, msg: messages});
}
</code>```

You could also use a library like lodash to make it a bit cleaner.

```<code>if (err){
    let messages = _.flatMap(err, (value, key) => { field: key, message: value.message });
    return res.json({success: false, msg: messages});
}
</code>```

Body:
I'm building my node.js api and want to pass on the callback only messages about errors. Now I need to have a deal with object like this

{
    "success": false,
    "msg": {
        "errors": {
            "email": {
                "message": "test@tes is not a valid email!",
                "name": "ValidatorError",
                "properties": {
                    "type": "user defined",
                    "message": "{VALUE} is not a valid email!",
                    "path": "email",
                    "value": "test@tes"
                },
                "kind": "user defined",
                "path": "email",
                "value": "test@tes"
            },
            "username": {
                "message": "The Username is not long enough",
                "name": "ValidatorError",
                "properties": {
                    "type": "user defined",
                    "message": "The Username is not long enough",
                    "path": "username",
                    "value": "te"
                },
                "kind": "user defined",
                "path": "username",
                "value": "te"
            }
        },
        "_message": "Users validation failed",
        "name": "ValidationError"
    }
}

Here is my code
userModel.js

/* Custom Validation */
const validator = (v)=> {
    return v.length > 5;
};
/* END of Custom Validation */

const UserSchema = new Schema({
        username: {
            type: String,
            validate: [
                validator,
                'The Username is not long enough'
            ],
            required: [true, 'The Username is required'],
            unique: true,
            lowercase: true
        },
        password: {
            type: String,
            required: [true, 'The Password is required']
        },
        email: {
            type: String,
            validate: [
                (v)=> { return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(v)},
                '{VALUE} is not a valid email!'
            ],
            lowercase: true,
            required: true
        },
        role: {
            type: [{
                type: String,
                enum: ['user', 'manager', 'admin']
            }],
            default: ['user']
        },
        team: {
            type: [{
                type: String,
                enum: ['IHLO', 'ADULT&SH', 'IPJ', 'ISD', '']
            }],
            default: ['']
        },
        created_date: {
            type: Date,
            default: Date.now
        },

    });

    UserSchema.pre('save', ...

    UserSchema.methods.comparePassword = ...

    module.exports = mongoose.model('Users', UserSchema);
**userController.js**

    / Register new user
    exports.signup = (req, res)=> {

        let new_user = new User(req.body);
        new_user.save((err, new_user)=> {
            if (err)
                return res.json({success: false, msg: err});
            res.json({success: true, msg: `Successful created new user ${new_user.username}.`});
        });
    };

Of course I can make a function on the frontend that search for 'message' keys but for some records it could be more than 100 errors. Is it anyway how I can do it and do not pass the redundancy data?

Body:
You could simply parse the error object before sending it to the frontend.

Here's how you could do it with a loop.

if (err){
    let messages = [];
    for(let i in err){
        messages.push({
            field: i,
            message: err[i].message
        });
    }

    return res.json({success: false, msg: messages});
}

You could also use a library like lodash to make it a bit cleaner.

if (err){
    let messages = _.flatMap(err, (value, key) => { field: key, message: value.message });
    return res.json({success: false, msg: messages});
}


问:
Printing HTML without forced page breaks
I am trying to print HTML with lots of big blockquote elements spanning half a page each or more. When printing, the browser adds a page break in cases where the blockquote element will not finish within the current page.

I've tried this on several browsers and same thing. How would one program the CSS to display the blockquotes even if they will be cut in the middle at the end of the current page?

for example:

```<code>text-text text-text text-text text-text
text-text text-text text-text text-text
<blockquote>
text-text text-text text-text
text-text text-text text-text
</blockquote>
</code>```

Browsers will add a page break before the "blockquote" element if its contents will not finish by the end of the current page.

How would one prevent this?

I've fiddled with CSS properties page-break-before/inside/after but that did not help.

答:
I believe you want one or both of these page-break rules:

```<code>blockquote {
  display: block;

  page-break-before: avoid;
  page-break-inside: auto;
}
</code>```

...or possibly the preceding element needs page-break-after: avoid.

(You can also use the more recently-introduced properties break-before, break-after, and break-inside -- but browser support for these is still, as of 2023, not complete.)

Per comments below, the element must have display:  block for this to work; display: inline-block doesn't trigger the page break behavior.

Body:
I am trying to print HTML with lots of big blockquote elements spanning half a page each or more. When printing, the browser adds a page break in cases where the blockquote element will not finish within the current page.

I've tried this on several browsers and same thing. How would one program the CSS to display the blockquotes even if they will be cut in the middle at the end of the current page?

for example:

text-text text-text text-text text-text
text-text text-text text-text text-text

text-text text-text text-text
text-text text-text text-text

Browsers will add a page break before the "blockquote" element if its contents will not finish by the end of the current page.

How would one prevent this?

I've fiddled with CSS properties page-break-before/inside/after but that did not help.

Body:
I believe you want one or both of these page-break rules:

blockquote {
  display: block;

  page-break-before: avoid;
  page-break-inside: auto;
}

...or possibly the preceding element needs page-break-after: avoid.

(You can also use the more recently-introduced properties break-before, break-after, and break-inside -- but browser support for these is still, as of 2023, not complete.)

Per comments below, the element must have display:  block for this to work; display: inline-block doesn't trigger the page break behavior.


问:
Google campaign for cordova
I want to track the installation source of an app developed using cordova.

Im using this plugin https://github.com/danwilson/google-analytics-plugin/

In the deviceReady callback there is this piece of code:

```<code> window.ga.startTrackerWithId('UA-xxxxxxxx-y', 30)
                  .then(function(){
                      console.log('Google analytics is ready now');
                      //the component is ready and you can call any method here
                      GoogleAnalytics.debugMode();
                      GoogleAnalytics.setAllowIDFACollection(true);
                  })
                .catch(e => console.log('Error starting GoogleAnalytics', e));
</code>```

also in here is the application tag content in the AndroidManifest.xml :

```<code><receiver android:name="cordova.plugins.Diagnostic$LocationProviderChangedReceiver">
        <intent-filter>
            <action android:name="android.location.PROVIDERS_CHANGED" />
        </intent-filter>
    </receiver>
    <receiver android:enabled="true" android:exported="true" android:name="com.google.android.gms.analytics.CampaignTrackingReceiver">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.CampaignTrackingService" />
    <receiver android:enabled="true" android:name="com.google.android.gms.analytics.AnalyticsReceiver">
        <intent-filter>
            <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.AnalyticsService" />
</code>```

After following the google guide and testing using this link I get the Broadcast completed: result=0, so everything is supposed to be ok.

Also in this SO post its said that "the author added an undocumented functionality for campaigns, and it works without any modification. It add the tags in the manifest and it works when a campaign link is launched to Google Play." means everything is done automatically, but IT IS NOT !

Am I missing something in this process, OR is there a way the get the url in the deviceReady callback and just use something like window.ga.trackView('Screen Title', 'my-scheme://content/1111?utm_source=google&utm_campaign=my-campaign') ???

Thank you.

答:
I finally found it,

The whole plugin was working fine, but to make the google campaign work I needed to install "Google Play Services SDK" on the building machine. The rest is done under the hood.

Title: Google campaign for cordova

Body:
I want to track the installation source of an app developed using cordova.

Im using this plugin https://github.com/danwilson/google-analytics-plugin/

In the deviceReady callback there is this piece of code:

 window.ga.startTrackerWithId('UA-xxxxxxxx-y', 30)
                  .then(function(){
                      console.log('Google analytics is ready now');
                      //the component is ready and you can call any method here
                      GoogleAnalytics.debugMode();
                      GoogleAnalytics.setAllowIDFACollection(true);
                  })
                .catch(e => console.log('Error starting GoogleAnalytics', e));

also in here is the application tag content in the AndroidManifest.xml :

<receiver android:name="cordova.plugins.Diagnostic$LocationProviderChangedReceiver">
        <intent-filter>
            <action android:name="android.location.PROVIDERS_CHANGED" />
        </intent-filter>
    </receiver>
    <receiver android:enabled="true" android:exported="true" android:name="com.google.android.gms.analytics.CampaignTrackingReceiver">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.CampaignTrackingService" />
    <receiver android:enabled="true" android:name="com.google.android.gms.analytics.AnalyticsReceiver">
        <intent-filter>
            <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:exported="false" android:name="com.google.android.gms.analytics.AnalyticsService" />

After following the google guide and testing using this link I get the Broadcast completed: result=0, so everything is supposed to be ok.

Also in this SO post its said that "the author added an undocumented functionality for campaigns, and it works without any modification. It add the tags in the manifest and it works when a campaign link is launched to Google Play." means everything is done automatically, but IT IS NOT !

Am I missing something in this process, OR is there a way the get the url in the deviceReady callback and just use something like window.ga.trackView('Screen Title', 'my-scheme://content/1111?utm_source=google&utm_campaign=my-campaign') ???

Thank you.


问:
Xcode can only refactor C and Objective-C code. How to rename swift class name in Xcode 6?
I have created a new Single View Application Project in Xcode 6 beta version. I want to rename swift class from ViewController.swift to some other name. But when I select Refactor -> Rename, it gives error Xcode can only refactor C and Objective-C code.

Any idea how to rename swift class in Xcode 6?

UPDATE:

Finally Xcode 9 is supporting Refactoring for Swift. It took Apple 3 years to add this basic feature. Refactoring

答:
Xcode 9

Xcode 9 now supports renaming in Swift. This was announced in WWDC 2017.


答:
Fairly positive you want to use CASE based on your comments.  You'll have to fill in the strings and the ints that you want, but here is the shell:

```<code>INSERT INTO Table2 (ID, Somedetail)
SELECT ID,
       CASE WHEN Type = 'string1' THEN 1,
            WHEN Type = 'string2' THEN 2,
            etc...
       END as Somedetail
FROM Table1
</code>```

Title: How to loop through one table and then Insert into another based on multiple IF ELSE

Body:
Fairly positive you want to use CASE based on your comments.  You'll have to fill in the strings and the ints that you want, but here is the shell:

INSERT INTO Table2 (ID, Somedetail)
SELECT ID,
       CASE WHEN Type = 'string1' THEN 1,
            WHEN Type = 'string2' THEN 2,
            etc...
       END as Somedetail
FROM Table1