问:
Trim Java String and use in Sql Where Clause
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

```<code>String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}
</code>```

Result Query:

```<code>SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);
</code>```

I want to get rid of the last comma after 'Broken'

答:
Need to update your for loop where you need to append element from array till its second last element and append last element of the array outside the loop.

```<code>for(int i=0;i<stat.length-1;i++){  // loop till second last element
sb.append("'"+stat[i]+"',"); //appends , at end
}
sb.append("'"+stat[stat.length-1]+"'"); // append last element
</code>```

Body:
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}

Result Query:

SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);

I want to get rid of the last comma after 'Broken'

Body:
Need to update your for loop where you need to append element from array till its second last element and append last element of the array outside the loop.

for(int i=0;i<stat.length-1;i++){  // loop till second last element
sb.append("'"+stat[i]+"',"); //appends , at end
}
sb.append("'"+stat[stat.length-1]+"'"); // append last element


来源: stackexchange

问:
POST to PHP file doesn't work in Fiddler
I have this very basic PHP file uploaded to www.example.com (not local):

```<code><?php
header('Access-Control-Allow-Origin: *');
echo $_POST['var1'];
?>
</code>```

I composed a simple test in Fiddler as below

I got blank result, nothing back. It supposed to give me test1234 in TextView

I tested with simple $.ajax call and it works in the browser. I also uploaded to another domain name to test cross domain call, it works too.

```<code>$.ajax({
    type: "POST",
    url: "http://www.example.com/test.php",
    data: {var1: "test1234"}
}).done(function(msg) {
    console.log(msg);
});
</code>```

However, if I swapped everything to GET (php, Fiddler), it works. So why I can't get Fiddler to pass POST params?

答:
Even though there's already a very short answer in the comments, I just had the same problem and wanted to provide a slightly longer solution/explanation, because at first glance I didn't get the difference:

Your problem is that PHP's $_GET and $_POST don't map to HTTP's GET and POST:

$_GET gets variables passed via the URL parameters

$_POST gets variables passed via the body of the request message, when the content type is application/x-www-form-urlencoded or multipart/form-data

...no matter whether the request was made via HTTP GET or POST!

Your $.ajax test worked because you passed the value via the request body.

Your Fiddler test didn't work because you passed the value via URL parameter.

So there are two possible solutions for Fiddler:

Pass parameter via URL, get value in PHP via $_GET['id']:

Pass parameter via "Request Body", use one of the content types mentioned above, get value in PHP via $_POST['id']:

ContentLicense: CC BY-SA 3.0

Body:
I have this very basic PHP file uploaded to www.example.com (not local):

<?php
header('Access-Control-Allow-Origin: *');
echo $_POST['var1'];
?>

I composed a simple test in Fiddler as below

I got blank result, nothing back. It supposed to give me test1234 in TextView

I tested with simple $.ajax call and it works in the browser. I also uploaded to another domain name to test cross domain call, it works too.

$.ajax({
    type: "POST",
    url: "http://www.example.com/test.php",
    data: {var1: "test1234"}
}).done(function(msg) {
    console.log(msg);
});

However, if I swapped everything to GET (php, Fiddler), it works. So why I can't get Fiddler to pass POST params?


问:
Javascript string object to array
I want to pass some data from html to jquery using data-attribute like this:

```<code><div data-frames="[
    { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
    { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
    { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
    { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
    { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
    { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' }
]"></div>
</code>```

I don't know a way how could I use this structure in jquery so it keeps the same format (array with objects). Is there a way to do this?

Using string.split(',') doesn't help me here.

答:
JavaScript is a better tool for storing complex data versus HTML. I'd change your solution so that your element contains a reference to a data structure in your JavaScript instead of the raw data itself:

var data = {
    someUniqueKey: [
        { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
        { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
        { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
        { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
        { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
        { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' }
    ]
};

$('div[data-frames]').each(function(i, el) {
    var key = $(el).data('frames');

    console.log(data[key]);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-frames="someUniqueKey"></div></code>```

Title: Javascript string object to array

Body:
I want to pass some data from html to jquery using data-attribute like this:

I don't know a way how could I use this structure in jquery so it keeps the same format (array with objects). Is there a way to do this?

Using string.split(',') doesn't help me here.

Body:
JavaScript is a better tool for storing complex data versus HTML. I'd change your solution so that your element contains a reference to a data structure in your JavaScript instead of the raw data itself:

var data = {
    someUniqueKey: [
        { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
        { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
        { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
        { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
        { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
        { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' }
    ]
};

$('div[data-frames]').each(function(i, el) {
    var key = $(el).data('frames');

    console.log(data[key]);
});

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

<div data-frames="someUniqueKey"></div>


问:
Is there a reason why http response is different from the site and code output?
I get a http response using Python by executing the following code:

```<code>conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')

conn.request("GET", "/something/somethig")
response = conn.getresponse()
#data = response.read()
data =json.load(response)
print(data)
</code>```

The results show a list of API results.

But they are different from the one that is executed and when I manually access the westus.api.cognitive.microsoft.com/something/something website.

Can somebody tell me what is wrong here?

答:
There are a lot of things that are different between a request in a script and a request in a browser. For one, your script will not execute any associated JavaScript from the page. Second, the header of your http request includes details of the requesting client.

For example for a REST interface, a server may return the plainest JSON to an application request and return a formatted page for a browser request.

In Chrome, you can open the developer tools with "..."->"More Tools"->"Developer Tools", and with that open, you can open all of your requests and see the headers:

There is a similar function in Firefox for looking at headers. Click the hamburger->"Developer"->"Web Console". Under "Net" you can filter for requests. Click a request to see the details.

For POST commands, also look at the body of the request.

Finally, last week, I was trying to automate a POST command in Java, and I had some difficulty in doing so. A colleague was able to make the call with the curl command, and that gave me enough clues about the critical parameters. So I recommend trying curl which can help distinguish critical parameters from accidental ones, or at least to look at the problem from another angle.

Body:
I get a http response using Python by executing the following code:

conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')

conn.request("GET", "/something/somethig")
response = conn.getresponse()
#data = response.read()
data =json.load(response)
print(data)

The results show a list of API results.

But they are different from the one that is executed and when I manually access the westus.api.cognitive.microsoft.com/something/something website.

Can somebody tell me what is wrong here?


问:
division in php
```<code> $voltage = '0.4000';
                    $newValue = str_replace('0.','',$voltage);
                    echo 'newvalue'.$newValue;
                    $newValue = $voltage/0.0125;
                    echo 'newvalue'.$newValue;
</code>```

when i do like this i get 32 after division where as i should get 320000. any problem in wht i am doing ?

答:
```<code> $newValue =  $newValue/0.0125;
</code>```

ContentLicense: CC BY-SA 2.5

Title: division in php

Body:
 $voltage = '0.4000';
                    $newValue = str_replace('0.','',$voltage);
                    echo 'newvalue'.$newValue;
                    $newValue = $voltage/0.0125;
                    echo 'newvalue'.$newValue;

when i do like this i get 32 after division where as i should get 320000. any problem in wht i am doing ?

Body: $newValue =  $newValue/0.0125;


问:
How to visualize QImage in QML
I have a QAbstractListModel with custom objects as items. Each object has a QImage that is loaded from a database. I use ListView in QML to visualize it but I do not see any mean to represent QImage in the delegate. Image primitive seems to accept only URLs.

Is the only way for me to show QImages is to create a QQuickImageProvider with some custom system of a URL per element (looks like a total overkill)?

答:
I think QQuickImageProvider is the proper way.

Also, I think you can use the word 'overkill' if you know exactly how the Qt internals work. Otherwise it's just guessing.

AFAIK there is a complex caching system of images (and other data) underneath, so once an image pixmap is loaded (and doesn't change) data retrieval is immediate. So no overkill at all, since in any case at some point you need to load those QImage, but just once.

I believe a QQuickImageProvider provides pointers to the cached data, and not the whole rasterized data every time. Moreover blitting operations are nowadays performed with hardware accelerations, so it's a single operation taking a fraction of millisecond.

In other words you end up having:

give me image with url "image://xyz"

Qt looks up in the cache and returns the data pointer or performs a full load of the image if not found

the QML renderer passes the data array to OpenGL

one single blit operation (microseconds) and you have it on screen

Title: How to visualize QImage in QML


问:
memory trace of all variables in program with DBI tool
I am using intel pin as my primary DBI tool.
I am interested to know how can I trace all variables allocated in a program .

suppose, we have the following snippet in C:

```<code>int *ptr_one, *ptr_two, g;
ptr_one = (int *)malloc(sizeof(int));
ptr_two = (int *)malloc(sizeof(int));
*ptr_one = 25;
*ptr_two = 24;
g = 130;
free(ptr_two);
g = 210;
*ptr_two = 50;
</code>```

I want to know how can I trace specific variables / memory references in my program . for example on the above code, I like to trace the variable "g" in my program with Intel Pin, how it can be done?

for dynamically allocated variables, I'm monitoring malloc/free calls  & follow their addresses, but for static ones I do not have any idea .

Another matter is, for dynamically allocated variables, I like to trace them across the whole program, suppose in the above code, I want to monitor (ptr_two) variable changes and modification during my program from start to finish .

If anyone have some idea about that, it can be nice to share it here, sample codes appreciated in Intel Pin .

thank you all .

答:
Simply stated, you can't associate a name from your source code (be it variable or function name) with a memory location on the compiled binary: this information is (probably) lost on the final binary.

This is not true in two cases:

1) If your binary is exporting functions: in this case other binaries must have a means to call the function by name (minus some subtleties), in which case the information must be available somewhere; for example on Windows, binaries that export functions, variables or classes have an export table.

2) You have symbolic information: in your example, either for the global variable or other local variable, you have to use the symbolic information provided by the compiler.

On Linux you will need an external tool / library / program (e.g. libelf.so or libdwarf.so) to parse the symbolic information from the symbol tables (usually dynsym / symtab) if the binary is not stripped.

On windows you have to rely on the program database (*.pdb files); the format is mostly undocumented (although MS is trying to document it) and you have to use either the DbgHelp API  or the DIA SDK.

As stated by the PIN user guide (emphasis is mine):

Pin provides access to function names using the symbol object (SYM).
  Symbol objects only provide information about the function symbols in
  the application. Information about other types of symbols (e.g. data
  symbols), must be obtained independently by the tool.

If you have symbolic information you can then associate a variable name - obtained from an external tool - with an address (relative to the module base for global vars or a stack location for local ones). At runtime it is then just a matter of converting the relative address to a virtual one.

Body:
I am using intel pin as my primary DBI tool.
I am interested to know how can I trace all variables allocated in a program .

suppose, we have the following snippet in C:

int *ptr_one, *ptr_two, g;
ptr_one = (int *)malloc(sizeof(int));
ptr_two = (int *)malloc(sizeof(int));
*ptr_one = 25;
*ptr_two = 24;
g = 130;
free(ptr_two);
g = 210;
*ptr_two = 50;

I want to know how can I trace specific variables / memory references in my program . for example on the above code, I like to trace the variable "g" in my program with Intel Pin, how it can be done?

for dynamically allocated variables, I'm monitoring malloc/free calls  & follow their addresses, but for static ones I do not have any idea .

Another matter is, for dynamically allocated variables, I like to trace them across the whole program, suppose in the above code, I want to monitor (ptr_two) variable changes and modification during my program from start to finish .

If anyone have some idea about that, it can be nice to share it here, sample codes appreciated in Intel Pin .

thank you all .


问:
ERROR: The certificate of `raw.githubusercontent.com' is not trusted
I am trying to use wget to retrieve some file from github over a remote server (ssh), here is what I get:

```<code>$ wget  https://raw.githubusercontent.com/aseemk/seadragon-ajax/master/seadragon-min.js
--2014-11-26 09:30:14--  https://raw.githubusercontent.com/aseemk/seadragon-ajax/master/seadragon-min.js
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.31.19.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.31.19.133|:443... connected.
ERROR: The certificate of `raw.githubusercontent.com' is not trusted.
ERROR: The certificate of `raw.githubusercontent.com' hasn't got a known issuer.
</code>```

Same goes for curl:

```<code>$ curl -o bla  https://raw.githubusercontent.com/aseemk/seadragon-ajax/master/seadragon-min.js
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
</code>```

Using wget option: --no-check-certificate seems like a hack, what could I be missing ?

答:
I had this problem on raspbian, fixed it with:</p>

```<code>sudo apt-get install ssl-cert
</code>```

Body:
I am trying to use wget to retrieve some file from github over a remote server (ssh), here is what I get:

$ wget  https://raw.githubusercontent.com/aseemk/seadragon-ajax/master/seadragon-min.js
--2014-11-26 09:30:14--  https://raw.githubusercontent.com/aseemk/seadragon-ajax/master/seadragon-min.js
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.31.19.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.31.19.133|:443... connected.
ERROR: The certificate of `raw.githubusercontent.com' is not trusted.
ERROR: The certificate of `raw.githubusercontent.com' hasn't got a known issuer.

Same goes for curl:

$ curl -o bla  https://raw.githubusercontent.com/aseemk/seadragon-ajax/master/seadragon-min.js
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

Using wget option: --no-check-certificate seems like a hack, what could I be missing ?

Body:
I had this problem on raspbian, fixed it with:

sudo apt-get install ssl-cert


问:
INNER JOIN Taking longer
I am joining a sub query with a table.

Sub query runs for 5 Seconds (returns 20 records) and the table has only 4 rows.

Sub query:

```<code>Select ID, Name, JoinID
FROM tableX
JOIN ..
</code>```

Sub query Sample Result:

```<code>1, xx, 1
2, yy, 2
3, zz, 1
4, vv, 2
5, bb, 1
</code>```

TableY (ID, Description):
Data

```<code>1, test1
2, test2
3, test3
4, test4
</code>```

My below query is taking more than 30 seconds. What am I doing wrong here? I see no issue with table Stats. Also sub query is not returning any NULL record for JoinID column.

```<code>Select sub.*, tab.*
from
(
sub query
) sub
Join tableY on tableY.ID = sub.JoinID
</code>```

答:
Joining subqueries would be slow in some cases. If your tables has not PK or FK indexes joining would be complex for database engines.

First check your tables. Add primary keys to ID columns if you dont have. Create foreign key on JOINID in TABLEX. If you already done and same result then you must create index on JOINID if this not works also then you must check your server configuration, check database engine documentation (Oracle,Mssql,mysql etc.)

You can use this SQL statement to get same result without using subquery,

```<code>SELECT X.*, Y.*
FROM TABLEX as X
JOIN TABLEX as Y ON (X.JOIN_ID=Y.ID)
</code>```

Use subqueries if you have aggregate functions or multiple joins in subquery sql statement.

Title: INNER JOIN Taking longer

Body:
I am joining a sub query with a table.

Sub query runs for 5 Seconds (returns 20 records) and the table has only 4 rows.

Sub query:

Select ID, Name, JoinID
FROM tableX
JOIN ..

Sub query Sample Result:

1, xx, 1
2, yy, 2
3, zz, 1
4, vv, 2
5, bb, 1

TableY (ID, Description):
Data

1, test1
2, test2
3, test3
4, test4

My below query is taking more than 30 seconds. What am I doing wrong here? I see no issue with table Stats. Also sub query is not returning any NULL record for JoinID column.

Select sub.*, tab.*
from
(
sub query
) sub
Join tableY on tableY.ID = sub.JoinID

Body:
Joining subqueries would be slow in some cases. If your tables has not PK or FK indexes joining would be complex for database engines.

First check your tables. Add primary keys to ID columns if you dont have. Create foreign key on JOINID in TABLEX. If you already done and same result then you must create index on JOINID if this not works also then you must check your server configuration, check database engine documentation (Oracle,Mssql,mysql etc.)

You can use this SQL statement to get same result without using subquery,

SELECT X.*, Y.*
FROM TABLEX as X
JOIN TABLEX as Y ON (X.JOIN_ID=Y.ID)

Use subqueries if you have aggregate functions or multiple joins in subquery sql statement.


问:
jQuery 101 - Change CSS not working with advanced selectors
This is across IE and Firefox.

I have an unordered list of 5 items within li tags.

```<code><script type="text/javascript">
$(function() //when doc is ready
    {
                $("li:first").css('color', 'red');

    });

</script>
</code>```

That does absolutely nothing, however if I leave out the :first part, it makes all li's red, unsure of why since I'm following a tutorial.

Here is the html:

```<code><div id="container">
<script type="text/javascript"><!--
$(function() //when doc is ready
{
    $("li:first").css('color', 'red');
});//--></script>

<div id="leftcontent">
<center><img src="http://www.dmu.com/5f/images/thiszis.png"></center>
<div id="hoastdears">
<ul>

<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
</code>```

With

in the header.

答:
It works for me as is, the problem must be somewhere else:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function() //when doc is ready
{
    $("li:first").css('color', 'red');
});//--></script>
</head>
<body>

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
</ul>

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

Update: Find your browser's JavaScript console (in Firefox, it can be found under the Tools menu). You might have a syntax error somewhere that's preventing JavaScript code from executing.

Body:
This is across IE and Firefox.

I have an unordered list of 5 items within li tags.

That does absolutely nothing, however if I leave out the :first part, it makes all li's red, unsure of why since I'm following a tutorial.

Here is the html:

item1

item2

item3

item4

item5

With

in the header.

Body:
It works for me as is, the problem must be somewhere else:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function() //when doc is ready
{
    $("li:first").css('color', 'red');
});//--></script>
</head>
<body>

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
</ul>

</body>
</html>

Update: Find your browser's JavaScript console (in Firefox, it can be found under the Tools menu). You might have a syntax error somewhere that's preventing JavaScript code from executing.


问:
foreach loop inside variable
Here is a situation I need to display values from array through foreach loop inside variable and than echo that variable inside  HTML table. Thanks in Advance. . I have checked all related links in stackoverflow  some links are given  below.

PHP  simple foreach loop with HTML [closed]

My  question is about store looping array inside a variable.. And their is no similarity in another and my question

I want my output to be this way below

I'm getting this error image given below

php filename: foreachloop.php

```<code>    <?php
$arr = array("Apple","orange","strawberry");
$abc = '<table border="2">
            <tr>
                <th>Names</th>
            </tr>
            foreach($arr as $key){
            <tr>
                <td>'.$key.'</td>
            </tr>
        }
        </table>';

echo $abc;
?>
</code>```

答:
You have miss placed the foreach. It is a code block and you have placed it inside the quotes, which will be treated as text. Check the below code.</p>

```<code><?php
    $arr = array("Apple","orange","strawberry");
    $abc = '<table border="2"><tr><th>Names</th></tr>';
    foreach($arr as $key){
        $abc .= '<tr><td>'.$key.'</td></tr>';
    }
    $abc .= '</table>';
    echo $abc;
?>
</code>```

Title: foreach loop inside variable

Body:
Here is a situation I need to display values from array through foreach loop inside variable and than echo that variable inside  HTML table. Thanks in Advance. . I have checked all related links in stackoverflow  some links are given  below.

PHP  simple foreach loop with HTML [closed]

My  question is about store looping array inside a variable.. And their is no similarity in another and my question

I want my output to be this way below

I'm getting this error image given below

php filename: foreachloop.php

    <?php
$arr = array("Apple","orange","strawberry");
$abc = '

                Names

            foreach($arr as $key){

                '.$key.'

        }

';

echo $abc;
?>

Body:
You have miss placed the foreach. It is a code block and you have placed it inside the quotes, which will be treated as text. Check the below code.

<?php
    $arr = array("Apple","orange","strawberry");
    $abc = '<table border="2"><tr><th>Names</th></tr>';
    foreach($arr as $key){
        $abc .= '<tr><td>'.$key.'</td></tr>';
    }
    $abc .= '</table>';
    echo $abc;
?>


问:
500 error when compressing files with .htaccess
I'm trying to compress files with .htaccess but I'm getting a 500 internal error,

This is the code I'm trying to use.

```<code># JavaScript compression htaccess ruleset
AddHandler application/x-httpd-php .js
php_value auto_prepend_file gzip-js.php
php_flag zlib.output_compression On
</code>```

I've also tried this but getting the same error,

```<code><files *.html>
SetOutputFilter DEFLATE
</files>
</code>```

Any suggestions why?

答:
This worked fine for me (paste in .htaccess):

```<code>AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</code>```

Body:
I'm trying to compress files with .htaccess but I'm getting a 500 internal error,

This is the code I'm trying to use.

# JavaScript compression htaccess ruleset
AddHandler application/x-httpd-php .js
php_value auto_prepend_file gzip-js.php
php_flag zlib.output_compression On

I've also tried this but getting the same error,

<files *.html>
SetOutputFilter DEFLATE
</files>

Any suggestions why?

Body:
This worked fine for me (paste in .htaccess):

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript


问:
customizing ActionBar.setDisplayHomeAsUpEnabled in android
Is it possible to customize Home button of action bar?
I use this code for closing notification as home btn clicked, but nothing happens.

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_adult1);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

}

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                notificationManager.cancel(notification_id);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
</code>```

what can I do?

答:
```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home)
        Log.d(TAG, "Home clicked");

    return super.onOptionsItemSelected(item);
}
</code>```

setDisplayHomeAsUpEnabled(boolean showHomeAsUp)

This method makes the icon and title in the action bar clickable so that “up” (ancestral) navigation can be provided.

This method will just make the icon and title pressable, but not actually add the functionality of navigating upwards. That has to be done by specifying the

android:parentActivityName

(takes the parent activity class name) on the activity in the AndroidManifest.xml file.

Body:
Is it possible to customize Home button of action bar?
I use this code for closing notification as home btn clicked, but nothing happens.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_adult1);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

}

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                notificationManager.cancel(notification_id);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

what can I do?

Body:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home)
        Log.d(TAG, "Home clicked");

    return super.onOptionsItemSelected(item);
}

setDisplayHomeAsUpEnabled(boolean showHomeAsUp)

This method makes the icon and title in the action bar clickable so that “up” (ancestral) navigation can be provided.

This method will just make the icon and title pressable, but not actually add the functionality of navigating upwards. That has to be done by specifying the

android:parentActivityName

(takes the parent activity class name) on the activity in the AndroidManifest.xml file.


答:
try something this.</p>

```<code> for(int i=0;i<stat.length;i++){

        sb.append("'"+stat[i]+"'");
            if(i!=stat.length-1){
              sb.append(",");
            }

        }
</code>```

Title: Trim Java String and use in Sql Where Clause

Body:
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}

Result Query:

SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);

I want to get rid of the last comma after 'Broken'

Body:
try something this.

 for(int i=0;i<stat.length;i++){

        sb.append("'"+stat[i]+"'");
            if(i!=stat.length-1){
              sb.append(",");
            }

        }


问:
HTTP 500 FAULT?
I am making a little site, but it says http 500 fault. I know that is that something is wrong. But I have looked like 100 times, and didn't anything. So, I want to ask you guys, what do I do wrong?

<?php
error_reporting(0);
mysql_connect("localhost", "apexgame_root", "apex17") or die(mysql_error());
mysql_select_db("apexgame_voorraad") or die(mysql_error());
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['1']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['1'] = $row['naam'];
$prijs['1'] = $row['prijs'];
$aantal['1'] = $_GET['1a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['2']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['2'] = $row['naam'];
$prijs['2'] = $row['prijs'];
$aantal['2'] = $_GET['2a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['3']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['3'] = $row['naam'];
$prijs['3'] = $row['prijs'];
$aantal['3'] = $_GET['3a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['4']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['4'] = $row['naam'];
$prijs['4'] = $row['prijs'];
$aantal['4'] = $_GET['4a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['5']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['5'] = $row['naam'];
$prijs['5'] = $row['prijs'];
$aantal['5'] = $_GET['5a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['6']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['6'] = $row['naam'];
$prijs['6'] = $row['prijs'];
$aantal['6'] = $_GET['6a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['7']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['7'] = $row['naam'];
$prijs['7'] = $row['prijs'];
$aantal['7'] = $_GET['7a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['8']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['8'] = $row['naam'];
$prijs['8'] = $row['prijs'];
$aantal['8'] = $_GET['8a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['9']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['9'] = $row['naam'];
$prijs['9'] = $row['prijs'];
$aantal['9'] = $_GET['9a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['10']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['10'] = $row['naam'];
$prijs['10'] = $row['prijs'];
$aantal['10'] = $_GET['10a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['11']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['11'] = $row['naam'];
$prijs['11'] = $row['prijs'];
$aantal['11'] = $_GET['11a'];
$result = mysql_query("SELECT * FROM voorraad WHERE id = '".$_GET['12']."'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$naam['12'] = $row['naam'];
$prijs['12'] = $row['prijs'];
$aantal['12'] = $_GET['12a'];
?>

<!DOCTYPE html>

    <meta charset="UTF-8">

    <meta name="generator" content="Silex v2.2.7">

    <link rel="stylesheet" href="//editor.silex.me/static/2.7/normalize.css" data-silex-static="">
    <link rel="stylesheet" href="//editor.silex.me/static/2.7/front-end.css" data-silex-static="">

    <title></title>

            <img alt="open mobile menu" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAoCAYAAAC8cqlMAAAB5UlEQVR42u2ZPWvCUBSGM+UfFO3e3dLu/QN+oKj4EUXRQREEJYgoiCAu6qCogyDo7iJ21UUaKqEgCC4iiEMGB3UVgsnpTWj/wfVK2nvhGbKEPJyT996TMMzPGg6H5mKx+GgkyuWyeTQasb8OTDwef4tEIp8+n+/LYIjJZJJHQiwzm81M6OLDarWqNpsNjEYgEJCy2ewT0+/3TagighElNFAnQT6ft1ARKkJFqMgfFvF4PFpuEwFtdrcRqVarIIoirFYrIiyXSxiPx+B2u/GJBINBuF6vQHopigK1Wg2fCMdxcLlciIuoqgqNRgOfiN1uB3Qwg91uB8fjkQiHwwEmkwne1qLxS0VuKKJle71eh06nQ4Rmswk8z+MVcTqdsNlsQJZlotF7Pp8hk8ngE4lGo/qN7xG/vV4Pb0Xm8zlxkdPpBGgMx/+yJxIJKBQKRMjlcuBwOGhq/Q+RcDgMsViMCFrAuFwu/CKDwQC22y1IkkSE/X4PgiDo+xc2Ea0S9zjGa/Hb7Xbxifj9fj0K7yFSqVTwtlY6nYbpdKpPiSRYLBbQarX0PYymFhWhIlSEilCRW6GdyUqlkoVZr9dsKpXiOY6TtW+7BkNBz/7ebrcf9L+6Xq+XRYPMMyrTq5EIhUIvaAjTJb4BBNQ2yhnth0wAAAAASUVORK5CYII="
                class="silex-element-content">

        Page 1

Datum:

<?php echo date("l jS \of F Y h:i:s A"); ?>

Aantal producten: <?php echo $_GET['aantal']; ?>

    <?php
    echo $naam['1'] . '  -  ' . $prijs['1'] 'Euro per stuk  -  Aantal:' . $aantal['1'] '  -  Totaal:' . $prijs['1']*$aantal['1'] . '
';
    echo $naam['2'] . '  -  ' . $prijs['2'] 'Euro per stuk  -  Aantal:' . $aantal['2'] '  -  Totaal:' . $prijs['2']*$aantal['2'] . '
';
    echo $naam['3'] . '  -  ' . $prijs['3'] 'Euro per stuk  -  Aantal:' . $aantal['3'] '  -  Totaal:' . $prijs['3']*$aantal['3'] . '
';
    echo $naam['4'] . '  -  ' . $prijs['4'] 'Euro per stuk  -  Aantal:' . $aantal['4'] '  -  Totaal:' . $prijs['4']*$aantal['4'] . '
';
    echo $naam['5'] . '  -  ' . $prijs['5'] 'Euro per stuk  -  Aantal:' . $aantal['5'] '  -  Totaal:' . $prijs['5']*$aantal['5'] . '
';
    echo $naam['6'] . '  -  ' . $prijs['6'] 'Euro per stuk  -  Aantal:' . $aantal['6'] '  -  Totaal:' . $prijs['6']*$aantal['6'] . '
';
    echo $naam['7'] . '  -  ' . $prijs['7'] 'Euro per stuk  -  Aantal:' . $aantal['7'] '  -  Totaal:' . $prijs['7']*$aantal['7'] . '
';
    echo $naam['8'] . '  -  ' . $prijs['8'] 'Euro per stuk  -  Aantal:' . $aantal['8'] '  -  Totaal:' . $prijs['8']*$aantal['8'] . '
';
    echo $naam['9'] . '  -  ' . $prijs['9'] 'Euro per stuk  -  Aantal:' . $aantal['9'] '  -  Totaal:' . $prijs['9']*$aantal['9'] . '
';
    echo $naam['10'] . '  -  ' . $prijs['10'] 'Euro per stuk  -  Aantal:' . $aantal['10'] '  -  Totaal:' . $prijs['10']*$aantal['10'] . '
';
    echo $naam['11'] . '  -  ' . $prijs['11'] 'Euro per stuk  -  Aantal:' . $aantal['11'] '  -  Totaal:' . $prijs['11']*$aantal['11'] . '
';
    echo $naam['12'] . '  -  ' . $prijs['12'] 'Euro per stuk  -  Aantal:' . $aantal['12'] '  -  Totaal:' . $prijs['12']*$aantal['12'] . '
';
    ?>

AlleenGadgets

            PLAKBON

                Aan:

<?php echo $_GET['straat']; ?>

                <?php echo $_GET['postcode']; ?>

                <?php echo $_GET['plaats']; ?>

                <?php echo $_GET['land']; ?>

                Van:

Burgemeester Perksingel 28

                1761CM

                Anna Paulowna

                Nederland

```

答:
you are missing something here:

```<code>echo $naam['1'] . '  -  ' . $prijs['1'] 'Euro per stuk  -  Aantal:'
</code>```

(which is at line 220)

it should read:

```<code>echo $naam['1'] . '  -  ' . $prijs['1'] . 'Euro per stuk  -  Aantal:'
</code>```

This error is also on de next lines..

Title: HTTP 500 FAULT?

Body:
you are missing something here:

echo $naam['1'] . '  -  ' . $prijs['1'] 'Euro per stuk  -  Aantal:'

(which is at line 220)

it should read:

echo $naam['1'] . '  -  ' . $prijs['1'] . 'Euro per stuk  -  Aantal:'

This error is also on de next lines..


问:
Using index in df name
I'm trying to merge 10 data frames on the intersection of two columns. I need it to return 25 data frames.

I have five portfolios of stocks ME_1, ME_2, ..., ME_5, and likewise 5 portfolios BM_1, BM_2, ..., BM_5.

R will not recognize BM_[i] as e.g. BM_1

```<code>for(i in 1:5) {
    for(j in 1:5) {
            pf <- paste("bm_", i, "me_", j, sep ="")
            assign(pf, merge(x=BM_[i], y=ME_[j], by = c("date", "tick")))

            pf <- pf %>%
                    arrange(tick, date) %>%
                    group_by(date_year.x) %>%
                    mutate(W = MVE_jun/sum(MVE_jun))
    }
}
</code>```

I get the following error:

```<code>Error in merge(x = BM_[i], y = ME_[j], by = c("date", "tick")) :
  object 'BM_' not found
</code>```

答:
The reason is that there is no BM_ dataset. We need BM_1 BM_2 instead of subsetting the columns using an object that was not there,  Using paste will get the character object names and then with get, we extract the value stored in that object

```<code>for(i in 1:5) {
   for(j in 1:5) {
        pf <- paste("bm_", i, "me_", j, sep ="")
        assign(pf, merge(x=get(paste0("BM_", i)),
               y=get(paste0("ME_", j)), by = c("date", "tick")))

        pf <- pf %>%
                arrange(tick, date) %>%
                group_by(date_year.x) %>%
                mutate(W = MVE_jun/sum(MVE_jun))
  }
}
</code>```

NOTE: As noted in the comments paste is vectorized, so there is no need to call paste multipie times

Title: Using index in df name

Body:
I'm trying to merge 10 data frames on the intersection of two columns. I need it to return 25 data frames.

I have five portfolios of stocks ME_1, ME_2, ..., ME_5, and likewise 5 portfolios BM_1, BM_2, ..., BM_5.

R will not recognize BM_[i] as e.g. BM_1

for(i in 1:5) {
    for(j in 1:5) {
            pf <- paste("bm_", i, "me_", j, sep ="")
            assign(pf, merge(x=BM_[i], y=ME_[j], by = c("date", "tick")))

            pf <- pf %>%
                    arrange(tick, date) %>%
                    group_by(date_year.x) %>%
                    mutate(W = MVE_jun/sum(MVE_jun))
    }
}

I get the following error:

Error in merge(x = BM_[i], y = ME_[j], by = c("date", "tick")) :
  object 'BM_' not found

Body:
The reason is that there is no BM_ dataset. We need BM_1 BM_2 instead of subsetting the columns using an object that was not there,  Using paste will get the character object names and then with get, we extract the value stored in that object

for(i in 1:5) {
   for(j in 1:5) {
        pf <- paste("bm_", i, "me_", j, sep ="")
        assign(pf, merge(x=get(paste0("BM_", i)),
               y=get(paste0("ME_", j)), by = c("date", "tick")))

        pf <- pf %>%
                arrange(tick, date) %>%
                group_by(date_year.x) %>%
                mutate(W = MVE_jun/sum(MVE_jun))
  }
}

NOTE: As noted in the comments paste is vectorized, so there is no need to call paste multipie times


问:
SKLearn: Getting distance of each point from decision boundary?
I am using SKLearn to run SVC on my data.

```<code>from sklearn import svm

svc = svm.SVC(kernel='linear', C=C).fit(X, y)
</code>```

I want to know how I can get the distance of each data point in X from the decision boundary?

答:
It happens to be that I am doing the homework 1 of a course named Machine Learning Techniques. And there happens to be a problem about point's distance to hyperplane even for RBF kernel.

First we know that SVM is to find an "optimal" w for a hyperplane wx + b = 0.

And the fact is that

w = \sum_{i} \alpha_i \phi(x_i)

where those x are so called support vectors and those alpha are coefficient of them. Note that there is a phi() outside the x; it is the transform function that transform x to some high dimension space (for RBF, it is infinite dimension). And we know that

```<code>[\phi(x_1)\phi(x_2) = K(x_1, x_2)][2]
</code>```

so we can compute

then we can get w. So, the distance you want should be

```<code>svc.decision_function(x) / w_norm
</code>```

where w_norm the the norm calculated above.

(StackOverflow doesn't allow me post more than 2 links so render the latex yourself bah.)

Body:
I am using SKLearn to run SVC on my data.

from sklearn import svm

svc = svm.SVC(kernel='linear', C=C).fit(X, y)

I want to know how I can get the distance of each data point in X from the decision boundary?

Body:
It happens to be that I am doing the homework 1 of a course named Machine Learning Techniques. And there happens to be a problem about point's distance to hyperplane even for RBF kernel.

First we know that SVM is to find an "optimal" w for a hyperplane wx + b = 0.

And the fact is that

w = \sum_{i} \alpha_i \phi(x_i)

where those x are so called support vectors and those alpha are coefficient of them. Note that there is a phi() outside the x; it is the transform function that transform x to some high dimension space (for RBF, it is infinite dimension). And we know that

[\phi(x_1)\phi(x_2) = K(x_1, x_2)][2]

so we can compute

then we can get w. So, the distance you want should be

svc.decision_function(x) / w_norm

where w_norm the the norm calculated above.

(StackOverflow doesn't allow me post more than 2 links so render the latex yourself bah.)

ContentLicense: CC BY-SA 4.0


问:
How to convert this php code in a wordpress shortcode?
Hi I found this code on online, it is a simple button to reveal the coupon code and open the URL at the same time.

```<code>function coupon_add($coup, $uurl)
{
echo "
<script type='text/javascript'>
<!--
function coupon(coup,url)
{alert('COUPON CODE: ' + coup);
window.open(url,'_blank');
}
//-->
</script>";
echo "<center><br /><input style=\"width:250px; height:60px;font-
size:30px;\" type=\"button\" onclick=\"coupon('".$coup."','".$uurl."')\"
value=\"VIEW COUPON\" \/></center><p>";
}
</code>```

I would like to turn this into a short code so I can insert it into a post. Would love some help with this, thanks in advance!

答:
In your functions.php:

```<code>add_shortcode( 'my_coupon_add', 'sc_my_coupon_add' );
function sc_my_coupon_add( $args, $content = null ){
  $atts = shortcode_atts( array(
    'coup' => '',
    'uurl' => ''
  ), $args, 'my_coupon_add' );
  return "<script type='text/javascript'>
    function coupon( coup, url ){
      alert( 'COUPON CODE: ' + coup );
      window.open( url, '_blank' );
    }
   </script>
   <center><br /><input style=\"width:250px; height:60px;font-size:30px;\" type=\"button\" onclick=\"coupon('" . $atts[ 'coup' ] . "','" . $atts[ 'uurl' ] . "')\" value=\"VIEW COUPON\" \/></center><p>";
}
</code>```

Now you can use the shortcode [my_coupon_add coup="" uurl=""] and pass your parameters. The way the javascript is written, this can only be used once on a page or post or else you'll have issues with the coupon() function, but this should give you enough to scale/rewrite it if needed more than once (like moving the coupon() javascript function to a main js file so it's available once and only when needed).

You might need to double-check the single and double quotes - I whipped this up quickly.

Body:
Hi I found this code on online, it is a simple button to reveal the coupon code and open the URL at the same time.

function coupon_add($coup, $uurl)
{
echo "
";
echo "
<input style=\"width:250px; height:60px;font-
size:30px;\" type=\"button\" onclick=\"coupon('".$coup."','".$uurl."')\"
value=\"VIEW COUPON\" \/>
";
}

I would like to turn this into a short code so I can insert it into a post. Would love some help with this, thanks in advance!

Body:
In your functions.php:

add_shortcode( 'my_coupon_add', 'sc_my_coupon_add' );
function sc_my_coupon_add( $args, $content = null ){
  $atts = shortcode_atts( array(
    'coup' => '',
    'uurl' => ''
  ), $args, 'my_coupon_add' );
  return "<script type='text/javascript'>
    function coupon( coup, url ){
      alert( 'COUPON CODE: ' + coup );
      window.open( url, '_blank' );
    }
   </script>
   <center><br /><input style=\"width:250px; height:60px;font-size:30px;\" type=\"button\" onclick=\"coupon('" . $atts[ 'coup' ] . "','" . $atts[ 'uurl' ] . "')\" value=\"VIEW COUPON\" \/></center><p>";
}

Now you can use the shortcode [my_coupon_add coup="" uurl=""] and pass your parameters. The way the javascript is written, this can only be used once on a page or post or else you'll have issues with the coupon() function, but this should give you enough to scale/rewrite it if needed more than once (like moving the coupon() javascript function to a main js file so it's available once and only when needed).

You might need to double-check the single and double quotes - I whipped this up quickly.


问:
How to print All rows in jtable
example data:
These are my 2 rows in jtable

```<code>[john, carter, post, add]
[smith, sale, col, late]

  for (int count = 0; count < dataModel.getRowCount(); count++){
  data.add(dataModel.getValueAt(count, 0).toString());
   }
  System.out.println(data);
</code>```

When I run this code i get output:

```<code>[john, smith]
</code>```

My question is how can i print the entire row rather than just the first column.
So the output should be:

```<code>[john, carter, post, add]
</code>```

答:
In order to print the entire table you'll need two loops, one for the rows, one for the columns:</p>

```<code>for (int row = 0; row < dataModel.getRowCount(); row++){
    for (int column = 0; column < dataModel.getColumnCount(); column++){
        data.add(dataModel.getValueAt(row, column).toString());
    }
    // Probably add new line to 'data'
}
</code>```

Title: How to print All rows in jtable

Body:
example data:
These are my 2 rows in jtable

[john, carter, post, add]
[smith, sale, col, late]

  for (int count = 0; count < dataModel.getRowCount(); count++){
  data.add(dataModel.getValueAt(count, 0).toString());
   }
  System.out.println(data);

When I run this code i get output:

[john, smith]

My question is how can i print the entire row rather than just the first column.
So the output should be:

[john, carter, post, add]

Body:
In order to print the entire table you'll need two loops, one for the rows, one for the columns:

for (int row = 0; row < dataModel.getRowCount(); row++){
    for (int column = 0; column < dataModel.getColumnCount(); column++){
        data.add(dataModel.getValueAt(row, column).toString());
    }
    // Probably add new line to 'data'
}


问:
Why doesn't my counter count?
This really suprised me. One of the simplest things doesn't work, making a counter. I'm making a kinda game application in c# and there is also a timer who counts the time. Very simple right? I know how to code this and this is something I did before but I don't understand why it isn't working now.

```<code>int i = 0;
i++;
label1.Text = i.ToString();
</code>```

label1.Text turns in to 1 and nothing else happens. Also tryied this with a timer but it freeezes in 1. I know this post isn't really going to help other people but it is very frustrating.

答:
If you want to increment it you have to add the incrementing logic in a loop like for or while loop:

If you want to use timer to count something please refer to this question : here

Title: Why doesn't my counter count?

Body:
This really suprised me. One of the simplest things doesn't work, making a counter. I'm making a kinda game application in c# and there is also a timer who counts the time. Very simple right? I know how to code this and this is something I did before but I don't understand why it isn't working now.

int i = 0;
i++;
label1.Text = i.ToString();

label1.Text turns in to 1 and nothing else happens. Also tryied this with a timer but it freeezes in 1. I know this post isn't really going to help other people but it is very frustrating.


问:
Inserting JSON into MySQL using Python
I have a JSON object in Python.  I am Using Python DB-API and SimpleJson. I am trying to insert the json into a MySQL table.

At moment am getting errors and I believe it is due to the single quotes '' in the JSON Objects.

How can I insert my JSON Object into MySQL using Python?

Here is the error message I get:

```<code>error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
</code>```

Another error for reference

```<code>error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right
syntax to use near 'RT @tweetmeme The Best BlackBerry Pearl
Cell Phone Covers http://bit.ly/9WtwUO''' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py|found_terminator|55]
[twitter.py|callback|28] [build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py|execute|166] [build/bdist.linux-
x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
</code>```

Here is a link to the code that I am using http://pastebin.com/q5QSfYLa

```<code>#!/usr/bin/env python

try:
        import json as simplejson
except ImportError:
        import simplejson

import twitstream
import MySQLdb

USER = ''
PASS = ''

USAGE = """%prog"""

conn = MySQLdb.connect(host = "",
                       user = "",
                       passwd = "",
                       db = "")

# Define a function/callable to be called on every status:
def callback(status):

    twitdb = conn.cursor ()
    twitdb.execute ("INSERT INTO tweets_unprocessed (text, created_at, twitter_id, user_id, user_screen_name, json) VALUES (%s,%s,%s,%s,%s,%s)",(status.get('text'), status.get('created_at'), status.get('id'), status.get('user', {}).get('id'), status.get('user', {}).get('screen_name'), status))

   # print status
     #print "%s:\t%s\n" % (status.get('user', {}).get('screen_name'), status.get('text'))

if __name__ == '__main__':
    # Call a specific API method from the twitstream module:
    # stream = twitstream.spritzer(USER, PASS, callback)

    twitstream.parser.usage = USAGE
    (options, args) = twitstream.parser.parse_args()

    if len(args) < 1:
        args = ['Blackberry']

    stream = twitstream.track(USER, PASS, callback, args, options.debug, engine=options.engine)

    # Loop forever on the streaming call:
    stream.run()
</code>```

答:
use json.dumps(json_value) to convert your json object(python object) in a json string that you can insert in a text field in mysql

http://docs.python.org/library/json.html

Title: Inserting JSON into MySQL using Python

Body:
I have a JSON object in Python.  I am Using Python DB-API and SimpleJson. I am trying to insert the json into a MySQL table.

At moment am getting errors and I believe it is due to the single quotes '' in the JSON Objects.

How can I insert my JSON Object into MySQL using Python?

Here is the error message I get:

error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])

Another error for reference

error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right
syntax to use near 'RT @tweetmeme The Best BlackBerry Pearl
Cell Phone Covers http://bit.ly/9WtwUO''' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py|found_terminator|55]
[twitter.py|callback|28] [build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py|execute|166] [build/bdist.linux-
x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])

Here is a link to the code that I am using http://pastebin.com/q5QSfYLa

#!/usr/bin/env python

try:
        import json as simplejson
except ImportError:
        import simplejson

import twitstream
import MySQLdb

USER = ''
PASS = ''

USAGE = """%prog"""

conn = MySQLdb.connect(host = "",
                       user = "",
                       passwd = "",
                       db = "")

# Define a function/callable to be called on every status:
def callback(status):

    twitdb = conn.cursor ()
    twitdb.execute ("INSERT INTO tweets_unprocessed (text, created_at, twitter_id, user_id, user_screen_name, json) VALUES (%s,%s,%s,%s,%s,%s)",(status.get('text'), status.get('created_at'), status.get('id'), status.get('user', {}).get('id'), status.get('user', {}).get('screen_name'), status))

   # print status
     #print "%s:\t%s\n" % (status.get('user', {}).get('screen_name'), status.get('text'))

if __name__ == '__main__':
    # Call a specific API method from the twitstream module:
    # stream = twitstream.spritzer(USER, PASS, callback)

    twitstream.parser.usage = USAGE
    (options, args) = twitstream.parser.parse_args()

    if len(args) < 1:
        args = ['Blackberry']

    stream = twitstream.track(USER, PASS, callback, args, options.debug, engine=options.engine)

    # Loop forever on the streaming call:
    stream.run()


问:
Wordpress Permalink Settings not working
I have installed a test blog on RichBloggers Domain. I am trying to use permalinks. With My current settings as follow

The site links works but with query string in url like

But when I change the setting to post name

My Links give me error

Here is my .htaccess

```<code># BEGIN WordPress
  <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
  </IfModule>

# END WordPress
</code>```

What am I missing?

答: Finally I figured it out. The Hosting Server I am using has old Plesk on it and doesn't have cPanel so the PHP version is outdated. URL rewrite is not working because Mod_rewrite is not enabled. </p>

Body:
I have installed a test blog on RichBloggers Domain. I am trying to use permalinks. With My current settings as follow

The site links works but with query string in url like

But when I change the setting to post name

My Links give me error

Here is my .htaccess

# BEGIN WordPress
  <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
  </IfModule>

# END WordPress

What am I missing?


问:
Modeling a Wire Protocol that allows to send objects over HTTP like application layer protocol
Following is kind of system (a small prototype) I need to build.

"Build a Simple Middleware System. That allows dynamically adding a service into the system and allows accessing the service from a client program. System will include simple utilities to build the server skel and client stub is to be built. To be written in Java; Server side using servlet API to be deployed in Tomcat. On client side, only use the basic socket API and no other libraries used. All processing should be done using basic language constructs. Define a OOPs enabled wire protocol, based on which the system is to be implemented. Should support defining object structure definitions."

Important design decision I need to take is :
"How should I design wire protocol that enables sending of objects and not only premitive data types, I mean what it should include ?"

I found CORBA(https://en.wikipedia.org/wiki/Common_Object_Request_Broker_Architecture), as good reference. If anyone can explain how it marshalls parameters and in which format it sends data (an example) would do the job.

Thanks.

答:
Protocol on the wire is GIOP but for a long time already GIOP with TCP/IP transport is used almost everywhere. GIOP with TCP/IP transport is IIOP. There's also a secure version with SSL, SSLIOP.

General Inter-ORB Protocol


问:
import user defined modules into pydev
I am a beginner to Eclipse neon + Pydev combo.
Trying to use python modules I created into other modules I will be creating.
For a start, I was going to use TKinter tutorial program outlined here:
http://effbot.org/tkinterbook/tkinter-hello-again.htm

In addition to printing a statement in response to a mouse click, I want to run a small module, fibo.py

Here's my code:

```<code>import the library
from tkinter import *

import fibo

class App:

    def __init__(self, master):

            frame = Frame(master)
            frame.pack()

            self.button = Button(
            frame, text="QUIT", fg="red", command=frame.quit
            )
            self.button.pack(side=LEFT)

            self.hi_there = Button(frame, text="Hello",command=self.say_hi)
            self.hi_there.pack(side=LEFT)

    def say_hi(self):
        fib(100)
        print ("hi there, everyone!")

root = Tk()

app = App(root)

root.mainloop()
root.destroy() # optional; see description below
</code>```

Here's fibo.py

```<code>def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
    print (b, end=" ")
    a, b = b, a+b

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
    result.append(b)
    a, b = b, a+b
    return result
</code>```

Both modules are in the same project and workspace.
The editor says,"unresolved import fibo"
Why is the module fibo not recognized by in pydev/eclipse?

My ultimate goal is to run a module upon button click. If there's a more direct way to accomplish this, I would like to know.

答:
Ok, so, based on your screenshot, the structure you have is actually:

```<code>/project (this is the PYTHONPATH root and marked as source folder)
/project/root
/project/root/__init__.py
/project/root/nested
/project/root/nested/__init__.py
/project/root/nested/example.py
/project/root/nested/fibo.py
</code>```

In this case, your import should be: from root.nested import fibo. Your code may work in the command line, but that's because you added an entry to sys.path only in runtime (so, PyDev can't follow that).

The other option would be moving both example.py and fibo.py to /project.

You can also use a relative import as from . import fibo, but then, to run the module as a __main__ module, you'll have to run modules by the module name (with the -m flag) -- you can configure PyDev to do that at the preferences > PyDev > Run > Launch modules with "python -m mod.name".

As a note, if you just write:

fibo in your case, and wait for the undefined variable error to be shown, you can use Ctrl+1 in that same line to get a suggestion which will write the import for you (or you can do a code-completion which will also write an import for you automatically).

Title: import user defined modules into pydev

Body:
I am a beginner to Eclipse neon + Pydev combo.
Trying to use python modules I created into other modules I will be creating.
For a start, I was going to use TKinter tutorial program outlined here:
http://effbot.org/tkinterbook/tkinter-hello-again.htm

In addition to printing a statement in response to a mouse click, I want to run a small module, fibo.py

Here's my code:

import the library
from tkinter import *

import fibo

class App:

    def __init__(self, master):

            frame = Frame(master)
            frame.pack()

            self.button = Button(
            frame, text="QUIT", fg="red", command=frame.quit
            )
            self.button.pack(side=LEFT)

            self.hi_there = Button(frame, text="Hello",command=self.say_hi)
            self.hi_there.pack(side=LEFT)

    def say_hi(self):
        fib(100)
        print ("hi there, everyone!")

root = Tk()

app = App(root)

root.mainloop()
root.destroy() # optional; see description below

Here's fibo.py

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
    print (b, end=" ")
    a, b = b, a+b

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
    result.append(b)
    a, b = b, a+b
    return result

Both modules are in the same project and workspace.
The editor says,"unresolved import fibo"
Why is the module fibo not recognized by in pydev/eclipse?

My ultimate goal is to run a module upon button click. If there's a more direct way to accomplish this, I would like to know.

Body:
Ok, so, based on your screenshot, the structure you have is actually:

/project (this is the PYTHONPATH root and marked as source folder)
/project/root
/project/root/__init__.py
/project/root/nested
/project/root/nested/__init__.py
/project/root/nested/example.py
/project/root/nested/fibo.py

In this case, your import should be: from root.nested import fibo. Your code may work in the command line, but that's because you added an entry to sys.path only in runtime (so, PyDev can't follow that).

The other option would be moving both example.py and fibo.py to /project.

You can also use a relative import as from . import fibo, but then, to run the module as a __main__ module, you'll have to run modules by the module name (with the -m flag) -- you can configure PyDev to do that at the preferences > PyDev > Run > Launch modules with "python -m mod.name".

As a note, if you just write:

fibo in your case, and wait for the undefined variable error to be shown, you can use Ctrl+1 in that same line to get a suggestion which will write the import for you (or you can do a code-completion which will also write an import for you automatically).


问:
Does Newtonsoft.Json Serialization Support Year-Only Date Fields?
According to ISO 8601 json date fields can contain partial data, e.g. "YYYY" for year-only or "YYYY-MM" for year-month-only.

But, the following code, using Json.NET deserializer that's supposed to support it, throws a format error:

```<code>class PartialDateContainter
{
    public DateTime MyPartialDate { get; set; }
}

[Test]
public void JustCheckJsonDates()
{
    var serializationSettings =
        new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            NullValueHandling = NullValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            ContractResolver = new ReadOnlyJsonContractResolver(),
            Converters = new List<JsonConverter>
            {
                new Iso8601TimeSpanConverter(),
                new IsoDateTimeConverter()
            }
        };

    var ser = JsonSerializer.Create(serializationSettings);

    var json = "{ \"MyPartialDate\": \"2005\" }";

    var shus = ser.Deserialize<PartialDateContainter>(new JsonTextReader(new StringReader(json)));

    Assert.True(true);
}
</code>```

Am I missing something?

答:
Does Newtonsoft.Json Serialization Support Year-Only Date Fields?

Not by default.

But it is flexible enough that is can be configured to support year only date fields.

Referencing Json.Net documentation here Serializing Dates in JSON

If your dates don't follow the ISO 8601 standard, then the
  DateFormatString setting can be used to customize the format of date
  strings that are read and written using .NET's custom date and time
  format syntax.

The following simplified example worked

```<code>[TestClass]
public class JsonNetDateSerializationTests {
    [TestMethod]
    public void JustCheckJsonDates() {
        //Arrange
        var settings =
            new JsonSerializerSettings {
                DateFormatString = "yyyy", //<-- for year only dates. all others should parse fine
            };

        var json = "{ \"YearOnly\": \"2017\", \"YearMonth\": \"2017-04\", \"YearMonthDay\": \"2017-04-02\" }";
        var expected = 2017;

        //Act
        var actual = JsonConvert.DeserializeObject<PartialDateContainter>(json, settings);

        //Assert
        Assert.IsNotNull(actual);
        Assert.AreEqual(expected, actual.YearOnly.Year);
        Assert.AreEqual(expected, actual.YearMonth.Year);
        Assert.AreEqual(expected, actual.YearMonthDay.Year);
    }

    class PartialDateContainter {
        public DateTime YearOnly { get; set; }
        public DateTime YearMonth { get; set; }
        public DateTime YearMonthDay { get; set; }
    }
}
</code>```

Body:
According to ISO 8601 json date fields can contain partial data, e.g. "YYYY" for year-only or "YYYY-MM" for year-month-only.

But, the following code, using Json.NET deserializer that's supposed to support it, throws a format error:

class PartialDateContainter
{
    public DateTime MyPartialDate { get; set; }
}

[Test]
public void JustCheckJsonDates()
{
    var serializationSettings =
        new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            NullValueHandling = NullValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            ContractResolver = new ReadOnlyJsonContractResolver(),
            Converters = new List<JsonConverter>
            {
                new Iso8601TimeSpanConverter(),
                new IsoDateTimeConverter()
            }
        };

    var ser = JsonSerializer.Create(serializationSettings);

    var json = "{ \"MyPartialDate\": \"2005\" }";

    var shus = ser.Deserialize<PartialDateContainter>(new JsonTextReader(new StringReader(json)));

    Assert.True(true);
}

Am I missing something?

Body:
Does Newtonsoft.Json Serialization Support Year-Only Date Fields?

Not by default.

But it is flexible enough that is can be configured to support year only date fields.

Referencing Json.Net documentation here Serializing Dates in JSON

If your dates don't follow the ISO 8601 standard, then the
  DateFormatString setting can be used to customize the format of date
  strings that are read and written using .NET's custom date and time
  format syntax.

The following simplified example worked

[TestClass]
public class JsonNetDateSerializationTests {
    [TestMethod]
    public void JustCheckJsonDates() {
        //Arrange
        var settings =
            new JsonSerializerSettings {
                DateFormatString = "yyyy", //<-- for year only dates. all others should parse fine
            };

        var json = "{ \"YearOnly\": \"2017\", \"YearMonth\": \"2017-04\", \"YearMonthDay\": \"2017-04-02\" }";
        var expected = 2017;

        //Act
        var actual = JsonConvert.DeserializeObject<PartialDateContainter>(json, settings);

        //Assert
        Assert.IsNotNull(actual);
        Assert.AreEqual(expected, actual.YearOnly.Year);
        Assert.AreEqual(expected, actual.YearMonth.Year);
        Assert.AreEqual(expected, actual.YearMonthDay.Year);
    }

    class PartialDateContainter {
        public DateTime YearOnly { get; set; }
        public DateTime YearMonth { get; set; }
        public DateTime YearMonthDay { get; set; }
    }
}


问:
How do I access individual words after splitting a string?
```<code>std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";
</code>```

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

```<code>if (word[0] == "something")
   do_this();
else
   do_that();
</code>```

答: You've defined token to be a std::string, which uses the index operator [] to return an individual character.  In order to output the entire string, avoid using the index operator.

Body:
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

if (word[0] == "something")
   do_this();
else
   do_that();


问:
Executing a package manager command on just one project in a solution
I have two projects in my solution, one is a WPF application and the other is a WCF.

I have entity framework on my WCF application and want to execute the Update-Database command since I have added to my initial seed method. How can I run this on the WCF project alone? As of now I get a warning telling me that migrations are not enabled for my WPF project.

答:
Found solution, Target a project like so:</p>

```<code>Update-Database -ProjectName MyProjectName
</code>```

Body:
Found solution, Target a project like so:

Update-Database -ProjectName MyProjectName


问:
Check if observer contains some element
To check if array contains undefined I can do it like this [undefined].indexOf(undefined) or this [undefined].some(el => el === undefined). But in my Vue.js app I've got -1 and false. I tried to print my data and I've got [__ob__: Observer]. How to check if Observer contains undefined?

```<code>var app = new Vue({
  el: '#app',
  data: [undefined]
  },
  methods: {
    someFunction() {
      console.log(this.data.some(el => el === undefined), this.data.indexOf(undefined));
    }
  }
})
</code>```

答:
Vue.js expects data to be an object, not an array.

```<code>var app = new Vue({
  el: '#app',
  data: {
     prop: [undefined]
  },
  methods: {
    someFunction() {
      console.log(this.prop.some(el => el === undefined), this.prop.indexOf(undefined));
    }
  }
});
</code>```

Title: Check if observer contains some element

Body:
To check if array contains undefined I can do it like this [undefined].indexOf(undefined) or this [undefined].some(el => el === undefined). But in my Vue.js app I've got -1 and false. I tried to print my data and I've got [__ob__: Observer]. How to check if Observer contains undefined?

var app = new Vue({
  el: '#app',
  data: [undefined]
  },
  methods: {
    someFunction() {
      console.log(this.data.some(el => el === undefined), this.data.indexOf(undefined));
    }
  }
})

Body:
Vue.js expects data to be an object, not an array.

var app = new Vue({
  el: '#app',
  data: {
     prop: [undefined]
  },
  methods: {
    someFunction() {
      console.log(this.prop.some(el => el === undefined), this.prop.indexOf(undefined));
    }
  }
});


问:
Validating a Django model field based on another field's value?
I have a Django app with models accessible by both Django REST Framework and a regular form interface. The form interface has some validation checks before saving changes to the model, but not using any special Django framework, just a simple local change in the view.

I'd like to apply the same validation to forms and REST calls, so I want to move my validation into the model. I can see how to do that for simple cases using the validators field of the Field, but in one case I have a name/type/value model where the acceptable values for 'value' change depending on which type is selected. The validator doesn't get sent any information about the model that the field is in, so it doesn't have access to other fields.

How can I perform this validation, without having essentially the same code in a serializer for DRF and my POST view for the form?

答:
You can use the required package for your cross-field validation. It allows you to express your validation rules declaratively in python. You would have something like this with DRF:

```<code>class MySerializer(serializers.Serializer):

    REQUIREMENTS = (
        Requires("end_date", "start_date") +
        Requires("end_date", R("end_date") > R("start_date")) +
        Requires("end_date", R("end_date") < today.date() + one_year) +
        Requires("start_date", R("start_date") < today.date() + one_year)
     )

    start_date = serializers.DateField(required=False, null=True, blank=True)
    end_date = serializers.DateField(required=False, null=True, blank=True)

    def validate(self, data):
        self.REQUIREMENTS.validate(data)  # handle validation error
</code>```

You could put the REQUIREMENTS on your Model and have both your DRF and Django Form validate your data using it.

Here is a blog post explaining more

Body:
You can use the required package for your cross-field validation. It allows you to express your validation rules declaratively in python. You would have something like this with DRF:

class MySerializer(serializers.Serializer):

    REQUIREMENTS = (
        Requires("end_date", "start_date") +
        Requires("end_date", R("end_date") > R("start_date")) +
        Requires("end_date", R("end_date") < today.date() + one_year) +
        Requires("start_date", R("start_date") < today.date() + one_year)
     )

    start_date = serializers.DateField(required=False, null=True, blank=True)
    end_date = serializers.DateField(required=False, null=True, blank=True)

    def validate(self, data):
        self.REQUIREMENTS.validate(data)  # handle validation error

You could put the REQUIREMENTS on your Model and have both your DRF and Django Form validate your data using it.

Here is a blog post explaining more


问:
Set the date from a shell on Android
For debugging purposes, I would like to run my app on a certain date. I can change the date manually on my emulator, of course, but I was wondering if there was a simple way to do it from the emulator shell (I know it can't be done from the UI).</p>

答:
Latest instructions, as of September 2022, for Android 9 and above:

Please see this answer: Emulated Android device does not re-sync time/date after restoring snapshot

Old instructions from April 2017, which don't work for Android 9/10/11/12/13 and above:

The following works on Mac OS X to align exactly with your computer's time, and it sets the seconds as well.

For Android 6/7/8 emulators, use this:

```<code>adb -e shell date $(date +%m%d%H%M%Y.%S)
</code>```

For Android 4/5 emulators, use this:

```<code>adb -e shell date -s $(date "+%Y%m%d.%H%M%S")
</code>```

For example, you could use a shell script to detect which Android OS version is running and run the correct adb command appropriately:

#!/bin/bash
android_os_version=$(adb -e shell getprop ro.build.version.sdk)
# The adb function will return a string like "23\n". So you must remove the new line
# character from it, otherwise the integer comparison (below) will not work.
# See https://stackoverflow.com/questions/19505227/integer-expression-expected-error-in-shell-script/#48705290
android_os_version="${android_os_version//[$'\t\r\n ']}"

echo "The emulator has android_os_version = $android_os_version"
if [ "$android_os_version" -gt 22 ] ; then
    echo "Android 6.0+ emulator detected."
    adb -e shell date $(date +%m%d%H%M%Y.%S)
else
    echo "Android 2/4/5 emulator detected."
    adb -e shell date -s $(date "+%Y%m%d.%H%M%S")
fi
```

Note 1: -e means "emulator", and it works reliably when you have both an emulator and device connected at the same time.

Note 2: The first variation was found by following on from the comment made by Siva Kranthi Kumar, on 9 June 2016. Attempting to use the documentation from adb shell date -? is virtually impossible. It's poorly written and far too difficult to understand.

Title: Set the date from a shell on Android

Body:
Latest instructions, as of September 2022, for Android 9 and above:

Please see this answer: Emulated Android device does not re-sync time/date after restoring snapshot

Old instructions from April 2017, which don't work for Android 9/10/11/12/13 and above:

The following works on Mac OS X to align exactly with your computer's time, and it sets the seconds as well.

For Android 6/7/8 emulators, use this:

adb -e shell date $(date +%m%d%H%M%Y.%S)

For Android 4/5 emulators, use this:

adb -e shell date -s $(date "+%Y%m%d.%H%M%S")

For example, you could use a shell script to detect which Android OS version is running and run the correct adb command appropriately:

#!/bin/bash
android_os_version=$(adb -e shell getprop ro.build.version.sdk)
# The adb function will return a string like "23\n". So you must remove the new line
# character from it, otherwise the integer comparison (below) will not work.
# See https://stackoverflow.com/questions/19505227/integer-expression-expected-error-in-shell-script/#48705290
android_os_version="${android_os_version//[$'\t\r\n ']}"

echo "The emulator has android_os_version = $android_os_version"
if [ "$android_os_version" -gt 22 ] ; then
    echo "Android 6.0+ emulator detected."
    adb -e shell date $(date +%m%d%H%M%Y.%S)
else
    echo "Android 2/4/5 emulator detected."
    adb -e shell date -s $(date "+%Y%m%d.%H%M%S")
fi

Note 1: -e means "emulator", and it works reliably when you have both an emulator and device connected at the same time.

Note 2: The first variation was found by following on from the comment made by Siva Kranthi Kumar, on 9 June 2016. Attempting to use the documentation from adb shell date -? is virtually impossible. It's poorly written and far too difficult to understand.


问:
modalpopupextender resizes the screen?
Can anyone PLEASE explain to me if this is expected behavior.

I have an asp.net site that looks good and all fits on one page so no scrolling is needed.  I am trying to show additional content by using the modalpopupextender when the user clicks a specific button.  The content shown is inside a panel and not shown on load since the display:none is used.

The problem is that when the user clicks the button, the panel content shows BUT it resizes that portion of the screen to be the full width and height of the screen so other elements inside the table view are now shifted way off of the screen.  It also adds a vertical and horizontal scrollbar that scrolls forever and never stops.

I have done hours of research on this and have tried everything I have found by setting the overflow:hidden etc...  The overflow hidden would work except that all of the other elements on the screen get moved way out into no mans land.

The question is, should the modalpopupextender be affecting the  size when the panel is shown and shifting the other elements off of the screen?  It doesn't do when I run the code on another machine, so I am wondering if it could be a bug in the Ajax toolkit version I am using but I am not sure how to check the version that is installed.

Thanks for the ideas.

答:
Just dealt with this; however it was exclusive to IE---FF, Chrome and Opera handled the modal appropriately. I discovered that the DOCTYPE needed to be set to XHTML 1.0 transitional instead of HTML 4 in header:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
</code>```

needs to be

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

Hope this helps.

Title: modalpopupextender resizes the screen?

Body:
Just dealt with this; however it was exclusive to IE---FF, Chrome and Opera handled the modal appropriately. I discovered that the DOCTYPE needed to be set to XHTML 1.0 transitional instead of HTML 4 in header:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

needs to be

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Hope this helps.


问:
How to fix this fibonacci batch lister?
I've researched about operand and operators, set /a , and setlocal EnableDelayedExpansion from this website but still somehow my code ends up telling
me that my operand is missing.

```<code>@echo off
cls
setlocal EnableDelayedExpansion
color 0a
title Fibonacci Lister
:Fibonacci
cls
set /a n1=1
echo %n1%
set /a n2=1
echo %n2%
set /a j=3
:loopfunction
set /a n%j%=!n%j-1%!+!n%j-2%!
echo !n%j%!
set /a j=%j%+1
goto :loopfunction
</code>```

So I wanted to know what is the problem here. It is probably in line 14 where
the code is complex and hard to understand easily.

答:
On line #14, you were using a variables named %j-1% and %j-2% which weren't declared.

Updated Script:

```<code>@echo off
    setlocal EnableDelayedExpansion
    color 0a
    title Fibonacci Lister
:Fibonacci
    set /a n1=1
    echo %n1%
    set /a n2=1
    echo %n2%
    set /a j=3
:loopfunction
    set /a j1=j-1&set /a j2=j-2
    set /a n%j%=!n%j1%!+!n%j2%!
    if "!n%j%!"=="1836311903" goto :EOF
    echo !n%j%!
    set /a j=j+1
goto :loopfunction
</code>```

Title: How to fix this fibonacci batch lister?

Body:
I've researched about operand and operators, set /a , and setlocal EnableDelayedExpansion from this website but still somehow my code ends up telling
me that my operand is missing.

@echo off
cls
setlocal EnableDelayedExpansion
color 0a
title Fibonacci Lister
:Fibonacci
cls
set /a n1=1
echo %n1%
set /a n2=1
echo %n2%
set /a j=3
:loopfunction
set /a n%j%=!n%j-1%!+!n%j-2%!
echo !n%j%!
set /a j=%j%+1
goto :loopfunction

So I wanted to know what is the problem here. It is probably in line 14 where
the code is complex and hard to understand easily.

Body:
On line #14, you were using a variables named %j-1% and %j-2% which weren't declared.

Updated Script:

@echo off
    setlocal EnableDelayedExpansion
    color 0a
    title Fibonacci Lister
:Fibonacci
    set /a n1=1
    echo %n1%
    set /a n2=1
    echo %n2%
    set /a j=3
:loopfunction
    set /a j1=j-1&set /a j2=j-2
    set /a n%j%=!n%j1%!+!n%j2%!
    if "!n%j%!"=="1836311903" goto :EOF
    echo !n%j%!
    set /a j=j+1
goto :loopfunction


问:
How do I instruct artisan to save model to specific directory?
I'm using Laravel 5. I have created a /Models directory under the /App directory, but when generating the models using Artisan it's storing them under the App directory.

I have searched the documentation to try and find how to specify a different path name, but to no avail:

```<code>php artisan make:model TestModel
</code>```

How do I instruct artisan to save the model to specific directory?

答:
In Laravel 5.4 or later

You can create as below

```<code> > php artisan make:model "Models\userModel"
</code>```

here Models is directory name and userModel is model name

Use " (double quotes) or ' (single quotes) to create model

Body:
I'm using Laravel 5. I have created a /Models directory under the /App directory, but when generating the models using Artisan it's storing them under the App directory.

I have searched the documentation to try and find how to specify a different path name, but to no avail:

php artisan make:model TestModel

How do I instruct artisan to save the model to specific directory?

Body:
In Laravel 5.4 or later

You can create as below

 > php artisan make:model "Models\userModel"

here Models is directory name and userModel is model name

Use " (double quotes) or ' (single quotes) to create model


问:
Missing Full Text Index System View In Sql Server 2008
I've been reading about the system view: sys.dm_fts_index_keywords_by_document
on msdn but can't find the view in my 2008 database.  Anyone know if it should be there by default?

答:
It's a TVF not a View.

If you mean you can't see it in Object Explorer look in the master database under Programmability -> Functions -> System Functions -> Table Valued Functions


问:
Trim Java String and use in Sql Where Clause
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

```<code>String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}
</code>```

Result Query:

```<code>SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);
</code>```

I want to get rid of the last comma after 'Broken'

答:
You can use deleteChartAt method:
sb.deleteCharAt(sb.length()-1);

For example:

```<code>String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if(stat!=null) {
    for(int i=0;i<stat.length;i++){
        sb.append("'"+stat[i]+"',");
    }
    sb.deleteCharAt(sb.length()-1); //---------> This will remove the last comma
    String app = "WHERE status in ("+sb.toString()+")";
    String sqlquery = "SELECT * FROM Table "+app+";";
}
</code>```

Body:
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}

Result Query:

SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);

I want to get rid of the last comma after 'Broken'

Body:
You can use deleteChartAt method:
sb.deleteCharAt(sb.length()-1);

For example:

String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if(stat!=null) {
    for(int i=0;i<stat.length;i++){
        sb.append("'"+stat[i]+"',");
    }
    sb.deleteCharAt(sb.length()-1); //---------> This will remove the last comma
    String app = "WHERE status in ("+sb.toString()+")";
    String sqlquery = "SELECT * FROM Table "+app+";";
}


问:
How to check if the name is in a list that is recognized by its similar term in a predicate?
Suppose, I have a prolog predicate such as:

```<code>name(music,[jazz,blues,classical]).
</code>```

and what I want is to check membership of say jazz and return me true if in music?

So far, I did this:

```<code>ismember(X,Y):-imember(X,name(Y,Z)),write(Z).
imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).
</code>```

But it isn't working.

```<code>?- ismember(jazz,music).
false.
</code>```

And it isn't writing the write(Z) part.

答:
In the visible part of the following fragment there is an error. Not only does your program fail, also the following generalization fails:

```
:- op(950, fy, *).
*(_).

ismember(X,Y):-
   imember(_/*<s>X</s>*/,name(_/*<s>Y</s>*/,Z)).

imember(X,[_|Tail]):-
   <b>*</b> <s>imember(X,Tail).</s>
imember(X,[_/*<s>X</s>*/|_]).

?- ismember(X, Y).
```

The generalization has been obtained by replacing some variables by _, and by removing one goal with *. It generalizes as much as possible. That is, any further generalization would make the goal succeed. And there is this nice property that holds in (pure, monotonic) Prolog:

If a generalization fails (for a specific query), then also the original program fails (for that same query).

That's the nice property that somehow establishes causality between a generalized fragment and the original program. If you want to remove the error, something in the generalized program has to be changed. Or conversely: If you make changes that still permit to get the generalization, then you have not fixed the error.

With this in mind,when searching for such a fragment, there is no need to "understand" the actual program. It suffices to guess and generalize mindlessly as long as this is possible.

Now, if we look at that generalization note that
the arguments of ismember/2 are completely ignored!

Body:
Suppose, I have a prolog predicate such as:

name(music,[jazz,blues,classical]).

and what I want is to check membership of say jazz and return me true if in music?

So far, I did this:

ismember(X,Y):-imember(X,name(Y,Z)),write(Z).
imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).

But it isn't working.

?- ismember(jazz,music).
false.

And it isn't writing the write(Z) part.

Body:
In the visible part of the following fragment there is an error. Not only does your program fail, also the following generalization fails:

:- op(950, fy, *).
*(_).

ismember(X,Y):-
   imember(_/*<s>X</s>*/,name(_/*<s>Y</s>*/,Z)).

imember(X,[_|Tail]):-
   * <s>imember(X,Tail).</s>
imember(X,[_/*<s>X</s>*/|_]).

?- ismember(X, Y).

The generalization has been obtained by replacing some variables by _, and by removing one goal with *. It generalizes as much as possible. That is, any further generalization would make the goal succeed. And there is this nice property that holds in (pure, monotonic) Prolog:

If a generalization fails (for a specific query), then also the original program fails (for that same query).

That's the nice property that somehow establishes causality between a generalized fragment and the original program. If you want to remove the error, something in the generalized program has to be changed. Or conversely: If you make changes that still permit to get the generalization, then you have not fixed the error.

With this in mind,when searching for such a fragment, there is no need to "understand" the actual program. It suffices to guess and generalize mindlessly as long as this is possible.

Now, if we look at that generalization note that
the arguments of ismember/2 are completely ignored!