问:
Python cx_Freeze Import Error "No module named humanize"
```<code>    C:\WINDOWS\system32>py C:\Users\Lenovo\Desktop\RPGTxtGame\setup.py build
running build
running build_exe
Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\RPGTxtGame\setup.py", line 5, in <module>
    cx_Freeze.setup( name = "downloads", version = "1.0", options = {"build_exe": {"packages": ["errno", "os", "re", "stat", "subprocess","collections", "pprint","shutil", "humanize","pycallgraph"], "include_files": []}}, executables = exe )
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\dist.py", line 349, in setup
    distutils.core.setup(**attrs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\command\build.py", line 135, in run
    self.run_command(cmd_name)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\dist.py", line 219, in run
    freezer.Freeze()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\freezer.py", line 621, in Freeze
    self.finder = self._GetModuleFinder()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\freezer.py", line 340, in _GetModuleFinder
    finder.IncludePackage(name)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\finder.py", line 653, in IncludePackage
    module = self._ImportModule(name, deferredImports)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\finder.py", line 350, in _ImportModule
    raise ImportError("No module named %r" % name)
ImportError: No module named 'humanize'
</code>```

Hi, I tried to create an executable from my python project. cx_Freeze is givinig this error though

I also tried the pyinstaller but that one is not compatible with python 3.6

My setup.py script is

```<code>import cx_Freeze

exe = [cx_Freeze.Executable("main.py")]

cx_Freeze.setup( name = "downloads", version = "1.0", options = {"build_exe": {"packages": ["errno", "os", "re", "stat", "subprocess","collections", "pprint","shutil", "humanize","pycallgraph"], "include_files": []}}, executables = exe )
</code>```

Could you help me?

答:
Okay I fixed by avoiding the setup.py completely.

There is another way in the Official documentation

Typing..

```<code>cxfreeze main.py
</code>```

in the cmd works for me

Body:
    C:\WINDOWS\system32>py C:\Users\Lenovo\Desktop\RPGTxtGame\setup.py build
running build
running build_exe
Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\RPGTxtGame\setup.py", line 5, in <module>
    cx_Freeze.setup( name = "downloads", version = "1.0", options = {"build_exe": {"packages": ["errno", "os", "re", "stat", "subprocess","collections", "pprint","shutil", "humanize","pycallgraph"], "include_files": []}}, executables = exe )
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\dist.py", line 349, in setup
    distutils.core.setup(**attrs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\command\build.py", line 135, in run
    self.run_command(cmd_name)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\dist.py", line 219, in run
    freezer.Freeze()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\freezer.py", line 621, in Freeze
    self.finder = self._GetModuleFinder()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\freezer.py", line 340, in _GetModuleFinder
    finder.IncludePackage(name)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\finder.py", line 653, in IncludePackage
    module = self._ImportModule(name, deferredImports)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\finder.py", line 350, in _ImportModule
    raise ImportError("No module named %r" % name)
ImportError: No module named 'humanize'

Hi, I tried to create an executable from my python project. cx_Freeze is givinig this error though

I also tried the pyinstaller but that one is not compatible with python 3.6

My setup.py script is

import cx_Freeze

exe = [cx_Freeze.Executable("main.py")]

cx_Freeze.setup( name = "downloads", version = "1.0", options = {"build_exe": {"packages": ["errno", "os", "re", "stat", "subprocess","collections", "pprint","shutil", "humanize","pycallgraph"], "include_files": []}}, executables = exe )

Could you help me?

Body:
Okay I fixed by avoiding the setup.py completely.

There is another way in the Official documentation

Typing..

cxfreeze main.py

in the cmd works for me


来源: stackexchange

问:
Javascript, change value of new created object
i think i got a Problem with async Code.

My form with a select:

Genre

  <select id="Genre" name="Genre" onchange="showUntergenre(this.value)">
   <option value="0" selected="selected"></option>
   $_sql_Genre = mysql_query ("SELECT * FROM tbl_genre ");
   While ($Genre_result = mysql_fetch_array($_sql_Genre)){
    $genre_id=$Genre_result[0];
    $genre_name=$Genre_result[1];
    echo"<option value='$genre_id'>$genre_name</option>";
   }
  </select>

 <input type="hidden" name="GenreHidden" id="GenreHidden" value="$genre">

 <input type="hidden" name="UntergenreHidden" id="UntergenreHidden" value="$untergenre">

```
</div>
</div>
</p>

<p>Now i set the value of the hidden fields and go in this form. The following javascript Code will be executed:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = selectSelectBox("Genre");
handleGenre();
handleUntergenre();</code>```

I select an entry in the selectbox.

function selectSelectBox(object){
 var selectBox = document.getElementById(object);
 var value = document.getElementById(object + "Hidden").value;
 if (selectBox != null && value != "0"){
  selectBox.selectedIndex = value;
 }
}```
</div>
</div>
</p>

<p>I want the value of the hidden field.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function handleGenre(){
 genreValue = document.getElementById("GenreHidden").value;
 if (genreValue != "0"){
  showUntergenre(document.getElementById("GenreHidden").value);
 }
}</code>```

Now i do a SELECT on my db to get the values for a new selectbox.

function showUntergenre(str, selected) {
 if (str==0){
  document.getElementById("txtHint").innerHTML="";
  return;
 }
 if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  }
 }
 xmlhttp.open("GET","getUntergenre.php?genre="+str+"&selected="+selected,true);
 xmlhttp.send();
}```
</div>
</div>
</p>

<p>Snippet of that php Page:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>echo "<select id='Untergenre' name='Untergenre'>";
 echo "<option value='0'></option>";
 $i =1;
 $_sql_Untergenre = mysql_query ("SELECT ".$Genre."_bezeichnung FROM tbl_genre_".$Genre);
 While ($UnterGenre = mysql_fetch_array($_sql_Untergenre)){
  if ($i == $selected)
   echo "<option value='".$i."' selected='selected'>".$UnterGenre[0]."</option>";
  else
   echo "<option value='".$i."'>".$UnterGenre[0]."</option>";
  $i++;
} </code>```

Now ive got a new selectbox in my form and i want to select my desired entry, located in a hidden field.

function handleUntergenre(){
  untergenreValue = document.getElementById("UntergenreHidden").value;
  if (untergenreValue != "0"){
    var selectBox = document.getElementById("Untergenre");
    console.log("!!!!! this selectBox is always null, except in the debugger !!!!: " + selectBox);
    selectBox.selectedIndex = untergenreValue;
  }
}```

This works only in the Browser debugger, otherwise "selectBox" is null.

I dont know if anyone can help me here, but thanks anyway :-)

答:
First, you have several other issues in your code:

You execute a function when assigning to window.onload, instead of just passing the function to it. This is not what you wanted to happen.

The function showUntergenre has two parameters, but you only call it with one (both from the HTML attribute as in the main JS code), so selected will always be undefined, yet you add its value to a URL.

Now to the main issue:

Indeed you are trying to find the Untergenre select box before it is available. You need to wait for the http request to come back with the response, and only then look for the select box.

One way to do this, is to use a callback system. I will provide that here, but you should definitely consider using promises and the fetch API:

Let the function showUntergenre accept a callback function (cb) as argument, which it will call when the additional content has been loaded:

```<code>function showUntergenre(str, selected, cb) {
    // ...
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            if (cb) cb(); // call the callback (if provided)
        }
        // ...
</code>```

Now make sure that callback feature is used, so do the same in handleGenre. Note that I do not know what you intend to pass for value for selected, so please provide the value you want it to have:

```<code>function handleGenre(cb){
    genreValue = document.getElementById("GenreHidden").value;
    if (genreValue != "0"){
        var selected = .......;
        showUntergenre(document.getElementById("GenreHidden").value, selected, cb);
    }
}
</code>```

... and in the call of handleGenre:

```<code>window.onload = function () { // Pass a function!!
    selectSelectBox("Genre");
    handleGenre(handleUntergenre); // here we define the real callback
};
</code>```

This is the idea... Now you'll probably have to adjust it to your actual needs.

ContentLicense: CC BY-SA 3.0

Body:
i think i got a Problem with async Code.

My form with a select:

Genre

  <select id="Genre" name="Genre" onchange="showUntergenre(this.value)">
   <option value="0" selected="selected"></option>
   $_sql_Genre = mysql_query ("SELECT * FROM tbl_genre ");
   While ($Genre_result = mysql_fetch_array($_sql_Genre)){
    $genre_id=$Genre_result[0];
    $genre_name=$Genre_result[1];
    echo"<option value='$genre_id'>$genre_name</option>";
   }
  </select>

 <input type="hidden" name="GenreHidden" id="GenreHidden" value="$genre">

 <input type="hidden" name="UntergenreHidden" id="UntergenreHidden" value="$untergenre">

Now i set the value of the hidden fields and go in this form. The following javascript Code will be executed:

window.onload = selectSelectBox("Genre");
handleGenre();
handleUntergenre();

I select an entry in the selectbox.

function selectSelectBox(object){
 var selectBox = document.getElementById(object);
 var value = document.getElementById(object + "Hidden").value;
 if (selectBox != null && value != "0"){
  selectBox.selectedIndex = value;
 }
}

I want the value of the hidden field.

function handleGenre(){
 genreValue = document.getElementById("GenreHidden").value;
 if (genreValue != "0"){
  showUntergenre(document.getElementById("GenreHidden").value);
 }
}

Now i do a SELECT on my db to get the values for a new selectbox.

function showUntergenre(str, selected) {
 if (str==0){
  document.getElementById("txtHint").innerHTML="";
  return;
 }
 if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  }
 }
 xmlhttp.open("GET","getUntergenre.php?genre="+str+"&selected="+selected,true);
 xmlhttp.send();
}

Snippet of that php Page:

echo "<select id='Untergenre' name='Untergenre'>";
 echo "<option value='0'></option>";
 $i =1;
 $_sql_Untergenre = mysql_query ("SELECT ".$Genre."_bezeichnung FROM tbl_genre_".$Genre);
 While ($UnterGenre = mysql_fetch_array($_sql_Untergenre)){
  if ($i == $selected)
   echo "<option value='".$i."' selected='selected'>".$UnterGenre[0]."</option>";
  else
   echo "<option value='".$i."'>".$UnterGenre[0]."</option>";
  $i++;
}

Now ive got a new selectbox in my form and i want to select my desired entry, located in a hidden field.

function handleUntergenre(){
  untergenreValue = document.getElementById("UntergenreHidden").value;
  if (untergenreValue != "0"){
    var selectBox = document.getElementById("Untergenre");
    console.log("!!!!! this selectBox is always null, except in the debugger !!!!: " + selectBox);
    selectBox.selectedIndex = untergenreValue;
  }
}

This works only in the Browser debugger, otherwise "selectBox" is null.

I dont know if anyone can help me here, but thanks anyway :-)

Body:
First, you have several other issues in your code:

You execute a function when assigning to window.onload, instead of just passing the function to it. This is not what you wanted to happen.

The function showUntergenre has two parameters, but you only call it with one (both from the HTML attribute as in the main JS code), so selected will always be undefined, yet you add its value to a URL.

Now to the main issue:

Indeed you are trying to find the Untergenre select box before it is available. You need to wait for the http request to come back with the response, and only then look for the select box.

One way to do this, is to use a callback system. I will provide that here, but you should definitely consider using promises and the fetch API:

Let the function showUntergenre accept a callback function (cb) as argument, which it will call when the additional content has been loaded:

function showUntergenre(str, selected, cb) {
    // ...
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            if (cb) cb(); // call the callback (if provided)
        }
        // ...

Now make sure that callback feature is used, so do the same in handleGenre. Note that I do not know what you intend to pass for value for selected, so please provide the value you want it to have:

function handleGenre(cb){
    genreValue = document.getElementById("GenreHidden").value;
    if (genreValue != "0"){
        var selected = .......;
        showUntergenre(document.getElementById("GenreHidden").value, selected, cb);
    }
}

... and in the call of handleGenre:

window.onload = function () { // Pass a function!!
    selectSelectBox("Genre");
    handleGenre(handleUntergenre); // here we define the real callback
};

This is the idea... Now you'll probably have to adjust it to your actual needs.


问:
how to Embed Youtube Video with Autoplay, Looping, and show controls?
how to Embed Youtube Video with Autoplay, Looping, and show controls?

Hi How do I make the video work continuously without interruption while at the same time showing control

答:
All you need is to modify url parameter for example autoplay=1 loop=1 and control=1

https://www.youtube.com/embed/E5ln4uR4TwQ?autoplay=1&loop=1&playlist=E5ln4uR4TwQ"

Please refer YouTube Embedded Players and Player Parameters for more settings.

** we need playlist parameter to make looping work, while the value will be your video id

Note: This parameter has limited support in the AS3 player and in IFrame embeds, which could load either the AS3 or HTML5 player. Currently, the loop parameter only works in the AS3 player when used in conjunction with the playlist parameter. To loop a single video, set the loop parameter value to 1 and set the playlist parameter value to the same video ID already specified in the Player API URL:


问:
Converting find() in matlab to python
I am converting a code from Matlab to Python. The code in Matlab is:

```<code>x = find(sEdgepoints > 0 & sNorm < lowT);
sEdgepoints(x)=0;
</code>```

Both arrays are of same size, and I am basically creating a mask.

I read here that nonzero() in numpy is equivalent to find(), so I used that. In Python, I have dstc for sEdgepoints and dst for sNorm. I have also directly put in lowT = 60. So, the code was

```<code>x = np.nonzero(dstc > 0 and dst < 60)
dstc[x] = 0
</code>```

But, I get following error:

```<code>Traceback (most recent call last):
File "C:\Python27\Sheet Counter\customsobel.py", line 32, in <module>
    x = np.nonzero(dstc > 0 and dst < 60)
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
</code>```

I read about the usage of a.any()/a.all() in this post, and I am not sure how that will work. So, I have two questions:
1. If it does, which array to use?
2. If I am correct and it does not work, how to convert the code?

答:
and does boolean operation and numpy expects you to do bitwise operation, so you have to use & i.e

```<code>x = np.nonzero((dstc > 0) & ( dst < 60))
</code>```

Title: Converting find() in matlab to python

Body:
I am converting a code from Matlab to Python. The code in Matlab is:

x = find(sEdgepoints > 0 & sNorm < lowT);
sEdgepoints(x)=0;

Both arrays are of same size, and I am basically creating a mask.

I read here that nonzero() in numpy is equivalent to find(), so I used that. In Python, I have dstc for sEdgepoints and dst for sNorm. I have also directly put in lowT = 60. So, the code was

x = np.nonzero(dstc > 0 and dst < 60)
dstc[x] = 0

But, I get following error:

Traceback (most recent call last):
File "C:\Python27\Sheet Counter\customsobel.py", line 32, in <module>
    x = np.nonzero(dstc > 0 and dst < 60)
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

I read about the usage of a.any()/a.all() in this post, and I am not sure how that will work. So, I have two questions:
1. If it does, which array to use?
2. If I am correct and it does not work, how to convert the code?

Body:
and does boolean operation and numpy expects you to do bitwise operation, so you have to use & i.e

x = np.nonzero((dstc > 0) & ( dst < 60))


问:
Android list view inside a scroll view
I have an android layout which has a scrollView with a number of elements with in it. At the bottom of the scrollView I have a listView which is then populated by an adapter.

The problem that I am experiencing, is that android is excluding the listView from the scrollView as the scrollView already has a scroll-able function.  I want the listView to be as long as the content is and for the master scroll view to be scroll-able.

How can I achieve this behavior?

Here is my main layout:

```<code><ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:fillViewport="true"
    android:gravity="top" >

    <LinearLayout
        android:id="@+id/foodItemActvity_linearLayout_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

</ScrollView>
</code>```

I then programmatically add my components to the linearlayour with the id: foodItemActvity_linearLayout_fragments.  Below is one of the views that is loaded into that linearlayout. This is the one giving me trouble with the scrolls.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
       android:id="@+id/fragment_dds_review_textView_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Reviews:"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <ListView
       android:id="@+id/fragment_dds_review_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </ListView>
</LinearLayout>
</code>```

My adapter then fills up this list view.

Here is an image from the android hierarchy viewer when I click on the master scrollView:

As you can see, it is excluding the reviews listView.

I should be able to scroll the page down and see 8 reviews, but instead it only shows me those 3, and I can scroll on the tiny part where the reviews are. I want a global page scroll

答:
I had a similar problem to the issue posed by the Original Poster - how to make the listview scroll inside the scrollview - and this answer solved my problem.
Disable scrolling of a ListView contained within a ScrollView

I didn't call new fragments into existing layouts or anything like that, like the OP was doing, so my code would look something like this :

```<code><ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:fillViewport="true"
    android:gravity="top" >

 <LinearLayout
        android:id="@+id/foodItemActvity_linearLayout_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    <TextView
       android:id="@+id/fragment_dds_review_textView_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Reviews:"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <ListView
       android:id="@+id/my_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </ListView>

</LinearLayout>

</ScrollView>
</code>```

Basically what I am doing is checking the length of the listview before I call it and when I call it I make it into that length. In your java class use this function:

```<code>public static void justifyListViewHeightBasedOnChildren (ListView listView) {

    ListAdapter adapter = listView.getAdapter();

    if (adapter == null) {
        return;
    }
    ViewGroup vg = listView;
    int totalHeight = 0;
    for (int i = 0; i < adapter.getCount(); i++) {
        View listItem = adapter.getView(i, null, vg);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams par = listView.getLayoutParams();
    par.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
    listView.setLayoutParams(par);
    listView.requestLayout();
}
</code>```

And call the function like this:

```<code>justifyListViewHeightBasedOnChildren(listView);
</code>```

The result is a listview with no scrollbar, the whole length of the listview being displayed, that scrolls with the scroll bar of the scrollview.

Title: Android list view inside a scroll view

Body:
I have an android layout which has a scrollView with a number of elements with in it. At the bottom of the scrollView I have a listView which is then populated by an adapter.

The problem that I am experiencing, is that android is excluding the listView from the scrollView as the scrollView already has a scroll-able function.  I want the listView to be as long as the content is and for the master scroll view to be scroll-able.

How can I achieve this behavior?

Here is my main layout:

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:fillViewport="true"
    android:gravity="top" >

    <LinearLayout
        android:id="@+id/foodItemActvity_linearLayout_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

</ScrollView>

I then programmatically add my components to the linearlayour with the id: foodItemActvity_linearLayout_fragments.  Below is one of the views that is loaded into that linearlayout. This is the one giving me trouble with the scrolls.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
       android:id="@+id/fragment_dds_review_textView_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Reviews:"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <ListView
       android:id="@+id/fragment_dds_review_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </ListView>
</LinearLayout>

My adapter then fills up this list view.

Here is an image from the android hierarchy viewer when I click on the master scrollView:

As you can see, it is excluding the reviews listView.

I should be able to scroll the page down and see 8 reviews, but instead it only shows me those 3, and I can scroll on the tiny part where the reviews are. I want a global page scroll

Body:
I had a similar problem to the issue posed by the Original Poster - how to make the listview scroll inside the scrollview - and this answer solved my problem.
Disable scrolling of a ListView contained within a ScrollView

I didn't call new fragments into existing layouts or anything like that, like the OP was doing, so my code would look something like this :

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:fillViewport="true"
    android:gravity="top" >

 <LinearLayout
        android:id="@+id/foodItemActvity_linearLayout_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    <TextView
       android:id="@+id/fragment_dds_review_textView_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Reviews:"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <ListView
       android:id="@+id/my_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </ListView>

</LinearLayout>

</ScrollView>

Basically what I am doing is checking the length of the listview before I call it and when I call it I make it into that length. In your java class use this function:

public static void justifyListViewHeightBasedOnChildren (ListView listView) {

    ListAdapter adapter = listView.getAdapter();

    if (adapter == null) {
        return;
    }
    ViewGroup vg = listView;
    int totalHeight = 0;
    for (int i = 0; i < adapter.getCount(); i++) {
        View listItem = adapter.getView(i, null, vg);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams par = listView.getLayoutParams();
    par.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
    listView.setLayoutParams(par);
    listView.requestLayout();
}

And call the function like this:

justifyListViewHeightBasedOnChildren(listView);

The result is a listview with no scrollbar, the whole length of the listview being displayed, that scrolls with the scroll bar of the scrollview.


问:
UDP hole-punching: testability on single machine
I'm writing a simple P2P application to test the feasibilty of using UDP hole-punching in a larger project.

I tried my test apps from home yesterday and they worked.

However, I am now at work and the same code no longer does the job. The sender is sending to the appropriate port on the external IP address of our router here, but the receiver isn't getting any of them.

Prior to calling UdpClient.Receive(), the receiving app sends a packet to the IP:port that it will be listening on. Again, this works on my home setup, but not here. The outcome is the same regardless of whether Windows Firewall is on or off, so that's not the issue.

Could it be that the routers are handling the situation differently?

EDIT1: Both apps run on the same machine.

答:
In answer to my own question:

The routers were indeed exhibiting different behavior.

My home router is hooked up to just my laptop. I assume this is why when I send out a UDP packet from port n it also leaves the router on port n.

However, my work network consists of several computers and the router randomizes the port on its end, which means that a packet sent from port y will leave the router on port x.

I have successfully gotten my home and work machines to communicate through NAT without using port forwarding in the following way:

H - Sends packet from port a to W:b, thereby opening port a for incoming connections

W - Sends packet to H:a and switches to receive mode. It too now has an open port.

H - Receives packet from W and instead of presuming to know which port to reply to, checks the packet for its source port and uses that instead.

H - Sends packet to W:source port

W - Receives packet.

Voila.

In practice, tho, H and W would contact a server to exchange connection details, which simplifies matters because the server knows exactly which ports H and W are sending from.

ContentLicense: CC BY-SA 2.5


问:
Inserting a character in String (Swift)
I have a String "000". I want to change this to "0.00".

I took a look at the insert function.

```<code>var str = "000"
str.insert(".", at: str.endIndex)
</code>```

How do I get the index of 2 before the end index?

I tried:

```<code>str.insert(".", at: str.endIndex - 1)
</code>```

but this didn't work at all.

答:
You could also use Strings character property. Its basically an array made up of all the characters (duh) in the String.

So you would:

```<code>var str = "000"

let index = str.characters.index(str.characters.startIndex, offsetBy: 1)  //here you define a place (index) to insert at
str.characters.insert(".", at: index)  //and here you insert
</code>```

Unfortunately you have to create an index first, as .insert does not allow you to specify the position using an Int.

Title: Inserting a character in String (Swift)

Body:
I have a String "000". I want to change this to "0.00".

I took a look at the insert function.

var str = "000"
str.insert(".", at: str.endIndex)

How do I get the index of 2 before the end index?

I tried:

str.insert(".", at: str.endIndex - 1)

but this didn't work at all.

Body:
You could also use Strings character property. Its basically an array made up of all the characters (duh) in the String.

So you would:

var str = "000"

let index = str.characters.index(str.characters.startIndex, offsetBy: 1)  //here you define a place (index) to insert at
str.characters.insert(".", at: index)  //and here you insert

Unfortunately you have to create an index first, as .insert does not allow you to specify the position using an Int.


问:
Disabling head-tracking on a SteamVR camera in Unity?
I am trying to develop a HUD for my VR players using two cameras. One is a stationary camera that points at my HUD objects with a depth=1, the other is the main camera with depth=0 which tracks the HMD and has the HUD overlaid onto it.

However Unity, SteamVR or OpenVR is forcing my camera to track the player's HMD. After my exhaustive search I was unable to find any way to stop this behavior. Then I tried to parent all of my HUD objects to my HUD camera and hoped for the best.

This results in undesirable jerky motion in all HUD objects:

Project Hierarchy:

```<code>[WorldHUD]
    |__ Container (HUD)
        |__ Camera (eye)
            |__ TextMesh (Status) <- Is child of camera

[CameraRig]
    |__ Camera (Head)
        |__ Camera (eye)

[SteamVR]
</code>```

I believe I really need control over my camera's transform so I may prevent it from moving or stopping it from tracking the player's HMD.

I have tried updating the cameras position in Update() and LateUpdate() but that does not have any affect. I also spent many hours modifying/debugging SteamVR and OVR scripts which had no positive results and the cameras never stopped tracking.

I have tried using this suggested script on my cameras parent:

NegateTracking.cs:

using UnityEngine;
using UnityEngine.VR;

public class NegateTracking : MonoBehaviour
{
    void LateUpdate()
    {
        transform.position = -InputTracking.GetLocalPosition(VRNode.CenterEye);
        transform.rotation = Quaternion.Inverse(InputTracking.GetLocalRotation(VRNode.CenterEye));
    }
}
```

This caused the camera to point in one direction but was still translating a bit. However I noticed that things seemed even more choppy this way and feel I'm either using it wrong or it just isn't sufficient.

I'm now back to looking for ways to disable headtracking on certain cameras so I am able to position them in my scene.

Does anyone know how SteamVR/OpenVR takes control of these camera's transforms? Is there any way to disable or overridden this behavior?

Thank you.

答:
So, just spent the whole night developing a functional workaround and put together a project that uses a little post processing magic to essentially "spoof" a stationary camera. My idea was to generate two renderTextures from a custom stereo camera setup consisting of two separate cameras that are not being tracked (which allows control of position, rotation, convergence plane. fov and so on). I then pass those camera's (left and right) renderTextures to the left and right eyes of one of the "tracked" cameras within the OnRenderImage() function. It worked better than I expected, So I decided to put everything up on GitHub and write a short tutorial for anyone else needing to do this.

Stationary Stereo Camera (Download From GitHub)

Body:
I am trying to develop a HUD for my VR players using two cameras. One is a stationary camera that points at my HUD objects with a depth=1, the other is the main camera with depth=0 which tracks the HMD and has the HUD overlaid onto it.

However Unity, SteamVR or OpenVR is forcing my camera to track the player's HMD. After my exhaustive search I was unable to find any way to stop this behavior. Then I tried to parent all of my HUD objects to my HUD camera and hoped for the best.

This results in undesirable jerky motion in all HUD objects:

Project Hierarchy:

[WorldHUD]
    |__ Container (HUD)
        |__ Camera (eye)
            |__ TextMesh (Status) <- Is child of camera

[CameraRig]
    |__ Camera (Head)
        |__ Camera (eye)

[SteamVR]

I believe I really need control over my camera's transform so I may prevent it from moving or stopping it from tracking the player's HMD.

I have tried updating the cameras position in Update() and LateUpdate() but that does not have any affect. I also spent many hours modifying/debugging SteamVR and OVR scripts which had no positive results and the cameras never stopped tracking.

I have tried using this suggested script on my cameras parent:

NegateTracking.cs:

using UnityEngine;
using UnityEngine.VR;

public class NegateTracking : MonoBehaviour
{
    void LateUpdate()
    {
        transform.position = -InputTracking.GetLocalPosition(VRNode.CenterEye);
        transform.rotation = Quaternion.Inverse(InputTracking.GetLocalRotation(VRNode.CenterEye));
    }
}

This caused the camera to point in one direction but was still translating a bit. However I noticed that things seemed even more choppy this way and feel I'm either using it wrong or it just isn't sufficient.

I'm now back to looking for ways to disable headtracking on certain cameras so I am able to position them in my scene.

Does anyone know how SteamVR/OpenVR takes control of these camera's transforms? Is there any way to disable or overridden this behavior?

Thank you.


问:
while loop is not giving expected results
i am learning python 3.6
while writing my script i come across a problem:

below are my codes

```<code>from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
    loop = 6

list1()

print("""-------------------------------------""")
</code>```

but problem is whenever i enter the defined names it works fine but when i enter the wrong name it stops, but what i want it should keep me asking "please enter valid name " until i enter valid name.
any suggestion. python 3.6

intend space is given here to give enter code

答:
First of all, your indentation is wrong.

To the problem: You are setting loop = 6 anyways, independent of whether you got a matching answer or not.

Here a slightly different suggestion:

```<code>print("Game starts here")
print("which Player do you choose?")
print("Now the game starts")

while True:

    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
        break
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
        break
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
        break
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
        break
    else:
        print("Please enter the valid name")
</code>```

This way we break the loop once we get a valid input, otherwise we keep looping indefinitely.

Body:
i am learning python 3.6
while writing my script i come across a problem:

below are my codes

from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
    loop = 6

list1()

print("""-------------------------------------""")

but problem is whenever i enter the defined names it works fine but when i enter the wrong name it stops, but what i want it should keep me asking "please enter valid name " until i enter valid name.
any suggestion. python 3.6

intend space is given here to give enter code

Body:
First of all, your indentation is wrong.

To the problem: You are setting loop = 6 anyways, independent of whether you got a matching answer or not.

Here a slightly different suggestion:

print("Game starts here")
print("which Player do you choose?")
print("Now the game starts")

while True:

    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
        break
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
        break
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
        break
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
        break
    else:
        print("Please enter the valid name")

This way we break the loop once we get a valid input, otherwise we keep looping indefinitely.


问:
How to make make an app function according to user accounts? (Ionic 2 and firebase)
Okay so this is how my app is supposed to function: it works like uber. Just that instead of hiring Drivers, users will be hiring helpers to clean their homes.
Do you have any idea of how to make the app function in accordance to specific accounts?
Like when user logs in using his account and it's authenticated using firebase.

Okay imagine this scenario :

Imagine that there's 2 users using this app. User 1 applies to become a helper. User 2 applies to become a requester(the one who requests for a helper). So user 2 will create a job request (that means keying in all the necessary data(date, time etc)) which will be saved to firebase. And user 1 will be able to look at the list of job requests made by different people.

Any idea how to tie those requests to specific accounts? (Job request 1 belongs to person 1, job request 2 belongs to person 2 etc). Is there a way to do this with firebase authentication? Or is there any other ways? In need of examples.

答:
User Grouping is possible in firebase

Example:

There's no explicit support for "groups" in Firebase, because you can represent them yourself quite easily. Here are two options, depending on your situation.

Storing group information in firebase.

The following data could be used to represent 2 groups ('alpha' and 'beta') and 3 pieces of protected data ('thing1', 'thing2', and 'thing3')

```<code>{
  "groups": {
    "alpha": {
      "joe": true,
      "sally": true
    },
    "beta": {
      "joe": true,
      "fred": true
    }
  },
  "data": {
    "thing1": {
      "group": "alpha"
      /* data accessible only by the "alpha" group */
    },
    "thing2": {
      "group": "beta"
      /* data accessible only by the "beta" group */
    },
    "thing3": {
      "group": "alpha"
      /* more data accessible by the "alpha" group */
    }
  }
}
</code>```

reference

Body:
User Grouping is possible in firebase

Example:

There's no explicit support for "groups" in Firebase, because you can represent them yourself quite easily. Here are two options, depending on your situation.

Storing group information in firebase.

The following data could be used to represent 2 groups ('alpha' and 'beta') and 3 pieces of protected data ('thing1', 'thing2', and 'thing3')

{
  "groups": {
    "alpha": {
      "joe": true,
      "sally": true
    },
    "beta": {
      "joe": true,
      "fred": true
    }
  },
  "data": {
    "thing1": {
      "group": "alpha"
      /* data accessible only by the "alpha" group */
    },
    "thing2": {
      "group": "beta"
      /* data accessible only by the "beta" group */
    },
    "thing3": {
      "group": "alpha"
      /* more data accessible by the "alpha" group */
    }
  }
}

reference


问:
Why doesn't IntelliJ Idea recognize my Spek tests?
I have a Gradle-based Kotlin project with some Spek tests, which are based on JUnit and should be compatible with Idea.

But I don't see a "Run" menu item in the context menu.

Why? What do I need to do in order to be able to run Spek tests in Idea like other JUnit tests?

Here's my build.gradle:

```<code>buildscript {
  ext.kotlin_version = '1.0.4'
  repositories {
    mavenCentral()
    maven {
        url "https://dl.bintray.com/jetbrains/spek"
    }
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M3'
  }

}

apply plugin: "kotlin"
apply plugin: "application"
apply plugin: 'org.junit.platform.gradle.plugin'

junitPlatform {
    filters {
        engines {
            include 'spek'
        }
    }
}

mainClassName = "com.mycompany.myproduct.AppKt"

sourceSets {
  deploy
}

repositories {
  mavenCentral()
  maven {
    url "https://dl.bintray.com/jetbrains/spek"
  }

}

dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  compile 'org.telegram:telegrambots:2.4.2'
  compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
  compile group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3'
  compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3'
  compile group: 'org.slf4j', name: 'slf4j-api', version: '1.6.1'
  testCompile  'junit:junit:4.11'
  testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
  testCompile group: 'org.mockito', name: 'mockito-all', version: '2.0.2-beta'
  testCompile 'org.jetbrains.spek:spek-api:1.1.19'
  testRuntime 'org.jetbrains.spek:spek-junit-platform-engine:1.1.19'
}

test.testClassesDir = project.tasks.compileTestKotlin.destinationDir

task wrapper(type: Wrapper) {
  gradleVersion="3.1"
}

run {
    jvmArgs = ["-Xmx100m", "-XX:+HeapDumpOnOutOfMemoryError", "-XX:HeapDumpPath=/[...]/log/memdump.log"]
}

jar {
    manifest {
        attributes 'Main-Class': mainClassName,
                   'Class-Path': configurations.runtime.files.collect {"$it.name"}.join(' ')
    }
}
</code>```

答:
Since you are using Junit 4.11, you can remove this from your build.gradle:

```<code>junitPlatform {
    filters {
        engines {
            include 'spek'
        }
    }
}
</code>```

Then add this above your test class declaration:

```<code>@RunWith(JUnitPlatform::class)
</code>```

Source: http://spekframework.org/docs/latest/#setting-up-legacy

Body:
I have a Gradle-based Kotlin project with some Spek tests, which are based on JUnit and should be compatible with Idea.

But I don't see a "Run" menu item in the context menu.

Why? What do I need to do in order to be able to run Spek tests in Idea like other JUnit tests?

Here's my build.gradle:

buildscript {
  ext.kotlin_version = '1.0.4'
  repositories {
    mavenCentral()
    maven {
        url "https://dl.bintray.com/jetbrains/spek"
    }
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M3'
  }

}

apply plugin: "kotlin"
apply plugin: "application"
apply plugin: 'org.junit.platform.gradle.plugin'

junitPlatform {
    filters {
        engines {
            include 'spek'
        }
    }
}

mainClassName = "com.mycompany.myproduct.AppKt"

sourceSets {
  deploy
}

repositories {
  mavenCentral()
  maven {
    url "https://dl.bintray.com/jetbrains/spek"
  }

}

dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  compile 'org.telegram:telegrambots:2.4.2'
  compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
  compile group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3'
  compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3'
  compile group: 'org.slf4j', name: 'slf4j-api', version: '1.6.1'
  testCompile  'junit:junit:4.11'
  testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
  testCompile group: 'org.mockito', name: 'mockito-all', version: '2.0.2-beta'
  testCompile 'org.jetbrains.spek:spek-api:1.1.19'
  testRuntime 'org.jetbrains.spek:spek-junit-platform-engine:1.1.19'
}

test.testClassesDir = project.tasks.compileTestKotlin.destinationDir

task wrapper(type: Wrapper) {
  gradleVersion="3.1"
}

run {
    jvmArgs = ["-Xmx100m", "-XX:+HeapDumpOnOutOfMemoryError", "-XX:HeapDumpPath=/[...]/log/memdump.log"]
}

jar {
    manifest {
        attributes 'Main-Class': mainClassName,
                   'Class-Path': configurations.runtime.files.collect {"$it.name"}.join(' ')
    }
}

Body:
Since you are using Junit 4.11, you can remove this from your build.gradle:

junitPlatform {
    filters {
        engines {
            include 'spek'
        }
    }
}

Then add this above your test class declaration:

@RunWith(JUnitPlatform::class)

Source: http://spekframework.org/docs/latest/#setting-up-legacy


问:
div animate not working jquery
HTML

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

<head>
  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>
</head>

<body>
  <div id="top1">
    <div class="inside1">
      <div class="nested_inside1"> MY HAPPY PLACES </div>
    </div>
    <div class="inside2">
      <div class="nested_inside2"> CLUMSSY BEACHES
      </div>
    </div>
    <div class="inside3">
      <div class="nested_inside3"> REGULAR APPLES </div>
    </div>
    <div class="inside4">
      <div class="nested_inside4"> LUSTY BRUSHES </div>
    </div>
    <div class="inside5">
      <div class="nested_inside5"> ECSTATIC DIMENSIONS </div>
    </div>
    <div class="inside6">
      <div class="nested_inside6"> CURLY HILLS </div>
    </div>
    <div class="inside7">
      <div class="nested_inside7"> SHINY WATER </div>
    </div>
    <div class="inside8">
      <div class="nested_inside8"> COOL BOATS </div>
    </div>
    <div class="inside9">
      <div class="nested_inside9"> CRUNCHY CLUSHTERS </div>
    </div>
    <script type="text/javascript" src="myscript2.js"></script>
</body>

</html>
</code>```

JavaScript

```<code>$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});
</code>```

答:
```<code> <head>
 <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script type="text/javascript" src="myscript2.js"></script>
<link rel="stylesheet" type="text/css" href="mystyle1.css">
<title>hd images</title>
</head>
</code>```

You need to add the link to the jquery file in your  then add your jquery file after that.

Title: div animate not working jquery

Body:
HTML

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>

 MY HAPPY PLACES

 CLUMSSY BEACHES

 REGULAR APPLES

 LUSTY BRUSHES

 ECSTATIC DIMENSIONS

 CURLY HILLS

 SHINY WATER

 COOL BOATS

 CRUNCHY CLUSHTERS

JavaScript

$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});

Body:
 <head>
 <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script type="text/javascript" src="myscript2.js"></script>
<link rel="stylesheet" type="text/css" href="mystyle1.css">
<title>hd images</title>
</head>

You need to add the link to the jquery file in your <head> then add your jquery file after that.


问:
How to convert the data stream to data set in flink?
I need to convert the datastream to data set so that I could perform sorting operation on the data set. How to convert the data stream to dataset? Is it possible in flink?</p>

答: It is not possible to convert a DataSet into a DataStream. The APIs for batch and stream processing are separate. You can however, write the DataStream into a file and read the file as a DataSet.


问:
Creating Access 97 format Database
Most of the example codes on the internet use either access97 or 2000 format database.In a database creation code it was mentioned that if Jet OLEDB:Engine Type=4 is used the database created is access 97 format and if Type=5 than access 2000 format.But when i create a database with code using type=4 or even with the visual data manager, the format created is access 95(as shown when opened with MS access 2003).What things do I need to check to create Access 97 format database? Please help!</p>

答:
Hi.

I successed to Make Blank Access 97 Format MDB File with VBScript 32bit on Windows 10 + Access 2016 64 bit.

To Create "E:\TEST97.MDB" , Let Run this VBScript  32bit.(Run From Command Prompt(Cmd.exe) and paste %SystemRoot%\SysWow64\cscript.exe "C:\hoge\MakeAC97.vbs" and enter)

Language General(English and so on)

To Make Vbscript "C:\hoge\MakeAC97.vbs

Transfer Access 2003 Format mdb, "E:\test2000_2003.mdb

I can Access 1.0 - Access 2003 format mdb file

Code sample is this Japanese Article

[http://qiita.com/Q11Q/items/1793f43a1fd4dd3f480f]

And Using SQL on VBScript 32 bit, We can read Access 97 format mdb Table Data, directly.

[http://qiita.com/Q11Q/items/fc06d858ee0d3c9423f4]

Of Course, There is limited, But Access 2016 format accdb file Tables and Select Queries and Union Queries Transfer to Access 97 Format mdb.

[http://qiita.com/Q11Q/items/0ada315f6b5eb9b14f8b]

    '%SystemRoot%\SysWow64\cscript.exe "C:\hoge\MakeAC97.vbs"
    'Access 2013 Later
    '64 / 32 Ok
     Const DB_Lang_General = ";LANGID=0x0409;CP=1252;COUNTRY=0"
     Const DB_LANG_JAPANESE = ";LANGID=0x0411;CP=932;COUNTRY=0"
     Const DB_Lang_Arabic = ";LANGID=0x0401;CP=1256;COUNTRY=0"
     Const DB_Lang_ChineseSimplified = ";LANGID=0x0804;CP=936;COUNTRY=0"
     onst DB_Lang_ChineseTraditional = ";LANGID=0x0404;CP=950;COUNTRY=0"
     Const DB_Lang_Cyrillic = ";LANGID=0x0419;CP=1251;COUNTRY=0"
     Const DB_Lang_Czech = ";LANGID=0x0405;CP=1250;COUNTRY=0"
     Const DB_Lang_Dutch = ";LANGID=0x0413;CP=1252;COUNTRY=0"
     Const DB_Lang_Greek = ";LANGID=0x0408;CP=1253;COUNTRY=0"
     Const DB_Lang_Hebrew = ";LANGID=0x040D;CP=1255;COUNTRY=0"
     Const DB_Lang_Hungarian = ";LANGID=0x040E;CP=1250;COUNTRY=0"
     Const DB_Lang_Icelandic = ";LANGID=0x040F;CP=1252;COUNTRY=0"
     Const DB_Lang_Korean = ";LANGID=0x0412;CP=949;COUNTRY=0"
     Const DB_Lang_Nordic = ";LANGID=0x041D;CP=1252;COUNTRY=0"
     Const DB_Lang_NorwDan = ";LANGID=0x0406;CP=1252;COUNTRY=0" 'Norway and Dennmark
     Const DB_Lang_Polish = ";LANGID=0x0415;CP=1250;COUNTRY=0"
     Const DB_Lang_Slovenian = ";LANGID=0x0424;CP=1250;COUNTRY=0"
     Const DB_Lang_Spanish = ";LANGID=0x040A;CP=1252;COUNTRY=0"
     Const DB_Lang_SwedFin = ";LANGID=0x041D;CP=1252;COUNTRY=0"
     Const DB_Lang_Thai = ";LANGID=0x041E;CP=874;COUNTRY=0"
     Const DB_Lang_Turkish = ";LANGID=0x041F;CP=1254;COUNTRY=0"

 Const DB_OPEN_DYNASET = 2
 Const DB_APPEND_ONLY = 8
 Const DRIVE_NAME = "E:\"
 Const FILE_NAME = "TEST97.mdb"
 Const oldFile = "E:\test97.mdb"
 Const NewFile = "E:\test2000_2003.mdb"
 Const cnsDbVersion30_AC95_AC97_Jet30_Jet35 = 32
 Const cnsDbVersion20_AC20_Jet20 = 16
 Const cndDBVerion10 =1
 Dim dbe : Set dbe = CreateObject("DAO.DBEngine.36")
' MDB Start Making...
 Set dbe = CreateObject("DAO.DBEngine.36")
 Set db = dbe.CreateDatabase(DRIVE_NAME & FILE_NAME, DB_Lang_General, cnsDbVersion30_AC95_AC97_Jet30_Jet35)
 Set db = Nothing
 Set dbe = Nothing
Call JetCompact
End Sub
Sub JetCompact()
Dim JIRO : Set JIRO = CreateObject("JRO.JetEngine")
Dim strOldConnect : strOldConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & oldFile & ";"
Dim strNewConnect : strNewConnect ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & NewFile & ";Jet OLEDB:Engine Type =5;"

With CreateObject("Scripting.FileSystemObject")
    If .FileExists(oldFIle)=False then Wscript.Quit
    If .FileExists(NewFile)=True then Wscript.Quit
End With
JIRO.CompactDatabase strOldConnect, strNewConnect
Set Jiro = Nothing
WScript.Echo "Success End"
End Sub
```

Title: Creating Access 97 format Database


问:
Dimensions must be equal, but are 1 and 128 for 'SparseSoftmaxCrossEntropyWithLogits
I tried to read an images as png format using conventional neural network in tensorflow. I faced a problem that I cannot deal with label in read data step, so, it gives me an error.

First thing I thought the problem is happened when I create batch queue and shuffle.
which was the problem in tf.train.shuffle_batch expected 1-D but actually it got shape as 3-D.

I fixed that. and then it gives me another error in loss function

The subcode is here

the problem is::

Traceback (most recent call last):   File "SVHN.py", line 280, in
        tf.app.run()   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/platform/app.py",
    line 48, in run
        _sys.exit(main(_sys.argv[:1] + flags_passthrough))   File "SVHN.py", line 269, in main
        train_op = SVHN_architecture_AND_optimize()   File "SVHN.py", line 203, in SVHN_architecture_AND_optimize
        cross_entropy =  tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels
    = labels)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py",
    line 1742, in sparse_softmax_cross_entropy_with_logits
        precise_logits, labels, name=name)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/gen_nn_ops.py",
    line 2418, in _sparse_softmax_cross_entropy_with_logits
        features=features, labels=labels, name=name)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py",
    line 768, in apply_op
        op_def=op_def)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py",
    line 2338, in create_op
        set_shapes_for_outputs(ret)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py",
    line 1719, in set_shapes_for_outputs
        shapes = shape_func(op)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py",
    line 1669, in call_with_requiring
        return call_cpp_shape_fn(op, require_shape_fn=True)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py",
    line 610, in call_cpp_shape_fn
        debug_python_shape_fn, require_shape_fn)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py",
    line 676, in _call_cpp_shape_fn_impl
        raise ValueError(err.message) ValueError: Dimensions must be equal, but are 1 and 128 for
    'SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits'
    (op: 'SparseSoftmaxCrossEntropyWithLogits') with input shapes: [1,10],
    [128].

答:
The reason for the error is because only 1 input image is getting passed to the  SparseSoftmaxEntropyWithLogits and not a complete batch. This line is causing the problem:

```<code># change your single input `image` to a batch of `images`
images = tf.reshape(images, [-1, IMAGE_SIZE, IMAGE_SIZE, depth])
</code>```

Body:
The reason for the error is because only 1 input image is getting passed to the  SparseSoftmaxEntropyWithLogits and not a complete batch. This line is causing the problem:

# change your single input `image` to a batch of `images`
images = tf.reshape(images, [-1, IMAGE_SIZE, IMAGE_SIZE, depth])


问:
@Autowire in a java servlet using AbstractAnnotationConfigDispatcherServletInitializer
I am currently trying to use the new Java based annotation configuration for both spring and my Java Web Servlets. I am currently having an issue using the @Autowired annotation inside the servlet itself, but I am unsure if it is my configuration files or a misstep with my use of AbstractAnnotationConfigDispatcherServletInitializer to bootstrap the servlet configuration.

I have searched the forum and thought I had found the answer using the following code snippet :

```<code>    public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
  }
</code>```

However it seems upon debugging that the "ServletConfig" - context is null and leads to the following error due to no beans being registered:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fdmgroup.bookshop.service.BookService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.processInjection(AutowiredAnnotationBeanPostProcessor.java:387)
at org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:110)
at com.fdmgroup.bookshop.controller.HomeController.init(HomeController.java:46)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
</code>```

I am currently unsure whether the @ComponentScan is not being activated properly in my WebConfig Class, the ServletConfig context is not being loaded properly, or something else altogether is at play. any help would be much appreciated!

WebServlet:

```<code>@WebServlet("/")
public class HomeController extends HttpServlet {
private static final long serialVersionUID = 1L;

@Autowired
private BookService bookService;

public HomeController() {
}

public HomeController(BookService bookService) {
    this.bookService = bookService;
}

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
  }

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<Book> books = bookService.retrieveAllBooks();
    request.setAttribute("books", books);
    request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
</code>```

Java configuration files:

```<code>public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getServletConfigClasses() {
    System.out.println("in Servlet Initializer");
    return new Class[] { WebConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { RootConfig.class };
}
</code>```

}

WebConfig.class:

```<code>@Configuration
@EnableWebMvc
@ComponentScan({ "com.fdmgroup.bookshop" })
public class WebConfig extends WebMvcConfigurerAdapter {
}
</code>```

RootConfig.class:

```<code>@Configurable
public class RootConfig {
}
</code>```

BookService.class:

```<code>@Service
public class BookService {
@Autowired
private CRUD<Book> bookRepository;

public BookService(CRUD<Book> bookRepository) {
    this.bookRepository = bookRepository;
}

public BookService() {
}

public void createBook (Book book){
    bookRepository.create(book);
}

public Book retrieveBook (long id){
    return bookRepository.retrieve(id);
}

public void deleteBook (long id){
    bookRepository.delete(id);
}

public List<Book> retrieveAllBooks (){
    return bookRepository.retrieveAll();
}
</code>```

}

Thanks!

答:
For anyone running into similar issues, I managed to solve my own problem thanks to this excellent post:
getservletconfigclasses-vs-getrootconfigclasses

The issue was indeed @ComponentScan related, as I hadn't realised the WebConfig  only scanned for bean's within the Servlet WebApplicationContext, and that the Root WebApplicationContext was treated completely separately. The solution with this new understanding was very simple, adding a second @ComponentScan in the RootConfig.class:

```<code>@Configurable
@ComponentScan({ "com.fdmgroup.bookshop" })
public class RootConfig {
}
</code>```

Body:
I am currently trying to use the new Java based annotation configuration for both spring and my Java Web Servlets. I am currently having an issue using the @Autowired annotation inside the servlet itself, but I am unsure if it is my configuration files or a misstep with my use of AbstractAnnotationConfigDispatcherServletInitializer to bootstrap the servlet configuration.

I have searched the forum and thought I had found the answer using the following code snippet :

    public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
  }

However it seems upon debugging that the "ServletConfig" - context is null and leads to the following error due to no beans being registered:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fdmgroup.bookshop.service.BookService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.processInjection(AutowiredAnnotationBeanPostProcessor.java:387)
at org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:110)
at com.fdmgroup.bookshop.controller.HomeController.init(HomeController.java:46)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

I am currently unsure whether the @ComponentScan is not being activated properly in my WebConfig Class, the ServletConfig context is not being loaded properly, or something else altogether is at play. any help would be much appreciated!

WebServlet:

@WebServlet("/")
public class HomeController extends HttpServlet {
private static final long serialVersionUID = 1L;

@Autowired
private BookService bookService;

public HomeController() {
}

public HomeController(BookService bookService) {
    this.bookService = bookService;
}

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
  }

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<Book> books = bookService.retrieveAllBooks();
    request.setAttribute("books", books);
    request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}

Java configuration files:

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getServletConfigClasses() {
    System.out.println("in Servlet Initializer");
    return new Class[] { WebConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { RootConfig.class };
}

}

WebConfig.class:

@Configuration
@EnableWebMvc
@ComponentScan({ "com.fdmgroup.bookshop" })
public class WebConfig extends WebMvcConfigurerAdapter {
}

RootConfig.class:

@Configurable
public class RootConfig {
}

BookService.class:

@Service
public class BookService {
@Autowired
private CRUD<Book> bookRepository;

public BookService(CRUD<Book> bookRepository) {
    this.bookRepository = bookRepository;
}

public BookService() {
}

public void createBook (Book book){
    bookRepository.create(book);
}

public Book retrieveBook (long id){
    return bookRepository.retrieve(id);
}

public void deleteBook (long id){
    bookRepository.delete(id);
}

public List<Book> retrieveAllBooks (){
    return bookRepository.retrieveAll();
}

}

Thanks!

Body:
For anyone running into similar issues, I managed to solve my own problem thanks to this excellent post:
getservletconfigclasses-vs-getrootconfigclasses

The issue was indeed @ComponentScan related, as I hadn't realised the WebConfig  only scanned for bean's within the Servlet WebApplicationContext, and that the Root WebApplicationContext was treated completely separately. The solution with this new understanding was very simple, adding a second @ComponentScan in the RootConfig.class:

@Configurable
@ComponentScan({ "com.fdmgroup.bookshop" })
public class RootConfig {
}


问:
How to force download a file over AJAX in Zend Framework?
I am looking for a way to show the browser's download dialog page when a user clicks on the download button.

This is my HTML -

```<code>    <span id="ajaxdownloadcontent" class="ajaxaction ajaxbutton"
onclick="javascript:AjaxDownloadContent('http://localhost/ajax/download/pic/12')">
Download </span>
</code>```

My Javascript -

```<code>function AjaxDownloadContent(path) {
    $.post(path);
}
</code>```

My controller, AjaxController.php -

```<code>class AjaxController extends Zend_Controller_Action {

public function init() {
    if ($this->getRequest()->isXmlHttpRequest()) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
    }
}

public function downloadAction() {
    if ($this->getRequest()->isXmlHttpRequest()) {
            $this->getResponse()
                    ->clearAllHeaders()
                    ->setHeader('Content-Disposition', 'attachment;filename="Google_Logo.gif"')
                    ->sendHeaders()
                    ->setBody(file_get_contents("http://www.google.com/logos/logo.gif"))
                    ->sendResponse();
return true;
}
</code>```

This is how the headers look like in firebug (Note that content type has been changed to text/html)

I think this is because of the following code in the bootstrap.

```<code>public static function sendResponse(Zend_Controller_Response_Http $response) {
    if (!headers_sent ()) {
        $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true);
    }
    $response->sendResponse();
}
</code>```

And finally the HTML response looks like something below -

How to force download the file(image in this case) over AJAX when the user clicks the download button?

答:
As far as I know, this is not possible using the Ajax route.

Why not use a simple  tag pointing to the resource though?

Body:
I am looking for a way to show the browser's download dialog page when a user clicks on the download button.

This is my HTML -

Download

My Javascript -

function AjaxDownloadContent(path) {
    $.post(path);
}

My controller, AjaxController.php -

class AjaxController extends Zend_Controller_Action {

public function init() {
    if ($this->getRequest()->isXmlHttpRequest()) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
    }
}

public function downloadAction() {
    if ($this->getRequest()->isXmlHttpRequest()) {
            $this->getResponse()
                    ->clearAllHeaders()
                    ->setHeader('Content-Disposition', 'attachment;filename="Google_Logo.gif"')
                    ->sendHeaders()
                    ->setBody(file_get_contents("http://www.google.com/logos/logo.gif"))
                    ->sendResponse();
return true;
}

This is how the headers look like in firebug (Note that content type has been changed to text/html)

I think this is because of the following code in the bootstrap.

public static function sendResponse(Zend_Controller_Response_Http $response) {
    if (!headers_sent ()) {
        $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true);
    }
    $response->sendResponse();
}

And finally the HTML response looks like something below -

How to force download the file(image in this case) over AJAX when the user clicks the download button?

Body:
As far as I know, this is not possible using the Ajax route.

Why not use a simple <a> tag pointing to the resource though?


问:
Database design for upvote/downvote in discussion forum?
I have a webite where there is a discussion forum. All questions have unique ID and answers have also unique ID with a foreign key referencing to question ID.

I have a user logged in. Using ajax, I can send the data(upvote/downvote,QID/AID, username).But there are few problems.

Whenever user logs back in, I want that when he opens a question, his previous upvotes and downvotes should be displayed.

A user cannot upvote/downvote a same question multiple times. Like if he upvoted a question to +1, he can only downvote it, not upvote it again.

Solution according to me. I am thinking of maintaining a table where username is the primary key and another attribute is a list of all the upvotes and downvotes he has done. Example:

```<code>(username, array)
(baqir, up_A001 up_A050 down_Q011 up_Q123)
</code>```

Whenever the user logs in, I take this array and make sure all the previous upvotes and downvotes of the user are as it is. If there is a new vote,I add it to the array.

Is there any better solution?

P.S. Not necceassary but my current database structure.

```<code>class Question(models.Model):
    QID = models.CharField( default="",max_length=1000, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=1000, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID
</code>```

I am using Django. And I basically want whatever stackoverflow has implemented for their voting of questions and answers.

答: Upvote and Downvote scenario can be handled using code,If the last vote is a upvote user have permission only to downvote, if the user downvote he has permission to upvote, but for keeping status as you told you can keep a history in a array.</p>

Body:
I have a webite where there is a discussion forum. All questions have unique ID and answers have also unique ID with a foreign key referencing to question ID.

I have a user logged in. Using ajax, I can send the data(upvote/downvote,QID/AID, username).But there are few problems.

Whenever user logs back in, I want that when he opens a question, his previous upvotes and downvotes should be displayed.

A user cannot upvote/downvote a same question multiple times. Like if he upvoted a question to +1, he can only downvote it, not upvote it again.

Solution according to me. I am thinking of maintaining a table where username is the primary key and another attribute is a list of all the upvotes and downvotes he has done. Example:

(username, array)
(baqir, up_A001 up_A050 down_Q011 up_Q123)

Whenever the user logs in, I take this array and make sure all the previous upvotes and downvotes of the user are as it is. If there is a new vote,I add it to the array.

Is there any better solution?

P.S. Not necceassary but my current database structure.

class Question(models.Model):
    QID = models.CharField( default="",max_length=1000, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=1000, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID

I am using Django. And I basically want whatever stackoverflow has implemented for their voting of questions and answers.


问:
Excel VBA macro finds and deletes only some of the needed cells
I'd like to create a really simple VBA macro for Excel which looks within a range of 9 columns and variable number of rows and finds cells containing specific words, then deletes their contents.
And I have this code currently:

```<code>Sub FindAllAndDelete()
'
'
    Dim SearchRange As Range

    Range("B58:J58").Select
    Range(Selection, Selection.End(xlDown)).Select
    Set SearchRange = Range(Selection, Selection.End(xlDown))

    Do While Not IsEmpty(SearchRange)
      Set c1 = SearchRange.Find("Missing")
        c1.ClearContents
      Set c2 = SearchRange.Find("NR")
        c2.ClearContents
      Set c3 = SearchRange.Find("NO")
        c3.ClearContents
    Loop

End Sub
</code>```

which seems to find and delete the contents of only some of those cells, not all of them.
Could you tell me why this happens and maybe give me a hint how to fix it?

答:
Basically find will give you only the first instance of the item that you are looking you. You will have to use findnext as given below</p>

```<code>Set SearchRange = Range("B58:J158")
  Set c = SearchRange.Find("NO")
  If Not c Is Nothing Then
    Do
        c.ClearContents
        Set c = SearchRange.FindNext(c)
    Loop While Not c Is Nothing
  End If
</code>```

Body:
I'd like to create a really simple VBA macro for Excel which looks within a range of 9 columns and variable number of rows and finds cells containing specific words, then deletes their contents.
And I have this code currently:

Sub FindAllAndDelete()
'
'
    Dim SearchRange As Range

    Range("B58:J58").Select
    Range(Selection, Selection.End(xlDown)).Select
    Set SearchRange = Range(Selection, Selection.End(xlDown))

    Do While Not IsEmpty(SearchRange)
      Set c1 = SearchRange.Find("Missing")
        c1.ClearContents
      Set c2 = SearchRange.Find("NR")
        c2.ClearContents
      Set c3 = SearchRange.Find("NO")
        c3.ClearContents
    Loop

End Sub

which seems to find and delete the contents of only some of those cells, not all of them.
Could you tell me why this happens and maybe give me a hint how to fix it?

Body:
Basically find will give you only the first instance of the item that you are looking you. You will have to use findnext as given below

Set SearchRange = Range("B58:J158")
  Set c = SearchRange.Find("NO")
  If Not c Is Nothing Then
    Do
        c.ClearContents
        Set c = SearchRange.FindNext(c)
    Loop While Not c Is Nothing
  End If


问:
Laravel 5.4 and Wordpress integration on ubuntu nginx
I am not finding a complete guide on how to integrate a wordpress to a already deployed laravel application for a begginer on ubuntu 14.04 nginx server (I am using digital ocean ) to create a blog with it using subdomain like example.com/blog

答: Create a new folder named blog in your laravel public folder, and install wordpress into it.


问:
Given a BST and its root, print all sequences of nodes which give rise to the same bst
Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.

Given a bst, say

```<code>  3
 /  \
1    5
</code>```

the answer should be 3,1,5 and 3,5,1.

another example

```<code>       5
     /   \
    4     7
   /     / \
  1     6   10
</code>```

the outputs will be

5,4,1,7,6,10

5,4,7,6,10,1

5,7,6,10,4,1

etc

The invariant here however is that the parent's index must always be lesser than its children. I am having difficulty implementing it.

答:
well here is my python code which does producing all sequences of elements/numbers for same BST.
for the logic i referred to the book  cracking the coding interview by Gayle Laakmann Mcdowell</p>

```<code>from binarytree import  Node, bst, pprint

def wavelist_list(first, second, wave, prefix):
    if first:
       fl = len(first)
    else:
       fl = 0

    if second:
        sl = len(second)
    else:
       sl = 0
    if fl == 0 or sl == 0:
       tmp = list()
       tmp.extend(prefix)
       if first:
          tmp.extend(first)
       if second:
          tmp.extend(second)
       wave.append(tmp)
       return

    if fl:
        fitem = first.pop(0)
        prefix.append(fitem)
        wavelist_list(first, second, wave, prefix)
        prefix.pop()
        first.insert(0, fitem)

    if sl:
        fitem = second.pop(0)
        prefix.append(fitem)
        wavelist_list(first, second, wave, prefix)
        prefix.pop()
        second.insert(0, fitem)

def allsequences(root):
    result = list()
    if root == None:
       return result

    prefix = list()
    prefix.append(root.value)

    leftseq = allsequences(root.left)
    rightseq = allsequences(root.right)
    lseq = len(leftseq)
    rseq = len(rightseq)

    if lseq and rseq:
       for i in range(lseq):
          for j in range(rseq):
            wave = list()
            wavelist_list(leftseq[i], rightseq[j], wave, prefix)
            for k in range(len(wave)):
                result.append(wave[k])

    elif lseq:
      for i in range(lseq):
        wave = list()
        wavelist_list(leftseq[i], None, wave, prefix)
        for k in range(len(wave)):
            result.append(wave[k])

    elif rseq:
      for j in range(rseq):
        wave = list()
        wavelist_list(None, rightseq[j], wave, prefix)
        for k in range(len(wave)):
            result.append(wave[k])
   else:
       result.append(prefix)

   return result

if __name__=="__main__":
    n = int(input("what is height of tree?"))
    my_bst = bst(n)
    pprint(my_bst)

    seq = allsequences(my_bst)
    print("All sequences")
    for i in range(len(seq)):
        print("set %d = " %(i+1), end="")
        print(seq[i])

 example output:
 what is height of tree?3

       ___12
      /     \
  __ 6       13
 /   \        \
 0     11       14
  \
   2

  All sequences
  set 1 = [12, 6, 0, 2, 11, 13, 14]
  set 2 = [12, 6, 0, 2, 13, 11, 14]
  set 3 = [12, 6, 0, 2, 13, 14, 11]
  set 4 = [12, 6, 0, 13, 2, 11, 14]
  set 5 = [12, 6, 0, 13, 2, 14, 11]
  set 6 = [12, 6, 0, 13, 14, 2, 11]
  set 7 = [12, 6, 13, 0, 2, 11, 14]
  set 8 = [12, 6, 13, 0, 2, 14, 11]
  set 9 = [12, 6, 13, 0, 14, 2, 11]
  set 10 = [12, 6, 13, 14, 0, 2, 11]
  set 11 = [12, 13, 6, 0, 2, 11, 14]
  set 12 = [12, 13, 6, 0, 2, 14, 11]
  set 13 = [12, 13, 6, 0, 14, 2, 11]
  set 14 = [12, 13, 6, 14, 0, 2, 11]
  set 15 = [12, 13, 14, 6, 0, 2, 11]
  set 16 = [12, 6, 0, 11, 2, 13, 14]
  set 17 = [12, 6, 0, 11, 13, 2, 14]
  set 18 = [12, 6, 0, 11, 13, 14, 2]
  set 19 = [12, 6, 0, 13, 11, 2, 14]
  set 20 = [12, 6, 0, 13, 11, 14, 2]
  set 21 = [12, 6, 0, 13, 14, 11, 2]
  set 22 = [12, 6, 13, 0, 11, 2, 14]
  set 23 = [12, 6, 13, 0, 11, 14, 2]
  set 24 = [12, 6, 13, 0, 14, 11, 2]
  set 25 = [12, 6, 13, 14, 0, 11, 2]
  set 26 = [12, 13, 6, 0, 11, 2, 14]
  set 27 = [12, 13, 6, 0, 11, 14, 2]
  set 28 = [12, 13, 6, 0, 14, 11, 2]
  set 29 = [12, 13, 6, 14, 0, 11, 2]
  set 30 = [12, 13, 14, 6, 0, 11, 2]
  set 31 = [12, 6, 11, 0, 2, 13, 14]
  set 32 = [12, 6, 11, 0, 13, 2, 14]
  set 33 = [12, 6, 11, 0, 13, 14, 2]
  set 34 = [12, 6, 11, 13, 0, 2, 14]
  set 35 = [12, 6, 11, 13, 0, 14, 2]
  set 36 = [12, 6, 11, 13, 14, 0, 2]
  set 37 = [12, 6, 13, 11, 0, 2, 14]
  set 38 = [12, 6, 13, 11, 0, 14, 2]
  set 39 = [12, 6, 13, 11, 14, 0, 2]
  set 40 = [12, 6, 13, 14, 11, 0, 2]
  set 41 = [12, 13, 6, 11, 0, 2, 14]
  set 42 = [12, 13, 6, 11, 0, 14, 2]
  set 43 = [12, 13, 6, 11, 14, 0, 2]
  set 44 = [12, 13, 6, 14, 11, 0, 2]
  set 45 = [12, 13, 14, 6, 11, 0, 2]
</code>```

Body:
Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.

Given a bst, say

  3
 /  \
1    5

the answer should be 3,1,5 and 3,5,1.

another example

       5
     /   \
    4     7
   /     / \
  1     6   10

the outputs will be

5,4,1,7,6,10

5,4,7,6,10,1

5,7,6,10,4,1

etc

The invariant here however is that the parent's index must always be lesser than its children. I am having difficulty implementing it.

Body:
well here is my python code which does producing all sequences of elements/numbers for same BST.
for the logic i referred to the book  cracking the coding interview by Gayle Laakmann Mcdowell

from binarytree import  Node, bst, pprint

def wavelist_list(first, second, wave, prefix):
    if first:
       fl = len(first)
    else:
       fl = 0

    if second:
        sl = len(second)
    else:
       sl = 0
    if fl == 0 or sl == 0:
       tmp = list()
       tmp.extend(prefix)
       if first:
          tmp.extend(first)
       if second:
          tmp.extend(second)
       wave.append(tmp)
       return

    if fl:
        fitem = first.pop(0)
        prefix.append(fitem)
        wavelist_list(first, second, wave, prefix)
        prefix.pop()
        first.insert(0, fitem)

    if sl:
        fitem = second.pop(0)
        prefix.append(fitem)
        wavelist_list(first, second, wave, prefix)
        prefix.pop()
        second.insert(0, fitem)

def allsequences(root):
    result = list()
    if root == None:
       return result

    prefix = list()
    prefix.append(root.value)

    leftseq = allsequences(root.left)
    rightseq = allsequences(root.right)
    lseq = len(leftseq)
    rseq = len(rightseq)

    if lseq and rseq:
       for i in range(lseq):
          for j in range(rseq):
            wave = list()
            wavelist_list(leftseq[i], rightseq[j], wave, prefix)
            for k in range(len(wave)):
                result.append(wave[k])

    elif lseq:
      for i in range(lseq):
        wave = list()
        wavelist_list(leftseq[i], None, wave, prefix)
        for k in range(len(wave)):
            result.append(wave[k])

    elif rseq:
      for j in range(rseq):
        wave = list()
        wavelist_list(None, rightseq[j], wave, prefix)
        for k in range(len(wave)):
            result.append(wave[k])
   else:
       result.append(prefix)

   return result

if __name__=="__main__":
    n = int(input("what is height of tree?"))
    my_bst = bst(n)
    pprint(my_bst)

    seq = allsequences(my_bst)
    print("All sequences")
    for i in range(len(seq)):
        print("set %d = " %(i+1), end="")
        print(seq[i])

 example output:
 what is height of tree?3

       ___12
      /     \
  __ 6       13
 /   \        \
 0     11       14
  \
   2

  All sequences
  set 1 = [12, 6, 0, 2, 11, 13, 14]
  set 2 = [12, 6, 0, 2, 13, 11, 14]
  set 3 = [12, 6, 0, 2, 13, 14, 11]
  set 4 = [12, 6, 0, 13, 2, 11, 14]
  set 5 = [12, 6, 0, 13, 2, 14, 11]
  set 6 = [12, 6, 0, 13, 14, 2, 11]
  set 7 = [12, 6, 13, 0, 2, 11, 14]
  set 8 = [12, 6, 13, 0, 2, 14, 11]
  set 9 = [12, 6, 13, 0, 14, 2, 11]
  set 10 = [12, 6, 13, 14, 0, 2, 11]
  set 11 = [12, 13, 6, 0, 2, 11, 14]
  set 12 = [12, 13, 6, 0, 2, 14, 11]
  set 13 = [12, 13, 6, 0, 14, 2, 11]
  set 14 = [12, 13, 6, 14, 0, 2, 11]
  set 15 = [12, 13, 14, 6, 0, 2, 11]
  set 16 = [12, 6, 0, 11, 2, 13, 14]
  set 17 = [12, 6, 0, 11, 13, 2, 14]
  set 18 = [12, 6, 0, 11, 13, 14, 2]
  set 19 = [12, 6, 0, 13, 11, 2, 14]
  set 20 = [12, 6, 0, 13, 11, 14, 2]
  set 21 = [12, 6, 0, 13, 14, 11, 2]
  set 22 = [12, 6, 13, 0, 11, 2, 14]
  set 23 = [12, 6, 13, 0, 11, 14, 2]
  set 24 = [12, 6, 13, 0, 14, 11, 2]
  set 25 = [12, 6, 13, 14, 0, 11, 2]
  set 26 = [12, 13, 6, 0, 11, 2, 14]
  set 27 = [12, 13, 6, 0, 11, 14, 2]
  set 28 = [12, 13, 6, 0, 14, 11, 2]
  set 29 = [12, 13, 6, 14, 0, 11, 2]
  set 30 = [12, 13, 14, 6, 0, 11, 2]
  set 31 = [12, 6, 11, 0, 2, 13, 14]
  set 32 = [12, 6, 11, 0, 13, 2, 14]
  set 33 = [12, 6, 11, 0, 13, 14, 2]
  set 34 = [12, 6, 11, 13, 0, 2, 14]
  set 35 = [12, 6, 11, 13, 0, 14, 2]
  set 36 = [12, 6, 11, 13, 14, 0, 2]
  set 37 = [12, 6, 13, 11, 0, 2, 14]
  set 38 = [12, 6, 13, 11, 0, 14, 2]
  set 39 = [12, 6, 13, 11, 14, 0, 2]
  set 40 = [12, 6, 13, 14, 11, 0, 2]
  set 41 = [12, 13, 6, 11, 0, 2, 14]
  set 42 = [12, 13, 6, 11, 0, 14, 2]
  set 43 = [12, 13, 6, 11, 14, 0, 2]
  set 44 = [12, 13, 6, 14, 11, 0, 2]
  set 45 = [12, 13, 14, 6, 11, 0, 2]


问:
The behavior of `attribute_changed?` inside of after callbacks will be changing
I just upgraded a project to Rails 5.1.0 and I'm seeing this deprecation warning.

```<code>DEPRECATION WARNING: The behavior of `attribute_changed?`
inside of after callbacks will be changing in the next version of Rails.
The new return value will reflect the behavior of calling the method
after `save` returned (e.g. the opposite of what it returns now).
To maintain the current behavior, use `saved_change_to_attribute?` instead.
</code>```

My code looks like this

```<code>class MyClass
  before_valiadtion :my_method

  def my_method
    if name_changed?
      ...
    end
  end
end
</code>```

I do not understand exactly the deprecation warning. If I use saved_change_to_name instead it will check it after it is saved but this is before validation callback.

I also noticed that if I change the name_changed? to saved_change_to_name my specs are not passing.

I'm having a hard time understanding what the appropriate way to this should be. It seems to me that how it was before it was doing the job okay, not fully understand the reason behind this change and how I should avoid these deprecation warnings.

答:
There are new names for these methods that more clearly express wether you're looking for a change that has just been saved, or one that is about to be saved.

In your case, the latter one, you're supposed to use will_save_change_to_attribute?(:name).

The deprecation warning is really misleading as it only mentions the first case, and assumes it must occur in an after callback.

Body:
I just upgraded a project to Rails 5.1.0 and I'm seeing this deprecation warning.

DEPRECATION WARNING: The behavior of `attribute_changed?`
inside of after callbacks will be changing in the next version of Rails.
The new return value will reflect the behavior of calling the method
after `save` returned (e.g. the opposite of what it returns now).
To maintain the current behavior, use `saved_change_to_attribute?` instead.

My code looks like this

class MyClass
  before_valiadtion :my_method

  def my_method
    if name_changed?
      ...
    end
  end
end

I do not understand exactly the deprecation warning. If I use saved_change_to_name instead it will check it after it is saved but this is before validation callback.

I also noticed that if I change the name_changed? to saved_change_to_name my specs are not passing.

I'm having a hard time understanding what the appropriate way to this should be. It seems to me that how it was before it was doing the job okay, not fully understand the reason behind this change and how I should avoid these deprecation warnings.