问:
Increasing JVM max heap size in MAC OSX 10.12
I am running MATLAB in my MAC OSX 10.12 (16 GB of memory). I want to increase the JVM 1.8 max heap for using MATLAB without issues. The current size I have is:

```<code> uintx MaxHeapSize    := 4294967296    {product}
</code>```

To increase, I used the following command to set 8GB max memory:

```<code>$java -Xms1g -Xmx8g MATLAB_R2016b.app
</code>```

but I get this error

```<code>Error: Could not find or load main class MATLAB_R2016b.app
</code>```

I don't know how to solve that. I googled it but still not finding the solution. Thank you

答: Try system preferences-> java control panel-> java -> click on view... then modify the Runtime args for the user</p>

Body:
I am running MATLAB in my MAC OSX 10.12 (16 GB of memory). I want to increase the JVM 1.8 max heap for using MATLAB without issues. The current size I have is:

 uintx MaxHeapSize    := 4294967296    {product}

To increase, I used the following command to set 8GB max memory:

$java -Xms1g -Xmx8g MATLAB_R2016b.app

but I get this error

Error: Could not find or load main class MATLAB_R2016b.app

I don't know how to solve that. I googled it but still not finding the solution. Thank you


来源: stackexchange

问:
Redirect old articles to new articles .htaccess
This is a pretty specific question, so no answer on Stack or Google could help me.

Recently I've moved my blog from www.example.com to www.example.com/blog.
On www.example.com I have a landing page, so I need it to be working as well.

I would like to redirect all www.example.com/YYYY/MM/DD/article-name to www.example.com/blog/YYYY/MM/DD/article-name, but at the same time to keep www.example.com intact.

Thank you in advance for your help.

答:
Try this code :)

```<code>RedirectMatch "^/(\d){4}/(\d){2}/(\d){2}/(.+)" "^/blog/$1/$2/$3/$4"
</code>```

If this doesn't do the job, the following line definitely will:

```<code>RedirectMatch "^/(\d)+/(\d)+/(\d)+/(.+)" "^/blog/$1/$2/$3/$4"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this code :)

RedirectMatch "^/(\d){4}/(\d){2}/(\d){2}/(.+)" "^/blog/$1/$2/$3/$4"

If this doesn't do the job, the following line definitely will:

RedirectMatch "^/(\d)+/(\d)+/(\d)+/(.+)" "^/blog/$1/$2/$3/$4"


问:
formatting of prime factorization algorithm
suppose we have following script for  prime factorization

```<code> z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
</code>```

but output of this code is not formatted well,for instance

```<code> >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1
</code>```

how can i do  so  that i got

```<code>30=2^1*3^1*5^1?
</code>```

thanks in advance

答:
Litle modification of your code.</p>

```<code>z=input('enter your number : ');
for ii=2:z
   s=0;
   while z/ii==floor(z/ii) % check if  z is divisible by ii
       z=z/ii;
       s=s+1;
   end
   if s>0
            str += [num2str(ii) '^' num2str(s) ];

        % If z = 1, no more divisions are necessary,
        % thus breaks the loop and quits
        if z == 1
            break
        else
           str+='*';
        end
    end

end
disp(str);
</code>```

Body:
suppose we have following script for  prime factorization

 z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end

but output of this code is not formatted well,for instance

 >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1

how can i do  so  that i got

30=2^1*3^1*5^1?

thanks in advance

Body:
Litle modification of your code.

z=input('enter your number : ');
for ii=2:z
   s=0;
   while z/ii==floor(z/ii) % check if  z is divisible by ii
       z=z/ii;
       s=s+1;
   end
   if s>0
            str += [num2str(ii) '^' num2str(s) ];

        % If z = 1, no more divisions are necessary,
        % thus breaks the loop and quits
        if z == 1
            break
        else
           str+='*';
        end
    end

end
disp(str);


问:
Cannot resolve method "checkSelfPermission"
I am getting the error in the below code:

```<code> if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
}
</code>```

The "checkSelfPermission" is always red indicating some kind of error.

I have imported "import android.support.v4.content.ContextCompat;" already.

The below is my build.gradle content:

```<code>apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"

defaultConfig {
    applicationId "com.xyz.user.abc"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
//    testCompile 'junit:junit:4.12'
compile files('libs/volley.jar')
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.google.android.gms:play-services:10.2.1'
compile 'com.android.support:design:25.3.0'
compile 'junit:junit:4.12'
//    compile 'com.google.android.gms:play-services-appindexing:10.2.1'
//    compile 'com.google.android.gms:play-services:9.8.0'
//    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
compile 'com.android.support:support-v4:25.3.0'
compile files('libs/android-support-v4.jar')
}
</code>```

Any advice will be really appreciated.

I got no idea why this is not working. Kind of a noob at this.

答: Using PermissionChecker.checkSelfPermission instead of ContextCompat.checkSelfPermission corrects the above error.

Body:
I am getting the error in the below code:

 if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
}

The "checkSelfPermission" is always red indicating some kind of error.

I have imported "import android.support.v4.content.ContextCompat;" already.

The below is my build.gradle content:

apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"

defaultConfig {
    applicationId "com.xyz.user.abc"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
//    testCompile 'junit:junit:4.12'
compile files('libs/volley.jar')
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.google.android.gms:play-services:10.2.1'
compile 'com.android.support:design:25.3.0'
compile 'junit:junit:4.12'
//    compile 'com.google.android.gms:play-services-appindexing:10.2.1'
//    compile 'com.google.android.gms:play-services:9.8.0'
//    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
compile 'com.android.support:support-v4:25.3.0'
compile files('libs/android-support-v4.jar')
}

Any advice will be really appreciated.

I got no idea why this is not working. Kind of a noob at this.


问:
How to create a file in resource/view directory Laravel
I am using Laravel 5.0 and I am trying to create a view if is does not exits like so

```<code>if (view()->exists($moduleName.$getCategoryNameToLowerCase))
    {
        //if exist return the view
         return view($moduleName.$getCategoryNameToLowerCase);
    }
    else{
         //else create a view and return it;
         fopen( app_path('../resources/','views/'.$moduleName .'.'. $getCategoryNameToLowerCase . '.blade.php' ), 'w');
         return view($moduleName.$getCategoryNameToLowerCase);
    }
</code>```

But I dont know why I am still not able to go one folder backwards to reach the resource folder it still says this

```<code>fopen(C:\xampp\htdocs\foobar\app/../resources/): failed to open stream: No such file or directory
</code>```

答:
Why use app_path, you can use base_path instead

https://laravel.com/docs/5.4/helpers#method-base-path

Body:
I am using Laravel 5.0 and I am trying to create a view if is does not exits like so

if (view()->exists($moduleName.$getCategoryNameToLowerCase))
    {
        //if exist return the view
         return view($moduleName.$getCategoryNameToLowerCase);
    }
    else{
         //else create a view and return it;
         fopen( app_path('../resources/','views/'.$moduleName .'.'. $getCategoryNameToLowerCase . '.blade.php' ), 'w');
         return view($moduleName.$getCategoryNameToLowerCase);
    }

But I dont know why I am still not able to go one folder backwards to reach the resource folder it still says this

fopen(C:\xampp\htdocs\foobar\app/../resources/): failed to open stream: No such file or directory


问:
Email validation regular expression in cshtml using jquery pops error
While validating email textbox using regex and jquery in shtml page, error pops showing issue with regex as it contains "@" in the regex.</p>

```<code>$(document).ready(function() {

$('#btn-submit').click(function() {

    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;   //"@" in regex is the issue

    var emailaddressVal = $("#UserEmail").val();
    if(emailaddressVal == '') {
        $("#UserEmail").after('<span class="error">Enter email address.</span>');
        hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
        $("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
        hasError = true;
    }

    if(hasError == true) { return false; }

   });
});
</code>```

Body:
While validating email textbox using regex and jquery in shtml page, error pops showing issue with regex as it contains "@" in the regex.

$(document).ready(function() {

$('#btn-submit').click(function() {

    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;   //"@" in regex is the issue

    var emailaddressVal = $("#UserEmail").val();
    if(emailaddressVal == '') {
        $("#UserEmail").after('Enter email address.');
        hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
        $("#UserEmail").after('Enter a valid email address.');
        hasError = true;
    }

    if(hasError == true) { return false; }

   });
});

Body:
use utf-8 code instead of @

/^([\w-\.]+\u0040([\w-]+\.)+[\w-]{2,4})?$/


问:
Demoing XSS Attack in Apache
So I want to create a basic form that is vulnurable to XSS for demo purposes. The code I've written looks like this

```<code><html>
    <body>
        <h1>
            Enter your name
        </h1>
        <form action="xssDemo.php" method="post">
            <label> What is your name? </label>
            <input type="text" name="yourName" size="30">
            <input type="submit" name='Btn' value="Submit">
        </form>
        <?php
            if(isset($_POST["Btn"])) {
                echo "Hello " . $_POST["yourName"];
            }
        ?>
    </body>
</html>
</code>```

The idea is for it to allow me to demo reflected XSS attacks by entering  However, Apache apparently has some built in security against XSS attacks as it filters my attack. How do I shut that off in Apache? Using XAMPP and Chrome if that matters.

Edit: Output is just "Hello "

答: So I ran it in Internet Explorer and it works. </p>

Title: Demoing XSS Attack in Apache

Body:
So I want to create a basic form that is vulnurable to XSS for demo purposes. The code I've written looks like this

            Enter your name

        <form action="xssDemo.php" method="post">
             What is your name?
            <input type="text" name="yourName" size="30">
            <input type="submit" name='Btn' value="Submit">
        </form>
        <?php
            if(isset($_POST["Btn"])) {
                echo "Hello " . $_POST["yourName"];
            }
        ?>

The idea is for it to allow me to demo reflected XSS attacks by entering  However, Apache apparently has some built in security against XSS attacks as it filters my attack. How do I shut that off in Apache? Using XAMPP and Chrome if that matters.

Edit: Output is just "Hello "


问:
how can I create word count output in python just by using reduce function?
I have the following list of tuples: [('a', 1), ('a', 1), ('b', 1), ('c',1), ('a', 1), ('c', 1)]

I would like to know if I can utilize python's reduce function to aggregate them and produce the following output : [('a', 3), ('b', 1), ('c', 2)]

Or if there are other ways, I would like to know as well (loop is fine)

答:
It seems difficult to achieve using reduce, because if both tuples that you "reduce" don't bear the same letter, you cannot compute the result. How to reduce ('a',1) and ('b',1) to some viable result?

Best I could do was l = functools.reduce(lambda x,y : (x[0],x[1]+y[1]) if x[0]==y[0] else x+y,sorted(l))

it got me ('a', 3, 'b', 1, 'c', 1, 'c', 1). So it kind of worked for the first element, but would need more than one pass to do the other ones (recreating tuples and make another similar reduce, well, not very efficient to say the least!).

Anyway, here are 2 working ways of doing it

First, using collections.Counter counting elements of the same kind:

```<code>l = [('a', 1), ('a', 1), ('b', 1), ('c',1), ('a', 1), ('c', 1)]

import collections

c = collections.Counter()
for a,i in l:
    c[a] += i
</code>```

We cannot use listcomp because each element has a weight (even if here it is 1)

Result: a dictionary: Counter({'a': 3, 'c': 2, 'b': 1})

Second option: use itertools.groupby on the sorted list, grouping by name/letter, and performing the sum on the integers bearing the same letter:

```<code>print ([(k,sum(e for _,e in v)) for k,v in itertools.groupby(sorted(l),key=lambda x : x[0])])
</code>```

result:

```<code>[('a', 3), ('b', 1), ('c', 2)]
</code>```

Body:
It seems difficult to achieve using reduce, because if both tuples that you "reduce" don't bear the same letter, you cannot compute the result. How to reduce ('a',1) and ('b',1) to some viable result?

Best I could do was l = functools.reduce(lambda x,y : (x[0],x[1]+y[1]) if x[0]==y[0] else x+y,sorted(l))

it got me ('a', 3, 'b', 1, 'c', 1, 'c', 1). So it kind of worked for the first element, but would need more than one pass to do the other ones (recreating tuples and make another similar reduce, well, not very efficient to say the least!).

Anyway, here are 2 working ways of doing it

First, using collections.Counter counting elements of the same kind:

l = [('a', 1), ('a', 1), ('b', 1), ('c',1), ('a', 1), ('c', 1)]

import collections

c = collections.Counter()
for a,i in l:
    c[a] += i

We cannot use listcomp because each element has a weight (even if here it is 1)

Result: a dictionary: Counter({'a': 3, 'c': 2, 'b': 1})

Second option: use itertools.groupby on the sorted list, grouping by name/letter, and performing the sum on the integers bearing the same letter:

print ([(k,sum(e for _,e in v)) for k,v in itertools.groupby(sorted(l),key=lambda x : x[0])])

result:

[('a', 3), ('b', 1), ('c', 2)]


问:
What is the best comment in source code you have ever encountered?
What is the best comment in source code you have ever encountered?</p>

答:
```<code>i++; //increment i
</code>```

OwnerDisplayName: endpoint

LastEditorDisplayName: Brian

Body: i++; //increment i

ContentLicense: CC BY-SA 2.5


问:
What is relation between tsne and word2vec?
As I know of, tsne is reducing dimension of word vector.

Word2vec is generate word embedding model with huge amount of data.

What is the relation between two?

Does Word2vec use tsne inside?

(I use Word2vec from Gensim)

答:
Internally they both use gradient-descent to reach their final optimized states. And both can be considered dimensionality-reduction operations. But, word2vec does not internally use t-SNE (or vice-versa).

t-SNE ("t-distributed stochastic neighbor embedding") typically reduces many-dimensional data to 2- or 3-dimensions, for the purposes of plotting a visualization. It involves learning a mapping from the original dimensionality, to the fewer dimensions, which still keeps similar points near each other.

word2vec takes many text examples and learns a shallow neural-network that's good at predicting words from nearby words. A particular layer of that neural-network's weights, which represent individual words, then becomes the learned N-dimensional word-vectors, with the value of N often 100 to 600.

(There's an alternative way to create word-vectors called GLoVE that works a little more like t-SNE, in that it trains directly from the high-dimensional co-occurrence matrix of words, rather than from the many in-context co-occurrence examples. But it's still not t-SNE itself.)

You could potentially run t-SNE with a target dimensionality of 100-400. But since that end-result wouldn't yet yield nice plots, the maintenance of 'nearness' that's central to t-SNE won't have delivered its usual intended benefit.

You could potentially learn word2vec (or GLoVE) vectors of just 2- or 3-dimensions, but most of the useful similarities/arrangements that people seek from word-vectors would be lost in the crowding. And in a plot, you'd probably not see as strong visual 'clumping' of related-word categories, because t-SNE's specific high-to-low dimensionality nearness-preservation goal wasn't applied.


问:
unable to load database value in php in ajax
I am entry level developer in PHP and have no knowledge in PHP, i am trying to call database values on selecting a drop down menu, have done this so far with the help of tutorial,.. the problem is when i select 1st drop down the second drop down is getting values from DB, but when i select option from 2nd drop down menu, i am not getting any data displayed on page. Nothing Happens after selecting an option from 2nd drop down.

```<code><?php
include '../connect.php';
 $unm=htmlentities($_SESSION['username']);
?>

<html>
<head>
<title> User Panel</title></head>

<body background="../image/pencilback.jpg">
<div id="welcome"><?php
echo '<align="right">'.'<h3>'."Welcome ".$unm.'</h3>';
?></div>

<link rel="stylesheet" type="text/css" href="../css/heading.css">
<table border="0" width="50%" height="150px" align="center" >
<tr width="100%" height="200px" > <td colspan="3"> <img src="../image/banner.jpg"> </td>  </tr>
</table>

<table id="tableborder" border="0" width="83%" height="40px" align="center" bgcolor="#BDBDBD" >

<td align="center"><a href="userpanel.php"><b> Take a Test</b></a> </td>
<td align="center"><a href="myaccount.php"><b> My Account Details</b> </td>
<td align="center"><a href="testhistory.php"><b> View Test History </b> </td>
<td align="center"><a href="feedback.php"><b> Give Feedback</b> </td>
<td align="center"><a href="../logout.php"><b> Logout</b> </td> </td>  </tr>
</table>
<form method="POST" action="">
 <div id="viewset"><center>
  Select Desired Test </center> <br></div><br><br><br><br><br><br>
 <table border="1px" align="center" cellspacing="10px" cellpadding="10px">
 <tr> <td> <select name="tstcat" id="countrydd" onChange="change_country()">
<option> Select Test Category</option>
<?php
$res=mysqli_query($connection,"select * from sub");
while($row=mysqli_fetch_array($res))
{
    ?>
    <option value="<?php echo $row["subname"]; ?>"> <?php echo $row["subname"]; ?> </option>
<?php
    }
?>

</select>
</td>
<td>
 <div id="state" align="center">
<select id="details" onChange="display_details()">
<option>Select Test</option>
</select>

</div>
 </tr> </td></table>
<br>

<div id="display">
<table border="1px" height="100px" width="30%" align="center">
<tr style=color:maroon> <th> Test Name </th> <th> No. of Questions </th> <th> Duration </th> </tr>
<tr> <td> </td> <td> </td> <td> </td> </tr>
</table>

</div>

<center> <input type="submit" name="submit" value="Go"></center>

<?php
if(isset($_POST['submit']))
{
$tstct=$_POST['tstcat'];
$tnm=$_POST['testid'];
$_SESSION['testname']=$tnm;
$_SESSION['testcatg']=$tsc;
header('location:teststart.php');
}
?>

 </div>
 </form>

 <script type="text/javascript">

 //========== FOR DROPDOWN SELECTION

 function change_country()
 {
     var xmlhttp=new XMLHttpRequest();
     xmlhttp.open("GET","ajax.php?category="+document.getElementById("countrydd").value,false);
     xmlhttp.send(null);
     document.getElementById("state").innerHTML=xmlhttp.responseText;

 }

  //========== TO LOAD TEST DETAILS

 function display_details()
 {
     var xmlhttp=new XMLHttpRequest();
     xmlhttp.open("GET","ajax2.php?testname="+document.getElementById("details").value,false);
     xmlhttp.send(null);
     document.getElementById("display").innerHTML=xmlhttp.responseText;

 }

 </script>

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

AJAX.PHP

```<code><?php
include '../connect.php';
$category=$_GET["category"];

if($category!="")
{
$res=mysqli_query($connection,"select * from test_detail where     test_category='$category'");
echo "<select name='testid' onchange='change_test()'>";
while($row=mysqli_fetch_array($res))
{
    ?>
    <option value="<?php echo $row["test_name"];?>"> <?php echo $row["test_name"];?>  </option>
    <?php
}
echo "</select>";
}
?>
</code>```

AJAX 2.PHP

```<code><?php
include '../connect.php';
$tstname=$_GET["testname"];

if($tstname!="")
{
$res1=mysqli_query($connection,"select * from test_detail where  test_name='$tstname'");
echo "<table>";
while($row1=mysqli_fetch_array($res1))
{
    ?>

    <tr> <td> <?php echo $row1["test_name"];?>  </td>
    <td> <?php echo $row1["total_ques"];?> </td>
    <td> <?php echo $row1["test_dur"];?> </td> </tr>
    <?php
}
echo "</table>";
}
    ?>
</code>```

答:
I would recommend you to check three things.

in the select that is inside to the div with id #state, you have an onChange calling the javascript function 'display_details()' which you use to load the table element with detail data. But when you return the select from AJAX.PHP the onchange event has another function 'change_test()', it should be 'display_details()'

When you insert dynamically new html elements in a document, normally you have to use dynamic event binding to attach the event handlers. For this I recommend you to use jquery, this link explain how Event binding on dynamically created elements

to make to ajax request jquery is very good library, but if you want to use the XMLHttpRequest object , It will be a good idea check the status of the response:

if (xmlhttp.status == 200){
    document.getElementById("state").innerHTML=xmlhttp.responseText;
}else{
     // Handle the error;
}

Body:
I am entry level developer in PHP and have no knowledge in PHP, i am trying to call database values on selecting a drop down menu, have done this so far with the help of tutorial,.. the problem is when i select 1st drop down the second drop down is getting values from DB, but when i select option from 2nd drop down menu, i am not getting any data displayed on page. Nothing Happens after selecting an option from 2nd drop down.

<?php
include '../connect.php';
 $unm=htmlentities($_SESSION['username']);
?>

<title> User Panel</title>

<?php
echo '<align="right">'.'
'."Welcome ".$unm.'
';
?>

<link rel="stylesheet" type="text/css" href="../css/heading.css">

 Take a Test
 My Account Details
 View Test History
 Give Feedback
 Logout

<form method="POST" action="">

  Select Desired Test

  <select name="tstcat" id="countrydd" onChange="change_country()">
<option> Select Test Category</option>
<?php
$res=mysqli_query($connection,"select * from sub");
while($row=mysqli_fetch_array($res))
{
    ?>
    <option value="<?php echo $row["subname"]; ?>"> <?php echo $row["subname"]; ?> </option>
<?php
    }
?>

</select>

<select id="details" onChange="display_details()">
<option>Select Test</option>
</select>

  Test Name 	  No. of Questions 	  Duration

 <input type="submit" name="submit" value="Go">

<?php
if(isset($_POST['submit']))
{
$tstct=$_POST['tstcat'];
$tnm=$_POST['testid'];
$_SESSION['testname']=$tnm;
$_SESSION['testcatg']=$tsc;
header('location:teststart.php');
}
?>

 </form>

AJAX.PHP

<?php
include '../connect.php';
$category=$_GET["category"];

if($category!="")
{
$res=mysqli_query($connection,"select * from test_detail where     test_category='$category'");
echo "<select name='testid' onchange='change_test()'>";
while($row=mysqli_fetch_array($res))
{
    ?>
    <option value="<?php echo $row["test_name"];?>"> <?php echo $row["test_name"];?>  </option>
    <?php
}
echo "</select>";
}
?>

AJAX 2.PHP

<?php
include '../connect.php';
$tstname=$_GET["testname"];

if($tstname!="")
{
$res1=mysqli_query($connection,"select * from test_detail where  test_name='$tstname'");
echo "
";
while($row1=mysqli_fetch_array($res1))
{
    ?>

  <?php echo $row1["test_name"];?>
     <?php echo $row1["total_ques"];?>
     <?php echo $row1["test_dur"];?>

    <?php
}
echo "
";
}
    ?>


问:
Mypy "class module" annotation
I have a function load_config that loads and returns a python module:

```<code>import imp

def load_config(path: str):
    return imp.load_source('config', path)

print(type(load_config('config.py')))
</code>```

This snippet prints <class 'module'>.

How do I annotate load_config return value with Mypy?

答:
The correct annotation is:

```<code>import imp
import types

def load_config(path: str) -> types.ModuleType:
  return imp.load_source('config', path)
</code>```

However, there's an open issue to fix it in the current version of mypy.

Title: Mypy "class module" annotation

Body:
I have a function load_config that loads and returns a python module:

import imp

def load_config(path: str):
    return imp.load_source('config', path)

print(type(load_config('config.py')))

This snippet prints <class 'module'>.

How do I annotate load_config return value with Mypy?

Body:
The correct annotation is:

import imp
import types

def load_config(path: str) -> types.ModuleType:
  return imp.load_source('config', path)

However, there's an open issue to fix it in the current version of mypy.


问:
Development build of pandas giving importerror: C extension: 'hashtable' not built on python 3.4 (anaconda)
Try to do a development build with 3.4 (have previously managed in 2.7). Python is just an anaconda installation on osx10.10. I can get

I:

git cloned pandas

ran python setup.py build_ext --inplace (got no errors)

ran python setup.py develop.

But when I try and import pandas I get:

```<code>import pandas as pd
Traceback (most recent call last):

  File "<ipython-input-2-af55e7023913>", line 1, in <module>
    import pandas as pd

  File "/Users/Nick/github/pandas/pandas/__init__.py", line 13, in <module>
    "extensions first.".format(module))

ImportError: C extension: 'hashtable' not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first.
</code>```

Note that when I do build_ext I get the following (apparently fine) output:

```<code>pandas(master)$python setup.py build_ext --inplace

running build_ext
skipping 'pandas/index.c' Cython extension (up-to-date)
skipping 'pandas/lib.c' Cython extension (up-to-date)
skipping 'pandas/parser.c' Cython extension (up-to-date)
skipping 'pandas/src/period.c' Cython extension (up-to-date)
skipping 'pandas/hashtable.c' Cython extension (up-to-date)
skipping 'pandas/algos.c' Cython extension (up-to-date)
skipping 'pandas/tslib.c' Cython extension (up-to-date)
skipping 'pandas/src/sparse.c' Cython extension (up-to-date)
skipping 'pandas/src/testing.c' Cython extension (up-to-date)
skipping 'pandas/msgpack.cpp' Cython extension (up-to-date)
</code>```

Further, I can get pandas installed if I run conda install pandas, but would really like a development environment for code development.

Similar to this, which looked unsolved and this

答:
I solved it reinstalling pandas with this command:

```<code>conda install pandas
</code>```

Everything was working fine, but I installed something using pip and started having problems. This solved it.

Body:
Try to do a development build with 3.4 (have previously managed in 2.7). Python is just an anaconda installation on osx10.10. I can get

I:

git cloned pandas

ran python setup.py build_ext --inplace (got no errors)

ran python setup.py develop.

But when I try and import pandas I get:

import pandas as pd
Traceback (most recent call last):

  File "<ipython-input-2-af55e7023913>", line 1, in <module>
    import pandas as pd

  File "/Users/Nick/github/pandas/pandas/__init__.py", line 13, in <module>
    "extensions first.".format(module))

ImportError: C extension: 'hashtable' not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first.

Note that when I do build_ext I get the following (apparently fine) output:

pandas(master)$python setup.py build_ext --inplace

running build_ext
skipping 'pandas/index.c' Cython extension (up-to-date)
skipping 'pandas/lib.c' Cython extension (up-to-date)
skipping 'pandas/parser.c' Cython extension (up-to-date)
skipping 'pandas/src/period.c' Cython extension (up-to-date)
skipping 'pandas/hashtable.c' Cython extension (up-to-date)
skipping 'pandas/algos.c' Cython extension (up-to-date)
skipping 'pandas/tslib.c' Cython extension (up-to-date)
skipping 'pandas/src/sparse.c' Cython extension (up-to-date)
skipping 'pandas/src/testing.c' Cython extension (up-to-date)
skipping 'pandas/msgpack.cpp' Cython extension (up-to-date)

Further, I can get pandas installed if I run conda install pandas, but would really like a development environment for code development.

Similar to this, which looked unsolved and this

Body:
I solved it reinstalling pandas with this command:

conda install pandas

Everything was working fine, but I installed something using pip and started having problems. This solved it.


问:
i need an applescript to open safari in full screen an to hide the toolbar on mavericks
I need an applescript to open safari in full screen an to hide the toolbar on mavericks.

it sounds easy but it isnt!

i need to open safari then open google in full screen mode an then hide the toolbar.

it would be the equivilent to the below sample but instead for safari

tell application "Google Chrome"
    open location "http://internet.ceo.wa.edu.au/Pages/default.aspx"
end tell

tell application "Google Chrome" to activate
tell application "System Events"
    keystroke "f" using {command down, shift down}
end tell

答:
Easy way:</p>

```<code>set MyApps to {"Google Chrome", "Skype", "Finder"}

repeat with MyApp in MyApps

    tell application MyApp

        activate

        delay 3

        tell application "System Events" to tell process MyApp

            set value of attribute "AXFullScreen" of window 1 to true

        end tell

    end tell

end repeat
</code>```

Body:
Easy way:

set MyApps to {"Google Chrome", "Skype", "Finder"}

repeat with MyApp in MyApps

    tell application MyApp

        activate

        delay 3

        tell application "System Events" to tell process MyApp

            set value of attribute "AXFullScreen" of window 1 to true

        end tell

    end tell

end repeat

ContentLicense: CC BY-SA 4.0


问:
Angular 2 - How to enable / disable contenteditable via click?
I would like to disable and enable the edit mode on the element I click
I have a loop that runs through and displays me widgets.

```<code>                <div *ngFor="let widget of container.widgets; let j = index"
                     class="item-column list-group-item "
                     dnd-sortable [sortableIndex]="j"
                     [dragEnabled]="!dragOperation"
                     (onDragEnter)="onDragEnter(widget, $event)"

                     (dblclick)="eventEmitDoubleClick(widget, container.widgets)"
             contenteditable="false"
                     >

                         <div class="item-item" >
                             {{widget.name}}
                        </div>

                </div>
</code>```

My click event

```<code>dragOperation: Boolean = false;
contenteditable: Boolean = false;
eventEmitDoubleClick(widget, containerWidgets) {

        if(this.dragOperation){
          this.dragOperation = false;
          this.contenteditable = true;
        }else{
         this.dragOperation = true;
          this.contenteditable = false;
        }

    }
</code>```

Can anyone help?

答:
```<code><div ... [contenteditable]="contenteditable"
</code>```

Body:
I would like to disable and enable the edit mode on the element I click
I have a loop that runs through and displays me widgets.

                             {{widget.name}}

My click event

dragOperation: Boolean = false;
contenteditable: Boolean = false;
eventEmitDoubleClick(widget, containerWidgets) {

        if(this.dragOperation){
          this.dragOperation = false;
          this.contenteditable = true;
        }else{
         this.dragOperation = true;
          this.contenteditable = false;
        }

    }

Can anyone help?


问:
How to log the latest git commit hash in Eclipse?
I am new to Git. I have developed an app in Java. The app logs every information in a text file during the execution. I have committed the application using Git. Now I want to print the latest Git commit hash value in the log file.

E.g.: Inside mysteps.log file:

Start of logging...

Please instruct me how to achieve this? Thanks in advance.. :)

答:
```<code>Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("git rev-parse HEAD");
try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(process.getInputStream())
)) {
    String revision = reader.readLine();
    // log the revision here
}
</code>```

Attention: Don't use this code in production. It is environment dependent which means that it will fail in case if Git is not installed or context is not in git repository.

To be able to use it in production you have to patch the revision into your artifact (eg. into jar archive). Usually it is done as a part of automated build by a build system (eg. gradle, maven, ant). For instance during maven build you might create new file with git-hash and pack it into the jar, then during runtime you can read the file whenever you need.

Body:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("git rev-parse HEAD");
try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(process.getInputStream())
)) {
    String revision = reader.readLine();
    // log the revision here
}

Attention: Don't use this code in production. It is environment dependent which means that it will fail in case if Git is not installed or context is not in git repository.

To be able to use it in production you have to patch the revision into your artifact (eg. into jar archive). Usually it is done as a part of automated build by a build system (eg. gradle, maven, ant). For instance during maven build you might create new file with git-hash and pack it into the jar, then during runtime you can read the file whenever you need.


问:
Time complexity of recursive algorithm for denomination task
I calculate all possible variants of input number k for 1, 2 or 5 numbers. It's easy algorithm for understanding:

```<code>//1,2,5
func foo(k: Int, result: [Int] = []) {
    if k == 0 {
        print(result)
        return
    }

    var one = result
    one.append(1)
    foo(k: k-1, result: one)

    if k >= 2 {
        var two = result
        two.append(2)
        foo(k: k-2, result: two)
    }

    if k >= 5 {
        var five = result
        five.append(5)
        foo(k: k-5, result: five)
    }
}
</code>```

So, it works. My question is what is complexity (big O) of this algorithm?
I assume it's 3^k, because of 3 recursive calls inside.
Please prove or explain your opinion.

答:
You are right, and there are two keys to the analysis. Since you define the function with k as its argument, then let's write down the complexity in terms of k:

For k >= 5, foo solving the problem of size kis reduced to calling itself 3 times to solve smaller problems, each of size k - c, where c is a constant (in your case at most 5). Thus, you can write down the time complexity of foo as:

```<code>3 * f(k-1) >= f(k) >= 3 * f(k-5)
</code>```

and the solution is clearly f(k) = O(3^k), which you can proof for example by measuring the number of leaves in the recursion tree.

Body:
I calculate all possible variants of input number k for 1, 2 or 5 numbers. It's easy algorithm for understanding:

//1,2,5
func foo(k: Int, result: [Int] = []) {
    if k == 0 {
        print(result)
        return
    }

    var one = result
    one.append(1)
    foo(k: k-1, result: one)

    if k >= 2 {
        var two = result
        two.append(2)
        foo(k: k-2, result: two)
    }

    if k >= 5 {
        var five = result
        five.append(5)
        foo(k: k-5, result: five)
    }
}

So, it works. My question is what is complexity (big O) of this algorithm?
I assume it's 3^k, because of 3 recursive calls inside.
Please prove or explain your opinion.

Body:
You are right, and there are two keys to the analysis. Since you define the function with k as its argument, then let's write down the complexity in terms of k:

For k >= 5, foo solving the problem of size kis reduced to calling itself 3 times to solve smaller problems, each of size k - c, where c is a constant (in your case at most 5). Thus, you can write down the time complexity of foo as:

3 * f(k-1) >= f(k) >= 3 * f(k-5)

and the solution is clearly f(k) = O(3^k), which you can proof for example by measuring the number of leaves in the recursion tree.


问:
ionic 1 check internet when app is working
I try to check if internet is working when I run the app. It works well on my computer but after compiling apk and running the app on my smartphone, this code doesn't work properly; could you help me ?

.run(function($window, $rootScope) {
 console.log($cordovaNetwork.getNetwork());
 $rootScope.online = navigator.onLine;
 $window.addEventListener("offline", function() {
  $rootScope.$apply(function() {
   $rootScope.online = false;
  });
 }, false);
 $window.addEventListener("online", function() {
  $rootScope.$apply(function() {
   $rootScope.online = true;
  });
 }, false);
})```

regards

答:
Its not good practice to use navigator.onLine on Android devices. Each device uses different version of Chromium and on some devices it will not work as expected.

I suggest you to use org.apache.cordova.network-information plugin that calls native API for network information (advantage)

Body:
I try to check if internet is working when I run the app. It works well on my computer but after compiling apk and running the app on my smartphone, this code doesn't work properly; could you help me ?

.run(function($window, $rootScope) {
 console.log($cordovaNetwork.getNetwork());
 $rootScope.online = navigator.onLine;
 $window.addEventListener("offline", function() {
  $rootScope.$apply(function() {
   $rootScope.online = false;
  });
 }, false);
 $window.addEventListener("online", function() {
  $rootScope.$apply(function() {
   $rootScope.online = true;
  });
 }, false);
})

regards


问:
Do you need to use Bootstrap's "container" and "row" if your content is to span the whole width?
I think the standard of Bootstrap 3 and 4 is

```<code><div class="container">
    <div class="row">
        <div class="col-md-4"> ... </div>
        <div class="col-md-8"> ... </div>   <!-- just add up to 12 -->
    </div>
</div>
</code>```

But what if you have a div, table, form, or any element, that you plan to just let it span the whole width?  Then do you need the container or row or col-md-12 at all, for the whole page to display well under the styling rules of Bootstrap 3 and 4?

P.S. if possible, please point to or quote the official Bootstrap docs related to this.

答:
Short answer: you do need to use container, but you don't need to use row.

You can put elements directly in the container or container-fluid. You aren't required to use the grid (.row and .col-*), and the container alone can be used as a container of content. Only use the grid when you need the responsive 12-unit structure.

For example, this is valid Bootstrap...

```<code><div class="container">
   <h2>Hello World</h2>
   <p class="lead">Some other content...</p>
</div>
</code>```

From the Bootstrap docs...

"Bootstrap requires a containing element to wrap site contents and
house our grid system."

So, the purpose of container is two-fold: 1) to "house the grid system", and 2) to "wrap site contents". However, when you do use the grid (.row and .col-*), a container is required to wrap the .row.

Even the basic starter template utilizes container without the grid.

In summary...

You can use .container or .container-fluid alone to contain elements and page content.

If you use the grid (.row and .col-*), .row must be inside a .container or .container-fluid, and .col-* must be inside a .row.

Body:
I think the standard of Bootstrap 3 and 4 is

 ...

 ...

But what if you have a div, table, form, or any element, that you plan to just let it span the whole width?  Then do you need the container or row or col-md-12 at all, for the whole page to display well under the styling rules of Bootstrap 3 and 4?

P.S. if possible, please point to or quote the official Bootstrap docs related to this.

Body:
Short answer: you do need to use container, but you don't need to use row.

You can put elements directly in the container or container-fluid. You aren't required to use the grid (.row and .col-*), and the container alone can be used as a container of content. Only use the grid when you need the responsive 12-unit structure.

For example, this is valid Bootstrap...

<div class="container">
   <h2>Hello World</h2>
   <p class="lead">Some other content...</p>
</div>

From the Bootstrap docs...

"Bootstrap requires a containing element to wrap site contents and
house our grid system."

So, the purpose of container is two-fold: 1) to "house the grid system", and 2) to "wrap site contents". However, when you do use the grid (.row and .col-*), a container is required to wrap the .row.

Even the basic starter template utilizes container without the grid.

In summary...

You can use .container or .container-fluid alone to contain elements and page content.

If you use the grid (.row and .col-*), .row must be inside a .container or .container-fluid, and .col-* must be inside a .row.


问:
regarding the ValueError: If `inputs` don't all have same shape and dtype or the shape
There is a program that defines the loss function as follows:

```<code>def loss(hypes, decoded_logits, labels):
"""Calculate the loss from the logits and the labels.

Args:
  logits: Logits tensor, float - [batch_size, NUM_CLASSES].
  labels: Labels tensor, int32 - [batch_size].

Returns:
  loss: Loss tensor of type float.
"""
logits = decoded_logits['logits']
with tf.name_scope('loss'):
    logits = tf.reshape(logits, (-1, 2))
    shape = [logits.get_shape()[0], 2]
    epsilon = tf.constant(value=hypes['solver']['epsilon'])
    # logits = logits + epsilon
    labels = tf.to_float(tf.reshape(labels, (-1, 2)))

    softmax = tf.nn.softmax(logits) + epsilon

    if hypes['loss'] == 'xentropy':
        cross_entropy_mean = _compute_cross_entropy_mean(hypes, labels,
                                                         softmax)
    elif hypes['loss'] == 'softF1':
        cross_entropy_mean = _compute_f1(hypes, labels, softmax, epsilon)

    elif hypes['loss'] == 'softIU':
        cross_entropy_mean = _compute_soft_ui(hypes, labels, softmax,
                                              epsilon)

    reg_loss_col = tf.GraphKeys.REGULARIZATION_LOSSES

    print('******'*10)
    print('loss type ',hypes['loss'])
    print('type ', type(tf.get_collection(reg_loss_col)))
    print( "Regression loss collection: {}".format(tf.get_collection(reg_loss_col)))
    print('******'*10)

    weight_loss = tf.add_n(tf.get_collection(reg_loss_col))

    total_loss = cross_entropy_mean + weight_loss

    losses = {}
    losses['total_loss'] = total_loss
    losses['xentropy'] = cross_entropy_mean
    losses['weight_loss'] = weight_loss

return losses
</code>```

Running the program raises the following error message

```<code>File "/home/ decoder/kitti_multiloss.py", line 86, in loss
    name='reg_loss')
  File "/devl /tensorflow/tf_0.12/lib/python3.4/site-packages/tensorflow/python/ops/math_ops.py", line 1827, in add_n
    raise ValueError("inputs must be a list of at least one Tensor with the "
ValueError: inputs must be a list of at least one Tensor with the same dtype and shape
</code>```

I checked the function of tf.add_n , its implementation is as follows. My question is that how to check the first parameter tf.get_collection(reg_loss_col) in tf.add_n and print its information to figure out why the error message was generated?

```<code>def add_n(inputs, name=None):
  """Adds all input tensors element-wise.
  Args:
    inputs: A list of `Tensor` objects, each with same shape and type.
    name: A name for the operation (optional).
  Returns:
    A `Tensor` of same shape and type as the elements of `inputs`.
  Raises:
    ValueError: If `inputs` don't all have same shape and dtype or the shape
    cannot be inferred.
  """
  if not inputs or not isinstance(inputs, (list, tuple)):
    raise ValueError("inputs must be a list of at least one Tensor with the "
                     "same dtype and shape")
  inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
  if not all(isinstance(x, ops.Tensor) for x in inputs):
    raise ValueError("inputs must be a list of at least one Tensor with the "
                     "same dtype and shape")
</code>```

答:
Why do you even need to get into add_n to see  what tf.get_collection(reg_loss_col) is? You can have tmp = tf.get_collection(reg_loss_col) and then see its type. BTW, it looks like that you don't have any regularized loss in your graph and in that case tf.get_collection(reg_loss_col) will return an empty list.

To see the type of an object in Python You can use the built-in function type. For example to see type of tmp: print type(tmp)

Body:
There is a program that defines the loss function as follows:

def loss(hypes, decoded_logits, labels):
"""Calculate the loss from the logits and the labels.

Args:
  logits: Logits tensor, float - [batch_size, NUM_CLASSES].
  labels: Labels tensor, int32 - [batch_size].

Returns:
  loss: Loss tensor of type float.
"""
logits = decoded_logits['logits']
with tf.name_scope('loss'):
    logits = tf.reshape(logits, (-1, 2))
    shape = [logits.get_shape()[0], 2]
    epsilon = tf.constant(value=hypes['solver']['epsilon'])
    # logits = logits + epsilon
    labels = tf.to_float(tf.reshape(labels, (-1, 2)))

    softmax = tf.nn.softmax(logits) + epsilon

    if hypes['loss'] == 'xentropy':
        cross_entropy_mean = _compute_cross_entropy_mean(hypes, labels,
                                                         softmax)
    elif hypes['loss'] == 'softF1':
        cross_entropy_mean = _compute_f1(hypes, labels, softmax, epsilon)

    elif hypes['loss'] == 'softIU':
        cross_entropy_mean = _compute_soft_ui(hypes, labels, softmax,
                                              epsilon)

    reg_loss_col = tf.GraphKeys.REGULARIZATION_LOSSES

    print('******'*10)
    print('loss type ',hypes['loss'])
    print('type ', type(tf.get_collection(reg_loss_col)))
    print( "Regression loss collection: {}".format(tf.get_collection(reg_loss_col)))
    print('******'*10)

    weight_loss = tf.add_n(tf.get_collection(reg_loss_col))

    total_loss = cross_entropy_mean + weight_loss

    losses = {}
    losses['total_loss'] = total_loss
    losses['xentropy'] = cross_entropy_mean
    losses['weight_loss'] = weight_loss

return losses

Running the program raises the following error message

File "/home/ decoder/kitti_multiloss.py", line 86, in loss
    name='reg_loss')
  File "/devl /tensorflow/tf_0.12/lib/python3.4/site-packages/tensorflow/python/ops/math_ops.py", line 1827, in add_n
    raise ValueError("inputs must be a list of at least one Tensor with the "
ValueError: inputs must be a list of at least one Tensor with the same dtype and shape

I checked the function of tf.add_n , its implementation is as follows. My question is that how to check the first parameter tf.get_collection(reg_loss_col) in tf.add_n and print its information to figure out why the error message was generated?

def add_n(inputs, name=None):
  """Adds all input tensors element-wise.
  Args:
    inputs: A list of `Tensor` objects, each with same shape and type.
    name: A name for the operation (optional).
  Returns:
    A `Tensor` of same shape and type as the elements of `inputs`.
  Raises:
    ValueError: If `inputs` don't all have same shape and dtype or the shape
    cannot be inferred.
  """
  if not inputs or not isinstance(inputs, (list, tuple)):
    raise ValueError("inputs must be a list of at least one Tensor with the "
                     "same dtype and shape")
  inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
  if not all(isinstance(x, ops.Tensor) for x in inputs):
    raise ValueError("inputs must be a list of at least one Tensor with the "
                     "same dtype and shape")


问:
How do you select the highest of a count()?
I've wrote a query which shows the reasons and the amount of the selected reasons people cancel their orders per state per year:

```<code>SELECT   DISTINCT LEFT(k.wijk,2) AS state,
         YEAR(a.eind_dt) AS year,
         opzegreden AS reason,
         count(*) AS amount
FROM     klant AS k
JOIN     abon AS a
ON       k.klant_id = a.lezer
WHERE    opzegreden IS NOT NULL
GROUP BY LEFT(k.wijk,2), year(a.eind_dt), opzegreden
ORDER BY state, year, reason;
</code>```

Which gives this result atm:
Current result

Now the only thing I can't seem to make happen is to show the reason which is picked the most per state per year. Which would be reason nr 14 with my current result.

Can someone please help me?

答:
You could try this:-</p>

```<code>    SELECT
      state,
      year,
      reason,
      max(amount)
    FROM
    (
    SELECT DISTINCT LEFT(k.wijk,2) AS state,
    YEAR(a.eind_dt) AS year,
    opzegreden AS reason, count(*) AS amount
    FROM klant AS k
    JOIN abon AS a
    ON k.klant_id = a.lezer
    WHERE opzegreden IS NOT NULL
    GROUP BY LEFT(k.wijk,2), year(a.eind_dt), opzegreden
    ORDER BY state, year, reason
    ) d
GROUP BY
  state,
  year,
  reason;
</code>```

Body:
I've wrote a query which shows the reasons and the amount of the selected reasons people cancel their orders per state per year:

SELECT   DISTINCT LEFT(k.wijk,2) AS state,
         YEAR(a.eind_dt) AS year,
         opzegreden AS reason,
         count(*) AS amount
FROM     klant AS k
JOIN     abon AS a
ON       k.klant_id = a.lezer
WHERE    opzegreden IS NOT NULL
GROUP BY LEFT(k.wijk,2), year(a.eind_dt), opzegreden
ORDER BY state, year, reason;

Which gives this result atm:
Current result

Now the only thing I can't seem to make happen is to show the reason which is picked the most per state per year. Which would be reason nr 14 with my current result.

Can someone please help me?

Body:
You could try this:-

    SELECT
      state,
      year,
      reason,
      max(amount)
    FROM
    (
    SELECT DISTINCT LEFT(k.wijk,2) AS state,
    YEAR(a.eind_dt) AS year,
    opzegreden AS reason, count(*) AS amount
    FROM klant AS k
    JOIN abon AS a
    ON k.klant_id = a.lezer
    WHERE opzegreden IS NOT NULL
    GROUP BY LEFT(k.wijk,2), year(a.eind_dt), opzegreden
    ORDER BY state, year, reason
    ) d
GROUP BY
  state,
  year,
  reason;


问:
Configure log4net or NLog with XML from code
Recently I have been working on a project where, among other things, we want to provide a centralized configuration system.  We are using WCF, Silverlight, C#, etc to create a distributed system of services and clients.  One of the things that we will want to configure is logging.  Obviously, we can configure log4net or NLog via the app.config or via a separate logging configuration file.  We can also configure via code.  I wanted to see if it was possible to configure via XML from code.  In other words, imagine that you have in memory (maybe read from a database?) the entire XML required to configure either logging framework.  Can it be done?  Is it possible to configure log4net and/or NLog via a string containing a correctly formed (in the context of the particular logging framework) as opposed to reading from the file or via "conventional" API configuration?

I have figured out how to do it for each of these logging frameworks.  I'm not sure that we will actually use it, but I thought that I would share it here on SO, just in case anyone else might find it useful.  Also, feel free to comment on the advisability (or not) of configuring the logging frameworks this way.

Two obvious potential issues that I can think of are:

It could be difficult to construct valid XML (or enter it in the database).  My first guess is that one would define the XML that same way one would today.  Put it in a app.config (or external config) file and then run a test program to verify that the XML yields the expected results.

How easy or difficult (or impossible) will it be to update the XML in the database and then have the program/service/whatever react to the change (like using log4net's ConfigureAndWatch option)?  I am not as interested in the mechanics of how a program or service would know that the XML has been updated.  Let's just assume that the program will check the database periodically.  Given a new XML string, it is easy enough to reconfigure the logging frameworks.

I will post my technique as an answer to this question.

答:
Configure log4net via XML in code:

```<code>  string xml =
  @"<log4net>
    <appender name='file1' type='log4net.Appender.RollingFileAppender'>
      <!-- Log file locaation -->
      <param name='File' value='log4net.log'/>
      <param name='AppendToFile' value='true'/>
      <!-- Maximum size of a log file -->
      <maximumFileSize value='2KB'/>
      <!--Maximum number of log file -->
      <maxSizeRollBackups value='8'/>
      <!--Set rolling style of log file -->
      <param name='RollingStyle' value='Composite'/>
      <param name='StaticLogFileName' value='false'/>
      <param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <!-- Appender layout fix to view in console-->
    <appender name='console' type='log4net.Appender.ConsoleAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='Header' value='[Header]\r\n'/>
        <param name='Footer' value='[Footer]\r\n'/>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <appender name='debug' type='log4net.Appender.DebugAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
      </layout>
    </appender>
    <root>
      <level value='INFO'/>
      <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL
            ERROR = 2 show  log -> FATAL ERROR
            WARN =  3 show  log -> FATAL ERROR WARN
            INFO =  4 show  log -> FATAL ERROR WARN INFO
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->
      <!-- To write log in file -->
      <appender-ref ref='debug'/>
      <appender-ref ref='file1'/>
    </root>

  </log4net>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);
</code>```

Configure NLog via XML in code (works for NLog 2.0 and later):

```<code>  string xml = @"<nlog>
                   <targets>
                     <target name='console' type='Console' layout='${message}' />
                   </targets>

                   <rules>
                     <logger name='*' minlevel='Error' writeTo='console' />
                   </rules>
                 </nlog>";

  StringReader sr = new StringReader(xml);
  XmlReader xr = XmlReader.Create(sr);
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null);
  LogManager.Configuration = config;
  //NLog is now configured just as if the XML above had been in NLog.config or app.config
</code>```

Prior to NLog 2.0, NLog's XmlLoggingConfiguration object does not take an XmlReader in its constructor.  You can pass an XmlElement instead, like this:

```<code>  string xml = @"<nlog>
               <targets>
                 <target name='debugger' type='Console' layout='${message}' />
               </targets>

               <rules>
                 <logger name='*' minlevel='Error' writeTo='console' />
               </rules>
             </nlog>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  XmlLoggingConfiguration config = new XmlLoggingConfiguration(doc.DocumentElement,null);
  LogManager.Configuration = config;
</code>```

To update the configuration, given a new XML string, simply repeat the steps for the particular logging framework that you are using.

Body:
Configure log4net via XML in code:

  string xml =
  @"<log4net>
    <appender name='file1' type='log4net.Appender.RollingFileAppender'>
      <!-- Log file locaation -->
      <param name='File' value='log4net.log'/>
      <param name='AppendToFile' value='true'/>
      <!-- Maximum size of a log file -->
      <maximumFileSize value='2KB'/>
      <!--Maximum number of log file -->
      <maxSizeRollBackups value='8'/>
      <!--Set rolling style of log file -->
      <param name='RollingStyle' value='Composite'/>
      <param name='StaticLogFileName' value='false'/>
      <param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <!-- Appender layout fix to view in console-->
    <appender name='console' type='log4net.Appender.ConsoleAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='Header' value='[Header]\r\n'/>
        <param name='Footer' value='[Footer]\r\n'/>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <appender name='debug' type='log4net.Appender.DebugAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
      </layout>
    </appender>
    <root>
      <level value='INFO'/>
      <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL
            ERROR = 2 show  log -> FATAL ERROR
            WARN =  3 show  log -> FATAL ERROR WARN
            INFO =  4 show  log -> FATAL ERROR WARN INFO
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->
      <!-- To write log in file -->
      <appender-ref ref='debug'/>
      <appender-ref ref='file1'/>
    </root>

  </log4net>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);

Configure NLog via XML in code (works for NLog 2.0 and later):

  string xml = @"<nlog>
                   <targets>
                     <target name='console' type='Console' layout='${message}' />
                   </targets>

                   <rules>
                     <logger name='*' minlevel='Error' writeTo='console' />
                   </rules>
                 </nlog>";

  StringReader sr = new StringReader(xml);
  XmlReader xr = XmlReader.Create(sr);
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null);
  LogManager.Configuration = config;
  //NLog is now configured just as if the XML above had been in NLog.config or app.config

Prior to NLog 2.0, NLog's XmlLoggingConfiguration object does not take an XmlReader in its constructor.  You can pass an XmlElement instead, like this:

  string xml = @"<nlog>
               <targets>
                 <target name='debugger' type='Console' layout='${message}' />
               </targets>

               <rules>
                 <logger name='*' minlevel='Error' writeTo='console' />
               </rules>
             </nlog>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  XmlLoggingConfiguration config = new XmlLoggingConfiguration(doc.DocumentElement,null);
  LogManager.Configuration = config;

To update the configuration, given a new XML string, simply repeat the steps for the particular logging framework that you are using.


答:
You can pair up top with ties with window function row_number to get the rows with max amount per state per year.

```<code>select top 1 with ties LEFT(k.wijk, 2) as state,
    YEAR(a.eind_dt) as year,
    opzegreden as reason,
    count(*) as amount
from klant as k
join abon as a on k.klant_id = a.lezer
where opzegreden is not null
group by LEFT(k.wijk, 2),
    year(a.eind_dt),
    opzegreden
order by row_number() over (
        partition by state, year order by amount desc
        );
</code>```

Title: How do you select the highest of a count()?

Body:
You can pair up top with ties with window function row_number to get the rows with max amount per state per year.

select top 1 with ties LEFT(k.wijk, 2) as state,
    YEAR(a.eind_dt) as year,
    opzegreden as reason,
    count(*) as amount
from klant as k
join abon as a on k.klant_id = a.lezer
where opzegreden is not null
group by LEFT(k.wijk, 2),
    year(a.eind_dt),
    opzegreden
order by row_number() over (
        partition by state, year order by amount desc
        );


问:
Populate a spinner based on the selection of another spinner
I have to populate states depending on the selected country. I also have to capture the items selected in other spinners. But the listener methods are not getting called.

```<code>countriesSpinner.setOnItemSelectedListener(this);
statesSpinner.setOnItemSelectedListener(this);
yearSpinner.setOnItemSelectedListener(this);

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // On selecting a spinner item
    switch(view.getId()){
        case R.id.countriesSpinner:
        {
            Log.i("selected country",selectedCountry);
            selectedCountry = parent.getItemAtPosition(position).toString();
            populateStates();
            ArrayAdapter stateAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, states);
            statesSpinner.setAdapter(stateAdapter);
        }
        break;

        case R.id.statesSpinner:
        {
            selectedState=parent.getItemAtPosition(position).toString();
        }
        break;

        case R.id.yearSpinner:
        {
            selectedYear = parent.getItemAtPosition(position).toString();
        }
    }

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
</code>```

答:
you got the Switch Id wrong...your need to use parent.getId()

try this:

```<code> public void onItemSelected(AdapterView<?> parent, View view,
        int pos, long id) {
    switch (parent.getId())
    {
        case R.id.countriesSpinner:

            Log.i("selected country",selectedCountry);
            selectedCountry = parent.getItemAtPosition(position).toString();
            populateStates();
            ArrayAdapter stateAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, states);
            statesSpinner.setAdapter(stateAdapter);
            break;

        case R.id.statesSpinner:
            selectedState=parent.getItemAtPosition(position).toString();
            break;
         case R.id.yearSpinner:
            selectedYear=parent.getItemAtPosition(position).toString();
            break;
    }
}
</code>```

Body:
I have to populate states depending on the selected country. I also have to capture the items selected in other spinners. But the listener methods are not getting called.

countriesSpinner.setOnItemSelectedListener(this);
statesSpinner.setOnItemSelectedListener(this);
yearSpinner.setOnItemSelectedListener(this);

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // On selecting a spinner item
    switch(view.getId()){
        case R.id.countriesSpinner:
        {
            Log.i("selected country",selectedCountry);
            selectedCountry = parent.getItemAtPosition(position).toString();
            populateStates();
            ArrayAdapter stateAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, states);
            statesSpinner.setAdapter(stateAdapter);
        }
        break;

        case R.id.statesSpinner:
        {
            selectedState=parent.getItemAtPosition(position).toString();
        }
        break;

        case R.id.yearSpinner:
        {
            selectedYear = parent.getItemAtPosition(position).toString();
        }
    }

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

Body:
you got the Switch Id wrong...your need to use parent.getId()

try this:

 public void onItemSelected(AdapterView<?> parent, View view,
        int pos, long id) {
    switch (parent.getId())
    {
        case R.id.countriesSpinner:

            Log.i("selected country",selectedCountry);
            selectedCountry = parent.getItemAtPosition(position).toString();
            populateStates();
            ArrayAdapter stateAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, states);
            statesSpinner.setAdapter(stateAdapter);
            break;

        case R.id.statesSpinner:
            selectedState=parent.getItemAtPosition(position).toString();
            break;
         case R.id.yearSpinner:
            selectedYear=parent.getItemAtPosition(position).toString();
            break;
    }
}


问:
Keep path when rewriting with .htaccess
I recently moved my webpage from HTTP to HTTPS and I now got a couple of things that doesn't work like before.

The problem I'm having is that when a user is trying to go to:
http://example.com/i/<imageID> they are redirected to:https://www.example.com/i/image.php?id=<imageID>. This is "correct", but not what I want. I want the links to stay at /i/<imageID> regardless of the user came from http or https.

I have two .htaccess-files that I use to control this redirection on my webpage.

First .htaccess (root directory):

```<code>RewriteEngine on
RewriteOptions inherit

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Second .htaccess (image directory - /i):

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^=]+)$ image.php?img=$1 [NC,L]
</code>```

This redirection was working just fine before I added the first .htaccess-file that redirects the user from HTTP to HTTPS, but now it seems to be broken.

I'm not that familiar with htaccess-files so I hope someone out there can help so I can get my clean URLs back. :)

答:
UPDATED ANSWER --> updated again

%{REQUEST_URI} only includes the URI WITHOUT the querystring. But this is stored in and can be retrieved in another variable --> %{QUERY_STRING}

I edited the code accordingly for the first .htaccess-file

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}%{QUERY_STRING} [L,R=301,QSA]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}%{QUERY_STRING} [L,R=301,QSA]
</code>```

If you change your second .htaccess file to the following, it should be clean :)

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/i/image.php
RewriteRule ^/i/(.*) /i/image.php?img=$1 [P,NC,L,QSA]
</code>```

The [P] stands for 'proxy' meaning that your Apache is seen by the client as a proxy (ofc, without his notice), because your Apache executes the actual (correct) request, while the client only sees the result.

My new take on your problem

```<code>RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^(.*)$ https://%2$1 [R=Permanent,L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^=]+)$ image.php?img=$1 [NC,L]
</code>```

Title: Keep path when rewriting with .htaccess

Body:
I recently moved my webpage from HTTP to HTTPS and I now got a couple of things that doesn't work like before.

The problem I'm having is that when a user is trying to go to:
http://example.com/i/<imageID> they are redirected to:https://www.example.com/i/image.php?id=<imageID>. This is "correct", but not what I want. I want the links to stay at /i/<imageID> regardless of the user came from http or https.

I have two .htaccess-files that I use to control this redirection on my webpage.

First .htaccess (root directory):

RewriteEngine on
RewriteOptions inherit

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Second .htaccess (image directory - /i):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^=]+)$ image.php?img=$1 [NC,L]

This redirection was working just fine before I added the first .htaccess-file that redirects the user from HTTP to HTTPS, but now it seems to be broken.

I'm not that familiar with htaccess-files so I hope someone out there can help so I can get my clean URLs back. :)

Body:
UPDATED ANSWER --> updated again

%{REQUEST_URI} only includes the URI WITHOUT the querystring. But this is stored in and can be retrieved in another variable --> %{QUERY_STRING}

I edited the code accordingly for the first .htaccess-file

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}%{QUERY_STRING} [L,R=301,QSA]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}%{QUERY_STRING} [L,R=301,QSA]

If you change your second .htaccess file to the following, it should be clean :)

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/i/image.php
RewriteRule ^/i/(.*) /i/image.php?img=$1 [P,NC,L,QSA]

The [P] stands for 'proxy' meaning that your Apache is seen by the client as a proxy (ofc, without his notice), because your Apache executes the actual (correct) request, while the client only sees the result.

My new take on your problem

RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^(.*)$ https://%2$1 [R=Permanent,L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^=]+)$ image.php?img=$1 [NC,L]


问:
Matching string regular expression
I would like to match data from strings like the following:

24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]

Colony.S02E09.720p.HDTV.x264-FLEET[rarbg]

24.Legacy (everything before S01E08)

S => 01

E => 08

720p.HDTV.x264 (everything between S01E08 and -)

AVS (everything between - en [)

rarbg (everything between [])

The following test almost works but needs some tweaks:

```<code>preg_match_all(
    '/(.*?).S([0-9]+)E([0-9]+).(.*?)(.*?)[(.*?)]/s',
    $download,
    $posts,
    PREG_SET_ORDER
);
</code>```

答:
Just write it down then :)

```<code>^
(?P<title>.+?)         # title
S(?P<season>\d+)       # season
E(?P<episode>\d+)\.    # episode
(?P<quality>[^-]+)-    # quality
(?P<type>[^[]+)        # type
\[
    (?P<torrent>[^]]+) # rest
\]
$
</code>```

Demo on regex101.com.

Title: Matching string regular expression

Body:
I would like to match data from strings like the following:

24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]

Colony.S02E09.720p.HDTV.x264-FLEET[rarbg]

24.Legacy (everything before S01E08)

S => 01

E => 08

720p.HDTV.x264 (everything between S01E08 and -)

AVS (everything between - en [)

rarbg (everything between [])

The following test almost works but needs some tweaks:

preg_match_all(
    '/(.*?).S([0-9]+)E([0-9]+).(.*?)(.*?)[(.*?)]/s',
    $download,
    $posts,
    PREG_SET_ORDER
);

Body:
Just write it down then :)

^
(?P<title>.+?)         # title
S(?P<season>\d+)       # season
E(?P<episode>\d+)\.    # episode
(?P<quality>[^-]+)-    # quality
(?P<type>[^[]+)        # type
\[
    (?P<torrent>[^]]+) # rest
\]
$

Demo on regex101.com.


问:
MySQl Trigger help needed
using MySQL 5.1.36, I am trying to write trigger which drops scratch tables form "scratch" database.

```<code>CREATE DEFINER=`root`@`localhost` TRIGGER
`jobq`.`DropScratch`
BEFORE DELETE ON jobq.jobq FOR EACH ROW
BEGIN
 DECLARE tblname VARCHAR(128);
 set tblname=concat('scratch.',OLD.jobname);
 DROP TABLE IF EXISTS tblname;
END;
</code>```

I am always getting an error:

```<code>Explicit or implicit commit is not allowed in stored function or trigger.
</code>```

Can I somehow overcome this restriction?

Thank you beforehand

Arman

答:
The primary problem here is that you are not allowed to drop a table within a trigger. That's what the error message is getting at when it says "implicit commit" is not allowed. The drop table does an implicit commit.

So you will need to figure out a different way to do this other than a trigger. One way would be to set up a cron job which compares the data in information_schema.tables to the jobq table to look for tables in the scratch DB that can be dropped, and then drop them.

I should also point out that the way you are trying to dynamically create a drop table statement will not work. That is going to drop a table named literally "tblname", not "scratch.jobname". If you want to drop a table dynamically you will need to build the drop table statement in a separate scripting language, such as python, perl, shell, etc.

Good luck!

Title: MySQl Trigger help needed

Body:
using MySQL 5.1.36, I am trying to write trigger which drops scratch tables form "scratch" database.

CREATE DEFINER=`root`@`localhost` TRIGGER
`jobq`.`DropScratch`
BEFORE DELETE ON jobq.jobq FOR EACH ROW
BEGIN
 DECLARE tblname VARCHAR(128);
 set tblname=concat('scratch.',OLD.jobname);
 DROP TABLE IF EXISTS tblname;
END;

I am always getting an error:

Explicit or implicit commit is not allowed in stored function or trigger.

Can I somehow overcome this restriction?

Thank you beforehand

Arman


问:
How to use my classes from Scala worksheet in IntelliJ CE with Scala plugin?
I can not use my classes from Scala worksheet in IntelliJ CE with Scala plugin.

I do the following:

Create Scala SBT project.

In src/main/scala create package test1.

In this package create class

```<code>package test1
class TestClass {
}
</code>```

In the same package create Scala worksheet ws1.sc, inside it create object ws1, inside it put a couple of expressions. It works.

When I add new ScalaTest to object ws1, IntelliJ adds import test1.ScalaTest, but evaluation of worksheet does not work.

If I add package test1 to my worksheet, it does not work at all, with warning "Package name doesn't correspond to directories structure, this may cause problem with resolve to classes from the file"

Is there any ideas how to use my classes from worksheet?

答: You must tick "Make project" next to the "Interactive mode"</p>

Body:
I can not use my classes from Scala worksheet in IntelliJ CE with Scala plugin.

I do the following:

Create Scala SBT project.

In src/main/scala create package test1.

In this package create class

package test1
class TestClass {
}

In the same package create Scala worksheet ws1.sc, inside it create object ws1, inside it put a couple of expressions. It works.

When I add new ScalaTest to object ws1, IntelliJ adds import test1.ScalaTest, but evaluation of worksheet does not work.

If I add package test1 to my worksheet, it does not work at all, with warning "Package name doesn't correspond to directories structure, this may cause problem with resolve to classes from the file"

Is there any ideas how to use my classes from worksheet?


问:
Is there a tool that allows to edit related code in single file?
My idea is that it's much easier to edit related code when it sits in single "work" file. E.g. in Rails application when you implementing some functionality you may edit 1 function per file in the following files: integration test, controller test, controller, model, controller helper. So if it would be possible to 1) mark this code fragments 2) automatically collect them in "work" file 3) edit them togather 4) the tool synchronizes (puts back) the changes; it could simplify development process in many cases. Especially if you need to go through many tweek-and-try iterations.</p>

答: Just open up Vim and open some windows. What's the problem?</p>


问:
Android database.sqlite.SQLiteException in Query
I'm new to Android Studio. I am creating a contact manager mobile application. The contacts can be added to my SQLite database and the correct names of contacts are being displayed. When clicked, the name of the contact should appear in another activity. I was using the putExtra method but it would not work. This is my code for the first activity when a name is clicked:

```<code>    lv_contactlist.setAdapter(aa_contacts);
    lv_contactlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String Name = (lv_contactlist.getItemAtPosition(position).toString());
            Intent intent = new Intent(MainActivity.this, FinalActivity.class);
            intent.putExtra("Name",Name);
            startActivity(intent);
        }
    });
</code>```

The second activity receives this name and should show the full contact information. This is my code:

```<code>String Name = getIntent().getStringExtra("Name");
    Cursor cursor = sdb.rawQuery("SELECT * contact WHERE NAME = " + Name, null);
    name.setText("NAME: "+cursor.getString(0));
    homephone.setText("HOME PHONE: "+cursor.getString(1));
    mobilephone.setText("MOBILE PHONE: "+cursor.getString(2));
    mobilephone.setText("EMAIL ADDRESS: "+cursor.getString(3));
</code>```

When debugging, I get the error message:

```<code>java.lang.RuntimeException: Unable to start activity  android.database.sqlite.SQLiteException: near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John)
</code>```

This is the exact name appearing on my list. This has led me to believe it has to be the putExtra method passing the information to the second activity or the getStringExtra method receiving the name. Thanks in advance

答:
Your query is wrong:

instead of:

```<code> Cursor cursor = sdb.rawQuery("SELECT * contact WHERE NAME = " + Name, null);
</code>```

use:

```<code> String[] params = new String[]{ Name };
Cursor c = db.rawQuery("SELECT * from contact WHERE NAME = ?", params);
</code>```

Body:
I'm new to Android Studio. I am creating a contact manager mobile application. The contacts can be added to my SQLite database and the correct names of contacts are being displayed. When clicked, the name of the contact should appear in another activity. I was using the putExtra method but it would not work. This is my code for the first activity when a name is clicked:

    lv_contactlist.setAdapter(aa_contacts);
    lv_contactlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String Name = (lv_contactlist.getItemAtPosition(position).toString());
            Intent intent = new Intent(MainActivity.this, FinalActivity.class);
            intent.putExtra("Name",Name);
            startActivity(intent);
        }
    });

The second activity receives this name and should show the full contact information. This is my code:

String Name = getIntent().getStringExtra("Name");
    Cursor cursor = sdb.rawQuery("SELECT * contact WHERE NAME = " + Name, null);
    name.setText("NAME: "+cursor.getString(0));
    homephone.setText("HOME PHONE: "+cursor.getString(1));
    mobilephone.setText("MOBILE PHONE: "+cursor.getString(2));
    mobilephone.setText("EMAIL ADDRESS: "+cursor.getString(3));

When debugging, I get the error message:

java.lang.RuntimeException: Unable to start activity  android.database.sqlite.SQLiteException: near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John)

This is the exact name appearing on my list. This has led me to believe it has to be the putExtra method passing the information to the second activity or the getStringExtra method receiving the name. Thanks in advance

Body:
Your query is wrong:

instead of:

 Cursor cursor = sdb.rawQuery("SELECT * contact WHERE NAME = " + Name, null);

use:

 String[] params = new String[]{ Name };
Cursor c = db.rawQuery("SELECT * from contact WHERE NAME = ?", params);


问:
mySQL :: insert into table, data from another table?
I was wondering if there is a way to do this purely in sql:

```<code>q1 = SELECT campaign_id, from_number, received_msg, date_received
     FROM `received_txts` WHERE `campaign_id` = '8';
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
    VALUES(q1.campaign_id, q1.from_number, q1.received_msg, q1.date_received);
</code>```

Note: q1 would return about 30k rows.

Is there any way to do what I am attempting above in straight sql?
To just pull the data straight from one table (basically a raw data table) and insert into another table (basically a processed data table)?

答:
```<code>INSERT INTO Table1 SELECT * FROM Table2
</code>```

Body:
I was wondering if there is a way to do this purely in sql:

q1 = SELECT campaign_id, from_number, received_msg, date_received
     FROM `received_txts` WHERE `campaign_id` = '8';
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
    VALUES(q1.campaign_id, q1.from_number, q1.received_msg, q1.date_received);

Note: q1 would return about 30k rows.

Is there any way to do what I am attempting above in straight sql?
To just pull the data straight from one table (basically a raw data table) and insert into another table (basically a processed data table)?

Body: INSERT INTO Table1 SELECT * FROM Table2


问:
C++ -& CRTP . Type erasure vs polymorphism
OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow

```<code>template <RealType> class Base
{

    void doSomething()
    {
         static_cast<RealType>(this)->doSomethingImpl()
    }

class Derived1 : public Base
{
    void doSomethingImpl()
    {
        /* do something, for real */
    }
}

class Derived2 : public Base
{
    void doSomethingImpl()
    {
        /* do something else */
    }
}
</code>```

This aproach, if I understood correctly, allows my classes to have no vtable, so function calls are direct and don't require the extra indirection.

Now imagine I want to store all my Derived# classes in a container. Let's say a vector.

First approach : I can create a non-template SuperBase class from which Base inherits and store that in the container.

However it seems to me that if I want to do that, I will have to make doSomething virtual, in SuperBase. And my goal is mainly not to have a vtable.

Second approach : I use type erasure, i.e. something like boost::any to store my elements in the Vector.
But then, I don't see a way I can iterate over the elements and call doSomething on them, because to "use" boost::any, I need to know the real type of the object when iterating.

Do you think what I want to do is even possible ?

Seems to me that it is because doSomething() is part of Base  but except using inheritance, I can't see a way to do it ....

答:
You can do what you want with the proper theoretical operation which is NOT polymorphism, but unification. Most people have no idea what a sum type (discriminated union) is and what it is for which is why they consistently abuse inheritance, which is entirely unrelated.

Unions are more popular in C, for example X-Windows event messages are union based, because they're broken in C++.

A union is the correct way to represent heterogeneous data types as a single type, hence the name unification: it unifies all the components into a single type. Unions always have a finite known number of components, functions using unions invariably use a switch on the discriminant to select the right handler code.

OOP cannot provide unification: it provides subtyping.

Templates provide something quite different again: parametric polymorphism.

All three concepts are quite distinct in both theory and practice. Subtyping OOP style turns out to be the least useful because what it can represent is heavily restricted, however those restrictions do permit dynamic dispatch to an open set of subtypes, which is very nice if it applies to your problem.

So now it is clear, in your array, all you need to put is a union of all your classes, and your problem goes away.

Only .. the classes have to be POD types in C++ at present due to an unprincipled restriction. So the best solution is to use a union of raw C functions, since C function pointers are PODs.

Something like:

```<code>enum tag {tag_X, tag_Y};

struct X { int x; };
void px(X a) { cout << a.x; }
struct PX { tag t; X a; void (*p)(X); };

struct Y { double x; };
void py(Y a) { cout << a.x; };
struct PY {tag t; Y a; void (*p)(Y); };

union XY { PX anX; PY anY; };

PX x1 = { tag_X, { 1 }, px };
PY y1 = { tag_Y, { 1.0 }, py };

XY xy1.anPX = x1;
XY xy2.anPy = x2;

XY xys[2] = {xy1, xy1};

xy = xys[0];
switch (xy.anPX.tag) { // hack
  case tag_X: xy.anPX.p (xy.PX.x); break;
  case tag_Y: xy.anPY.p (xy.PY.x); break;
}
</code>```

If you think this is ugly, you're right: C and C++ are brain dead. Another solution is to use a tag and a pointer which is cast to a void*, then use the tag to cast to the required type: this is much easier but requires heap allocation of the data and hence you have a memory management issue. Another alternative is Boost variant type (which automates some of the housekeeping but is still very ugly).

Here's similar code in Ocaml:

```<code>type xy = X of int | Y of double
let print u =
  match u with
  | X x -> print_int x
  | Y x -> print_double x
in
  print (X 1);
  print (Y 2.0)
</code>```

In this code the X and Y are the tags of the C code above, they're called type constructors because they construct an xy type out of an int or a double (resp.). The match expression there is just a switch with automatic selection of the right component type and scoping used to ensure you can't refer to the wrong component (as you could in the C code), also there's no break, match handlers don't drop thru, and the memory management is done by a garbage collector.

Body:
OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow

template <RealType> class Base
{

    void doSomething()
    {
         static_cast<RealType>(this)->doSomethingImpl()
    }

class Derived1 : public Base
{
    void doSomethingImpl()
    {
        /* do something, for real */
    }
}

class Derived2 : public Base
{
    void doSomethingImpl()
    {
        /* do something else */
    }
}

This aproach, if I understood correctly, allows my classes to have no vtable, so function calls are direct and don't require the extra indirection.

Now imagine I want to store all my Derived# classes in a container. Let's say a vector.

First approach : I can create a non-template SuperBase class from which Base inherits and store that in the container.

However it seems to me that if I want to do that, I will have to make doSomething virtual, in SuperBase. And my goal is mainly not to have a vtable.

Second approach : I use type erasure, i.e. something like boost::any to store my elements in the Vector.
But then, I don't see a way I can iterate over the elements and call doSomething on them, because to "use" boost::any, I need to know the real type of the object when iterating.

Do you think what I want to do is even possible ?

Seems to me that it is because doSomething() is part of Base  but except using inheritance, I can't see a way to do it ....

Body:
You can do what you want with the proper theoretical operation which is NOT polymorphism, but unification. Most people have no idea what a sum type (discriminated union) is and what it is for which is why they consistently abuse inheritance, which is entirely unrelated.

Unions are more popular in C, for example X-Windows event messages are union based, because they're broken in C++.

A union is the correct way to represent heterogeneous data types as a single type, hence the name unification: it unifies all the components into a single type. Unions always have a finite known number of components, functions using unions invariably use a switch on the discriminant to select the right handler code.

OOP cannot provide unification: it provides subtyping.

Templates provide something quite different again: parametric polymorphism.

All three concepts are quite distinct in both theory and practice. Subtyping OOP style turns out to be the least useful because what it can represent is heavily restricted, however those restrictions do permit dynamic dispatch to an open set of subtypes, which is very nice if it applies to your problem.

So now it is clear, in your array, all you need to put is a union of all your classes, and your problem goes away.

Only .. the classes have to be POD types in C++ at present due to an unprincipled restriction. So the best solution is to use a union of raw C functions, since C function pointers are PODs.

Something like:

enum tag {tag_X, tag_Y};

struct X { int x; };
void px(X a) { cout << a.x; }
struct PX { tag t; X a; void (*p)(X); };

struct Y { double x; };
void py(Y a) { cout << a.x; };
struct PY {tag t; Y a; void (*p)(Y); };

union XY { PX anX; PY anY; };

PX x1 = { tag_X, { 1 }, px };
PY y1 = { tag_Y, { 1.0 }, py };

XY xy1.anPX = x1;
XY xy2.anPy = x2;

XY xys[2] = {xy1, xy1};

xy = xys[0];
switch (xy.anPX.tag) { // hack
  case tag_X: xy.anPX.p (xy.PX.x); break;
  case tag_Y: xy.anPY.p (xy.PY.x); break;
}

If you think this is ugly, you're right: C and C++ are brain dead. Another solution is to use a tag and a pointer which is cast to a void*, then use the tag to cast to the required type: this is much easier but requires heap allocation of the data and hence you have a memory management issue. Another alternative is Boost variant type (which automates some of the housekeeping but is still very ugly).

Here's similar code in Ocaml:

type xy = X of int | Y of double
let print u =
  match u with
  | X x -> print_int x
  | Y x -> print_double x
in
  print (X 1);
  print (Y 2.0)

In this code the X and Y are the tags of the C code above, they're called type constructors because they construct an xy type out of an int or a double (resp.). The match expression there is just a switch with automatic selection of the right component type and scoping used to ensure you can't refer to the wrong component (as you could in the C code), also there's no break, match handlers don't drop thru, and the memory management is done by a garbage collector.


问:
Debian 7: connection problems and timeouts
On my root server, debian 7 is the operation system. Running kernel is 2.6.32.
I have the problem, that TCP/IP-connections seems to be "unstable".
ssh connections often hang or timeout. Webserver sometimes runs fast, sometimes the client (browser) is waiting and waiting for a response.
I dont know where to start right now for this problems. I made a hardware check requests at my ISP ticket system.
Is there a hint you can give me?</p>

答:
I would guess it is DNS related. I would isolate one destination to communicate to, and one location to communicate from. Using ping, I would determine if there was latency in the link itself (ping from the server to one destination and from your client workstation to the troubled server). Once you determine that times are predictable (no **'s)I would learn both IP addresses and put them in /etc/hosts.

When you run ssh I would consider using -vv to see what it is doing and maybe that will help.


问:
How to replace all occurrences of an array in JavaScript
If my array is gave me:
["ITEM_1", "ITEM_2", "ITEM_3"]

How I can remove the part ITEM_ to get only ["1", "2", "3"] ?

答:
or:

```<code>var arr = ["ITEM_1", "ITEM_2", "ITEM_3"].map(function(item){
return item.split('_')[1];
});
</code>```

or:

```<code>var arr = ["ITEM_1", "ITEM_2", "ITEM_3"].map(function(item){
return item.replace('ITEM_', '');
});
</code>```

Body:
or:

var arr = ["ITEM_1", "ITEM_2", "ITEM_3"].map(function(item){
return item.split('_')[1];
});

or:

var arr = ["ITEM_1", "ITEM_2", "ITEM_3"].map(function(item){
return item.replace('ITEM_', '');
});


问:
ERR_INSECURE_RESPONSE + subdomains
I need help to understand if Chrome behaviour is OK or it's due to my mistake. I'm using selfsigned-certificates and subdomains.

From https://preproduser.svtools.tp.XXX.it/#!/login/ there is an Ajax query to another subdomain which returns error:

```<code>OPTIONS https://preprodauth.svtools.tp.XXX.it/v1/authenticate net::ERR_INSECURE_RESPONSE
</code>```

Both app are served by a Nging reverse proxy with this certificate:

```<code># openssl x509 -noout -certopt no_sigdump,no_pubkey -text -in selfsigned.svtools.tp.XXX.it.crt
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 15659850292680964857 (0xd952f6df2b0bbaf9)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=IT, ST=Italia, L=YYY, O=XXX, CN=*.svtools.tp.XXX.it
        Validity
            Not Before: Apr  2 18:36:50 2017 GMT
            Not After : Mar 31 18:36:50 2027 GMT
        Subject: C=IT, ST=Italia, L=YYY, O=XXX, CN=*.svtools.tp.XXX.it
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:svtools.tp.XXX.it, DNS:preproduser.svtools.tp.XXX.it, DNS:preprodauth.svtools.tp.XXX.it
</code>```

I see on Chrome that the certificate has SAN and Chrome tells me ERR_CERT_AUTHORITY_INVALID (expected behavior).

Question: after accepting the security certificate issue before opening  https://preproduser.svtools.tp.XXX.it/ I expect no further problems for https://preprodauth.svtools.tp.XXX.it/. Chrome still complains the security issue. Can I avoid this?

Riccardo

答:
While you can override the warning about ERR_CERT_AUTHORITY_INVALID it will only override the warning for exactly this certificate at exactly this hostname and not automatically trust this certificate for any other hosts.

Just imagine that this would be otherwise: in this case some man in the middle attacker could use a certificate to intercept the connection to some unimportant host where many would just override the warning because there are no sensitive data. Once this is done the attacker could use the same certificate (now trusted by the browser) to intercept connections to important hosts. That's why any certificate exemption is only for the specific hostname where the certificate was explicitly exempted for.

Title: ERR_INSECURE_RESPONSE + subdomains

Body:
I need help to understand if Chrome behaviour is OK or it's due to my mistake. I'm using selfsigned-certificates and subdomains.

From https://preproduser.svtools.tp.XXX.it/#!/login/ there is an Ajax query to another subdomain which returns error:

OPTIONS https://preprodauth.svtools.tp.XXX.it/v1/authenticate net::ERR_INSECURE_RESPONSE

Both app are served by a Nging reverse proxy with this certificate:

# openssl x509 -noout -certopt no_sigdump,no_pubkey -text -in selfsigned.svtools.tp.XXX.it.crt
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 15659850292680964857 (0xd952f6df2b0bbaf9)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=IT, ST=Italia, L=YYY, O=XXX, CN=*.svtools.tp.XXX.it
        Validity
            Not Before: Apr  2 18:36:50 2017 GMT
            Not After : Mar 31 18:36:50 2027 GMT
        Subject: C=IT, ST=Italia, L=YYY, O=XXX, CN=*.svtools.tp.XXX.it
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:svtools.tp.XXX.it, DNS:preproduser.svtools.tp.XXX.it, DNS:preprodauth.svtools.tp.XXX.it

I see on Chrome that the certificate has SAN and Chrome tells me ERR_CERT_AUTHORITY_INVALID (expected behavior).

Question: after accepting the security certificate issue before opening  https://preproduser.svtools.tp.XXX.it/ I expect no further problems for https://preprodauth.svtools.tp.XXX.it/. Chrome still complains the security issue. Can I avoid this?

Riccardo