问:
Error parsing XML: not well-formed (invalid token) in Android
I am learning android development and facing problems while building the project.
I am making a calculator app:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_alignParentBottom="true"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.palakjain.simplecalculator.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="100dp"
        android:layout_marginBottom="20dp"
        android:id="@+id/textView" />

        <!--<Button
            android:id="@+id/btnErase"
            android:text="<-"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnClear"
            android:text="C"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnPercentage"
            android:text="%"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnDivide"
            android:text="/"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn1"
            android:text="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn2"
            android:text="2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn3"
            android:text="3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnMul"
            android:text="X"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout2"
        android:layout_below="@+id/linearLayout">

        <Button
            android:id="@+id/btn4"
            android:text="4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn5"
            android:text="5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn6"
            android:text="6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnSub"
            android:text="-"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout">

        <Button
            android:id="@+id/btn7"
            android:text="7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn8"
            android:text="8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn9"
            android:text="9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnAdd"
            android:text="+"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/btnPoint"
            android:text="."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn0"
            android:text="0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnEquals"
            android:text="="
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>
</code>```

This is what I have done in my XML file and I am not able to figure out what's wrong. Kindly help.

答:
Use attribute android:layout_width="wrap_content" to btnClear instead of match_parent to show btnPercentage and btnDivide on screen.

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/btnClear"
        android:text="C"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnPercentage"
        android:text="%"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnDivide"
        android:text="/"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

Finally, Clean and Rebuild your project and Run again.

UPDATE:

Error parsing XML: not well-formed (invalid token) in Android

I guess this problem is occurring due to android:text="<-". If you want to show "<-" as Text on Button, then use below code:

```<code><Button
    android:id="@+id/btnClear"
    android:text="<-"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</code>```

FYI, here < represents <. Hope this will work~

Body:
I am learning android development and facing problems while building the project.
I am making a calculator app:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_alignParentBottom="true"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.palakjain.simplecalculator.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="100dp"
        android:layout_marginBottom="20dp"
        android:id="@+id/textView" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnClear"
            android:text="C"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnPercentage"
            android:text="%"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnDivide"
            android:text="/"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn1"
            android:text="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn2"
            android:text="2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn3"
            android:text="3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnMul"
            android:text="X"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout2"
        android:layout_below="@+id/linearLayout">

        <Button
            android:id="@+id/btn4"
            android:text="4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn5"
            android:text="5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn6"
            android:text="6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnSub"
            android:text="-"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout">

        <Button
            android:id="@+id/btn7"
            android:text="7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn8"
            android:text="8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn9"
            android:text="9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnAdd"
            android:text="+"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/btnPoint"
            android:text="."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn0"
            android:text="0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnEquals"
            android:text="="
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

This is what I have done in my XML file and I am not able to figure out what's wrong. Kindly help.

Body:
Use attribute android:layout_width="wrap_content" to btnClear instead of match_parent to show btnPercentage and btnDivide on screen.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/btnClear"
        android:text="C"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnPercentage"
        android:text="%"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnDivide"
        android:text="/"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Finally, Clean and Rebuild your project and Run again.

UPDATE:

Error parsing XML: not well-formed (invalid token) in Android

I guess this problem is occurring due to android:text="<-". If you want to show "<-" as Text on Button, then use below code:

<Button
    android:id="@+id/btnClear"
    android:text="&lt;-"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

FYI, here &lt; represents <. Hope this will work~


来源: stackexchange

问:
AnkhSVN not showing in Visual Studio 2017
I cannot see AnkhSVN as an option under "Tools - Options - Source Control" in Visual Studio 2017.  I have uninstalled and reinstalled AnkhSVN, but no effect.

Is there a way to fix this?

答: You have to install "Ankh.VS15Package.vsix" package along with AnkhSVN software in your system as the version of AnkhSVN that you are installing might be supporting only up to Visual Studio 2015 or less. I had the same issue and resolved it by installing the package mentioned.</p>

ContentLicense: CC BY-SA 3.0


问:
Response.Listener not working
i have a registration form for my app and the volley sends the request to the php file on the server and i see the user registered on the database, but the response listener does not receive the response which allows it to go back to homepage
this is my android code

```<code>if (rdPassword.equals(rdPassword2)) {
                if(rdEmail.matches(emailPattern)||rdEmail.matches(emailPattern2)){
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            System.out.println(response);
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");
                            if (success) {
                                pd.dismiss();
                                Intent bktohome = new Intent(driver_registration.this, home.class);
                                bktohome.putExtra("company", rdCompany);
                                startActivity(bktohome);
                                finish();
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                };
                DriverRegistration registerRequest = new DriverRegistration(rdUsername, rdPassword, rdName, rdEmail,
                        rdMobile, rdCompany, rdAddress, rdSSN, rdDLN,rdImage_encoded, responseListener);
                RequestQueue queue = Volley.newRequestQueue(driver_registration.this);
                queue.add(registerRequest);
                }
                else
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
                    builder.setMessage("Wrong Email Format...")
                            .setNegativeButton("Retry",null)
                            .create()
                            .show();
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
                builder.setMessage(" Passwords do not match")
                        .setNegativeButton("Retry", null)
                        .create()
                        .show();
            }
</code>```

DriverRegistration class

```<code>public class DriverRegistration extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://trackitfinal.hostei.com/registerDriver.php";
private Map<String , String> params;
public DriverRegistration(String username , String password , String name , String email  , int mobile , String company , String address ,
                              int SSN , int DLN,String rdImage_encoded, Response.Listener<String> listener)
{
    super(Method.POST,REGISTER_REQUEST_URL,listener,null);
    params=new HashMap<>();
    params.put("username",username);
    params.put("password",password);
    params.put("name",name);
    params.put("email",email);
    params.put("mobile",mobile+"");
    params.put("company",company);
    params.put("address",address);
    params.put("SSN",SSN+"");
    params.put("DLN",DLN+"");
    params.put("image",rdImage_encoded);
}

@Override
public Map<String, String> getParams() {
    return params;
}
</code>```

}

答: check if your Api is working and sending proper response when User hit it or it may be just updating DB.and is there Api for getting user detail you can check it by hitting it or check it in the postman.</p>

Title: Response.Listener not working

Body:
i have a registration form for my app and the volley sends the request to the php file on the server and i see the user registered on the database, but the response listener does not receive the response which allows it to go back to homepage
this is my android code

if (rdPassword.equals(rdPassword2)) {
                if(rdEmail.matches(emailPattern)||rdEmail.matches(emailPattern2)){
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            System.out.println(response);
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");
                            if (success) {
                                pd.dismiss();
                                Intent bktohome = new Intent(driver_registration.this, home.class);
                                bktohome.putExtra("company", rdCompany);
                                startActivity(bktohome);
                                finish();
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                };
                DriverRegistration registerRequest = new DriverRegistration(rdUsername, rdPassword, rdName, rdEmail,
                        rdMobile, rdCompany, rdAddress, rdSSN, rdDLN,rdImage_encoded, responseListener);
                RequestQueue queue = Volley.newRequestQueue(driver_registration.this);
                queue.add(registerRequest);
                }
                else
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
                    builder.setMessage("Wrong Email Format...")
                            .setNegativeButton("Retry",null)
                            .create()
                            .show();
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
                builder.setMessage(" Passwords do not match")
                        .setNegativeButton("Retry", null)
                        .create()
                        .show();
            }

DriverRegistration class

public class DriverRegistration extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://trackitfinal.hostei.com/registerDriver.php";
private Map<String , String> params;
public DriverRegistration(String username , String password , String name , String email  , int mobile , String company , String address ,
                              int SSN , int DLN,String rdImage_encoded, Response.Listener<String> listener)
{
    super(Method.POST,REGISTER_REQUEST_URL,listener,null);
    params=new HashMap<>();
    params.put("username",username);
    params.put("password",password);
    params.put("name",name);
    params.put("email",email);
    params.put("mobile",mobile+"");
    params.put("company",company);
    params.put("address",address);
    params.put("SSN",SSN+"");
    params.put("DLN",DLN+"");
    params.put("image",rdImage_encoded);
}

@Override
public Map<String, String> getParams() {
    return params;
}

}


问:
Java fibonacci stack overflow error
```<code>public static void main(String[] args) {
    one();
    System.out.println();
}

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();

  for (int j=0; j<i; j++) {
      System.out.println(fibonacci(j));
  }
}

public static int fibonacci(int num){
    if (num == 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}
</code>```

When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to

```<code>public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();
  System.out.println(fibonacci(j));
}
</code>```

I wont get error, even I just enter 1, could I ask why?

答:
I think you missed to handle the zero. Just try the following loop,</p>

```<code>   for (int j=1; j<=i; j++) {
    System.out.println(fibonacci(j));
    }
</code>```

Title: Java fibonacci stack overflow error

Body:
public static void main(String[] args) {
    one();
    System.out.println();
}

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();

  for (int j=0; j<i; j++) {
      System.out.println(fibonacci(j));
  }
}

public static int fibonacci(int num){
    if (num == 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}

When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();
  System.out.println(fibonacci(j));
}

I wont get error, even I just enter 1, could I ask why?

Body:
I think you missed to handle the zero. Just try the following loop,

   for (int j=1; j<=i; j++) {
    System.out.println(fibonacci(j));
    }


问:
HTML audio not stopping on variable count
It's a simple program which starts the audio in HTML as variable in betNo in javascript starts from 0.

But I am having trouble stopping the audio when variable reaches 10. I have reduced the original code to make it simpler. The counter is necessary for my program so removing it can't be an option. You can see the varible count in the console.

You can use jquery to solve as I am already using it.

Thank you in advance.

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio></code>```

答:
The solution is much simpler (cause was just a silly mistake). Thanks @Rory McCrossan for pointing that out in the comments.

I just took the var isPlaying = false; out of the setInterval function, otherwise it was being set to false even if the song was playing.

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var isPlaying = false;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio></code>```

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio></code>```

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio></code>```

Body:
It's a simple program which starts the audio in HTML as variable in betNo in javascript starts from 0.

But I am having trouble stopping the audio when variable reaches 10. I have reduced the original code to make it simpler. The counter is necessary for my program so removing it can't be an option. You can see the varible count in the console.

You can use jquery to solve as I am already using it.

Thank you in advance.

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});

<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>

Body:
The solution is much simpler (cause was just a silly mistake). Thanks @Rory McCrossan for pointing that out in the comments.

I just took the var isPlaying = false; out of the setInterval function, otherwise it was being set to false even if the song was playing.

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var isPlaying = false;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>


问:
How can I use this javafx library?

I am trying to design gui on java.

I will use this javafx library https://github.com/HanSolo/Medusa

I downloaded this lib but how can I used it?

I added external jar on my javafx project but I can not make any sample code work.

I'm working with eclipse neon and java 8. By the way I set up javafx. It is okay.

Do I need anything else for using this library?

I have gradle and maven plug-in my eclipse IDE.

答:
Don't directly download this file, use something like maven or gradle for this:

If you scroll down on this page: https://bintray.com/hansolo/Medusa/Medusa you will find the copy-paste parts.

There even is an example-project using that lib: https://github.com/HanSolo/medusademo

ContentLicense: CC BY-SA 4.0

Title: How can I use this javafx library?


问:
How to replace the contents of a page with an iframe containing the contents of the page?
I am trying to create a chrome extension that places the contents of the current page into one iframe, and the contents of another page into another iframe, and show them side-by-side (both iframes are width:50%;float:left).

What I've got is:

```<code>var h = jQuery('html');
h.html('<iframe src="data:text/html;charset=utf-8,' + escape(h.html()) + '" style="width:50%; float:left;"></iframe><iframe src="...');
</code>```

My problem is it is not rendering css or loading the js.

As a stop-gap I am setting the src attribute as the location.href, but that is only doing a GET of the current page, the contents of which may change on POST.

How do I get the iframe to render the css and js?

答:
This issue is due to the resources of the iframe being unable to work out what the host is. As such, because my references are all relative, they could not work out the full path. I.e. I have set the src of the iframe to a string of HTML, and the css path is similar to /css/styles.css - it cannot resolve /css/styles.css relative to the string of HTML.

The solution is add a <base href="" /> tag to the head of the HTML:

```<code>h.find('head').prepend('<base href="'+location.origin+'"/>');
</code>```

The full script now looks like:

```<code>var h = jQuery('html');
h.find('head').prepend('<base href="'+location.origin+'"/>');
h.html('<iframe src="data:text/html;charset=utf-8,' + escape(h.html()) + '" style="width:50%; float:left;"></iframe><iframe src="...');
</code>```

The base tag is telling all the relative urls to prepend the href attribute to themselves; i.e. turn the relative css url from /css/styles.css to http://example.com/css/styles.css

Body:
I am trying to create a chrome extension that places the contents of the current page into one iframe, and the contents of another page into another iframe, and show them side-by-side (both iframes are width:50%;float:left).

What I've got is:

var h = jQuery('html');
h.html('<iframe src="...');

My problem is it is not rendering css or loading the js.

As a stop-gap I am setting the src attribute as the location.href, but that is only doing a GET of the current page, the contents of which may change on POST.

How do I get the iframe to render the css and js?

Body:
This issue is due to the resources of the iframe being unable to work out what the host is. As such, because my references are all relative, they could not work out the full path. I.e. I have set the src of the iframe to a string of HTML, and the css path is similar to /css/styles.css - it cannot resolve /css/styles.css relative to the string of HTML.

The solution is add a <base href="" /> tag to the head of the HTML:

h.find('head').prepend('<base href="'+location.origin+'"/>');

The full script now looks like:

var h = jQuery('html');
h.find('head').prepend('<base href="'+location.origin+'"/>');
h.html('<iframe src="data:text/html;charset=utf-8,' + escape(h.html()) + '" style="width:50%; float:left;"></iframe><iframe src="...');

The base tag is telling all the relative urls to prepend the href attribute to themselves; i.e. turn the relative css url from /css/styles.css to http://example.com/css/styles.css


问:
Can't send file correct URI using FileProvider
I'm creating a file with this path

```<code>File file = new File(getExternalFilesDir(null) + "/package.apk");
</code>```

then I'm trying to send it using this code

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(FileProvider.getUriForFile(UpdateActivity.this, getPackageName() + ".provider", file), "application/vnd.android.package-archive");
Log.d("uri",FileProvider.getUriForFile(UpdateActivity.this, getPackageName() + ".provider", file).toString());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</code>```

my android manifest is

```<code><provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" />
</provider>
</code>```

and the provider_paths

```<code><?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="files" path="." />
</paths>
</code>```

After running code I'm getting There was a problem parsing the package error but if I open the file using file manager from path Android/my.package.name/files/package.apk it's parsing so the URI I'm sending is incorrect then I tried to print it and the result is

```<code>content://my.package.name.provider/files/package.apk
</code>```

what am I doing wrong?

答:
You forgot to add FLAG_GRANT_READ_URI_PERMISSION on the Intent. As it stands, the Uri is valid, but the installer has no rights to access its content.

Also note that the stock Android installer only supports content schemes as of Android 7.0. Older Android devices are limited to file.

Body:
I'm creating a file with this path

File file = new File(getExternalFilesDir(null) + "/package.apk");

then I'm trying to send it using this code

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(FileProvider.getUriForFile(UpdateActivity.this, getPackageName() + ".provider", file), "application/vnd.android.package-archive");
Log.d("uri",FileProvider.getUriForFile(UpdateActivity.this, getPackageName() + ".provider", file).toString());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

my android manifest is

<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" />
</provider>

and the provider_paths

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="files" path="." />
</paths>

After running code I'm getting There was a problem parsing the package error but if I open the file using file manager from path Android/my.package.name/files/package.apk it's parsing so the URI I'm sending is incorrect then I tried to print it and the result is

content://my.package.name.provider/files/package.apk

what am I doing wrong?


问:
Visual Studio 2010 "Not enough storage is available to process this command"
I'm fighting with VS 2010 and this error that seems to be very common in previous versions, but it looks like not everyone is having it in the latest version.
I've got VS 2010 SP1 and I'm getting this error quite often.

The problem is that it's not even enough to restart VS in order to make it go away, I usually have to restart my PC, and I'm losing a lot of time doing this (it's quite frequent)

I've got Windows 7 32bits (can't upgrade to 64 bits, the company doesn't allow it), and I can't do things like creating another solution (please don't reply this :) )

I've used the command to make devenv.exe LARGEADDRESSAWARE, but the error keeps on happening.
My virtual memory size is set to automatic, and the weird thing is that VS doesn't even take 2GB of ram, so I don't know if the error is really because it's lacking memory, or if it's some bug in the program

Any ideas, things to try, something?

答:
Check the output project type in properties. In my case it was changed to "Windows Application" though it was a "Console Application".

Switching back to console application solved my problem.


问:
How to display multiple flashmessages in the backend of OctoberCMS
Currently OctoberCMS only displays first flash message of each type (success, error etc). There is an issue about it too in github.

I need to show all the messages. A very simple use case is when deleting records in a list. If some of the records are not deleted, then error messages should be shown about them and also a success message saying which ones were deleted successfully.

Can someone suggest a workaround for this issue so that multiple messages can be shown?

答:
One solution is to swap out the native notifications functionality by overriding the defalt layout in flash_messages.htm with something like this (using Noty)

```<code>    <?php
    $types = ['success', 'info', 'warning', 'error'];
    ?>

    <script type="text/javascript">
        <?php
        foreach ($types as $type) {
            foreach (Flash::$type() as $message): ?>
                new Noty({
                    type: '<?=$type?>',
                    layout: 'topCenter',
                    text: '<?= e($message) ?>',
                    timeout: 5000,
                    progressBar: false,
                    closeWith: ['click', 'button']
                }).show()
            <?php endforeach;
        }
        ?>
    </script>
</code>```

Body:
One solution is to swap out the native notifications functionality by overriding the defalt layout in flash_messages.htm with something like this (using Noty)

    <?php
    $types = ['success', 'info', 'warning', 'error'];
    ?>

    <script type="text/javascript">
        <?php
        foreach ($types as $type) {
            foreach (Flash::$type() as $message): ?>
                new Noty({
                    type: '<?=$type?>',
                    layout: 'topCenter',
                    text: '<?= e($message) ?>',
                    timeout: 5000,
                    progressBar: false,
                    closeWith: ['click', 'button']
                }).show()
            <?php endforeach;
        }
        ?>
    </script>


问:
Simulation from a customised distribution in R
Does anyone know how to simulate random variables from the following probability density function (pdf):

where g(x) is the pdf for standard normal distribution N(0,1).
I understand that simulating random variables from customised distribution involves finding the cumulative density function and using the uniform distribution (as there were similar questions on this topic in this platform also). However, the pdf I have here looks a bit more complicated than the other examples I came across before. For example, I would imagine that finding the cumulative density function (need to integrate) is not so straight forward. Can anyone give me advice on how to solve this? Or is there another simpler method to simulate from the above distribution?
Look forward to your advice. Thanks!

答: You might try a Markov chain Monte Carlo approach such as the Metropolis-Hastings Algorithm. https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm</p>


问:
Javascript RegEx : Match repeating character exactly twice (ignore if it matches 3 times)
I am parsing strings for tokens that have 2 types of delimiter (similar to mustache templates).

I need a pure reg ex solution that matches {{bob}} in this is {{bob}} a double token. But does NOT match in this is {{{bob}}} a triple token

I am matching the double with

```<code>\{\{[^\{]([\s\S]+?)[^\}]\}\}
</code>```

However, it matches the {{bob}} within the triple {{{bob}}}.

Without the negative look behind i'm struggling to find a pure regex solution.  Any pointers?

答:
You could search any whitespace char outside the brackets, something like this:

\s(\{\{([^\{\}]+?)\}\})\s

Body:
I am parsing strings for tokens that have 2 types of delimiter (similar to mustache templates).

I need a pure reg ex solution that matches {{bob}} in this is {{bob}} a double token. But does NOT match in this is {{{bob}}} a triple token

I am matching the double with

\{\{[^\{]([\s\S]+?)[^\}]\}\}

However, it matches the {{bob}} within the triple {{{bob}}}.

Without the negative look behind i'm struggling to find a pure regex solution.  Any pointers?


问:
PHP imagettftext always drawing black
Basically when I draw text it's ending up black like this: http://i.stack.imgur.com/z675F.png
Instead of the color I'm allocated in PHP and the function.
Code:

```<code>    $finalImage = imagecreatefrompng($imageFile);
    $logo = imagecreatefrompng($logoImage);
    imagecopy($finalImage, $logo, $logoPosition['x'], $logoPosition['y'], 0, 0, imagesx($logo), imagesy($logo));
    $font = "arial.ttf";
    $fontSize = 10;
    $yOffSet = 15;
    $white = imagecolorallocate($finalImage, 255, 255, 255);
    foreach($pixelArray as $key => $x) {
        foreach($valueArray[$key] as $valueText) {

            imagettftext($finalImage, $fontSize, 0, $x, $yOffSet, $white, $font, $valueText);
            $yOffSet += 15;
        }
        $yOffSet = 15;
    }
    if($miscText != null) {
        foreach($miscText as $key => $text) {
            imagettftext($finalImage, $fontSize, 0, $text['x'], $text['y'], $white, $font, $text['text']);
        }
    }
    imagepng($finalImage,$saveFileName.".png");
    imagedestroy($finalImage);
</code>```

It was working before, but then it just stopped and I have no clue why. It was after I changed the source image (Was generating fine) and I hadn't touched the code. I've tried all sorts of things with changing the colors, but I can't get it to display in anything other then black.

答:
Fixed it by changing imagecolorallocate to imagecolorclosest since I already some white text on a logo I copy in:

```<code>//       imagecolorallocate....
$white = imagecolorclosest($im, 255, 255, 255);
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP imagettftext always drawing black

Body:
Basically when I draw text it's ending up black like this: http://i.stack.imgur.com/z675F.png
Instead of the color I'm allocated in PHP and the function.
Code:

    $finalImage = imagecreatefrompng($imageFile);
    $logo = imagecreatefrompng($logoImage);
    imagecopy($finalImage, $logo, $logoPosition['x'], $logoPosition['y'], 0, 0, imagesx($logo), imagesy($logo));
    $font = "arial.ttf";
    $fontSize = 10;
    $yOffSet = 15;
    $white = imagecolorallocate($finalImage, 255, 255, 255);
    foreach($pixelArray as $key => $x) {
        foreach($valueArray[$key] as $valueText) {

            imagettftext($finalImage, $fontSize, 0, $x, $yOffSet, $white, $font, $valueText);
            $yOffSet += 15;
        }
        $yOffSet = 15;
    }
    if($miscText != null) {
        foreach($miscText as $key => $text) {
            imagettftext($finalImage, $fontSize, 0, $text['x'], $text['y'], $white, $font, $text['text']);
        }
    }
    imagepng($finalImage,$saveFileName.".png");
    imagedestroy($finalImage);

It was working before, but then it just stopped and I have no clue why. It was after I changed the source image (Was generating fine) and I hadn't touched the code. I've tried all sorts of things with changing the colors, but I can't get it to display in anything other then black.

Body:
Fixed it by changing imagecolorallocate to imagecolorclosest since I already some white text on a logo I copy in:

//       imagecolorallocate....
$white = imagecolorclosest($im, 255, 255, 255);


问:
How to Disable the Mouse wheel click Button?
I'm trying to find a way of disabling the default action of the mouse wheel button which is to open the link in a new tab.

Is that possible?

答:
My code:</p>

```<code>$(document).on('auxclick', 'a', function(e) {
if (e.which === 2) { //middle Click
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    return false;
}
return true;
</code>```

Body:
My code:

$(document).on('auxclick', 'a', function(e) {
if (e.which === 2) { //middle Click
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    return false;
}
return true;


问:
Treat Userform as a Function
I have created a VBA UserForm which is essentially a glorified input box

Just like an input box can be employed like this

```<code>Dim returnVal As String
returnVal = InputBox("Write some string")
</code>```

I would like my userform to run like this

```<code>Dim returnVal As customClass
Set returnVal = MyUserForm([some arguments])
</code>```

ie. the MyUserForm() code passes some arguments to the userform, and when the userform is closed, it gets some arguments back (in the form of a custom class rather than a plain string)

What's the best way of structuring my userform to allow this functionality?

Currently, I'm just declaring some variables and the custom class publicly. I'm catching command button clicks and Query_close() events to hide the form, then I read the outputVal and close the form completely. I don't like this because I'd like my form to be totally self contained, and I think the capturing of events is messy.

In simplified code (read/return a string):

```<code>Function myUf(inVal As String) As String
Dim frm As New frmTest
frm.inputval = inVal
frm.Init 'sets caption. We cannot rely on userform initialize as this runs before inputval is set
         'We could pass a variable here to save writing to the public variable
frm.Show
myUf = frm.outputVal
Set frm = Nothing
End Function
</code>```

And in my Userform called frmTest with a textbox called tb1

```<code>Public inputval As String
Public outputVal As String

Public Sub Init()
Me.Caption = inputval 'setting caption, but could pass this anywhere
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then Cancel = 1
outputVal = tb1 'reading value from textbox, but could return anything here
Me.Hide
End Sub
</code>```

答:
You need to find a way to initiate the UserForm from a ClassObject. Then, you can use a simple factory pattern to create the UserForm exactly the way you want.

In general, I have copied a bit of the code of Mat's Mug somewhere in StackOverflow and I wrote an article about the User Forms. If you take a look here (http://www.vitoshacademy.com/vba-the-perfect-userform-in-vba/) you will find a way to initialize the form with Public Sub ShowMainForm() It's possible to add a parameter to the ShowMainForm, then pass it to the initializer of the class.

In general, take the code from the article, make sure it works, and change the ShowMainForm initializer to the following:

```<code>Public Sub ShowMainForm(strText As String, strText2 As String)

    If (objPresenter Is Nothing) Then
        Set objPresenter = New clsSummaryPresenter
    End If

    objPresenter.Show
    Call objPresenter.ChangeLabelAndCaption(strText, strText2)

End Sub
</code>```

Then, if you call like this in the immediate window:

```<code>call ShowMainForm("Just","testing")
</code>```

You will get this:

Which is quite what you need. :)

Title: Treat Userform as a Function

Body:
I have created a VBA UserForm which is essentially a glorified input box

Just like an input box can be employed like this

Dim returnVal As String
returnVal = InputBox("Write some string")

I would like my userform to run like this

Dim returnVal As customClass
Set returnVal = MyUserForm([some arguments])

ie. the MyUserForm() code passes some arguments to the userform, and when the userform is closed, it gets some arguments back (in the form of a custom class rather than a plain string)

What's the best way of structuring my userform to allow this functionality?

Currently, I'm just declaring some variables and the custom class publicly. I'm catching command button clicks and Query_close() events to hide the form, then I read the outputVal and close the form completely. I don't like this because I'd like my form to be totally self contained, and I think the capturing of events is messy.

In simplified code (read/return a string):

Function myUf(inVal As String) As String
Dim frm As New frmTest
frm.inputval = inVal
frm.Init 'sets caption. We cannot rely on userform initialize as this runs before inputval is set
         'We could pass a variable here to save writing to the public variable
frm.Show
myUf = frm.outputVal
Set frm = Nothing
End Function

And in my Userform called frmTest with a textbox called tb1

Public inputval As String
Public outputVal As String

Public Sub Init()
Me.Caption = inputval 'setting caption, but could pass this anywhere
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then Cancel = 1
outputVal = tb1 'reading value from textbox, but could return anything here
Me.Hide
End Sub

Body:
You need to find a way to initiate the UserForm from a ClassObject. Then, you can use a simple factory pattern to create the UserForm exactly the way you want.

In general, I have copied a bit of the code of Mat's Mug somewhere in StackOverflow and I wrote an article about the User Forms. If you take a look here (http://www.vitoshacademy.com/vba-the-perfect-userform-in-vba/) you will find a way to initialize the form with Public Sub ShowMainForm() It's possible to add a parameter to the ShowMainForm, then pass it to the initializer of the class.

In general, take the code from the article, make sure it works, and change the ShowMainForm initializer to the following:

Public Sub ShowMainForm(strText As String, strText2 As String)

    If (objPresenter Is Nothing) Then
        Set objPresenter = New clsSummaryPresenter
    End If

    objPresenter.Show
    Call objPresenter.ChangeLabelAndCaption(strText, strText2)

End Sub

Then, if you call like this in the immediate window:

call ShowMainForm("Just","testing")

You will get this:

Which is quite what you need. :)


问:
Check if each row of a data frame is contained in another data frame
I wrote the following function, it works. However it is very slow when df1 has 1700 rows, and df2 has 70000 rows. Is there anyway to improve the efficiency?

```<code>rowcheck <- function(df1, df2){
         apply(df1, 1, function(x) any(apply(df2, 1, function(y) all(y==x))))
}
</code>```

An example I wrote this function to apply to is: I want to check whether each row in df1 is contained as a row in df2:

```<code>df1=data.frame(a=c(1:3),b=c("a","b","c"))
df2=data.frame(a=c(1:6),b=rep(c("a","b","c"),2))
</code>```

For each row of df1, I want to check if it is contained as a row in df2. I want to return of the function to be a logical vector of length nrow(df1).

Thank you for your help.

答:
Just wanted to give my two cents on this query. A plyr-based solution:

```<code>nrow(match_df(df2, df1))
</code>```

.. Will check each row of df1 against df2 (with respect to all columns) and give you the number of rows of df1 contained in df2.

Body:
I wrote the following function, it works. However it is very slow when df1 has 1700 rows, and df2 has 70000 rows. Is there anyway to improve the efficiency?

rowcheck <- function(df1, df2){
         apply(df1, 1, function(x) any(apply(df2, 1, function(y) all(y==x))))
}

An example I wrote this function to apply to is: I want to check whether each row in df1 is contained as a row in df2:

df1=data.frame(a=c(1:3),b=c("a","b","c"))
df2=data.frame(a=c(1:6),b=rep(c("a","b","c"),2))

For each row of df1, I want to check if it is contained as a row in df2. I want to return of the function to be a logical vector of length nrow(df1).

Thank you for your help.

Body:
Just wanted to give my two cents on this query. A plyr-based solution:

nrow(match_df(df2, df1))

.. Will check each row of df1 against df2 (with respect to all columns) and give you the number of rows of df1 contained in df2.


问:
Why static initializer allow re-initialization of static variable in Java?
I am studying static initializers in Java. I came through a source code as given below:

```<code>    public class A {
       private static int count = 5;
       final static int STEP = 10;
       boolean alive;
       static {
         count = 1;
       }
       public static void main(String[] args) {
          A a = new A();
          System.out.println(A.count);
       }
    }
</code>```

My question is that why the compiler is not complaining about the variable count being reassigned the value 1 in count = 1 in the static initializer block. I know that Java allows forward referencing as long as declaration-before-read rule (i.e. any identifier should not be read before declaration) is followed which is for all initializers and if not then the reference (or identifier) must come on the left-hand side of the assignment. I also know that if multiple static initializer expressions and static field initializer blocks are written in a class then their order of execution is sequential.

According to me the flow of execution should be: The class is loaded and then all the static initializer (expressions and blocks) are executed in sequence, due to which the count will be initialized to value 5 and then the default constructor will be executed calling the super() and initializing the instance variable alive to default value. But why it is not throwing an error that static variable count has been re-initialized (as it is not the case of forward reference), instead, it gives the output 1.
Does that mean that we can re-initialize static variables through static initializer blocks?

答: As long as you manipulate the static variable within the class it is initialized you won't get an error from the compiler. If you had declared it as final the behavior you mentioned would have occurred. Keep in mind that static means that the variable is shared across all instances of the object, so it only gets initialized and memory allocated once. </p>

Body:
I am studying static initializers in Java. I came through a source code as given below:

    public class A {
       private static int count = 5;
       final static int STEP = 10;
       boolean alive;
       static {
         count = 1;
       }
       public static void main(String[] args) {
          A a = new A();
          System.out.println(A.count);
       }
    }

My question is that why the compiler is not complaining about the variable count being reassigned the value 1 in count = 1 in the static initializer block. I know that Java allows forward referencing as long as declaration-before-read rule (i.e. any identifier should not be read before declaration) is followed which is for all initializers and if not then the reference (or identifier) must come on the left-hand side of the assignment. I also know that if multiple static initializer expressions and static field initializer blocks are written in a class then their order of execution is sequential.

According to me the flow of execution should be: The class is loaded and then all the static initializer (expressions and blocks) are executed in sequence, due to which the count will be initialized to value 5 and then the default constructor will be executed calling the super() and initializing the instance variable alive to default value. But why it is not throwing an error that static variable count has been re-initialized (as it is not the case of forward reference), instead, it gives the output 1.
Does that mean that we can re-initialize static variables through static initializer blocks?


问:
python altair line chart cut off by count
I am currently trying to cut off a line chart in Altair. My code so far is:

```<code>    Chart(orient_frame).mark_line().encode(
    x = X('year:O'),
    y = Y('count(type:N)', scale=Scale(domain=(0,2500)),
    color = Color('type:N')
    )
</code>```

the count(type:N) goes up to values over 9100 and I want to cut them out of the graph entirely. But Scale() does not cut of the line, so one line 'shoots out of the graph'.

I have also already tried

```<code>    Chart(orient_frame).mark_line().encode(
        x = X('year:O'),
        y = Y('count(type:N)'),
        color = Color('type:N')
    ).transform_data(
        filter='count(type:N) < 2500'
    )
</code>```

but it just empties the output entirely. Can anyone help me here? It would be great!
This is the output of the first so far

As for a minimal working example was asked:

```<code>import altair as al
import pandas as pd

#Create a simple 1 variable example
answers = ['No' for _ in range(3)]
answers.extend(['Yes' for _ in range(5)])
answers.extend(['Maybe' for _ in range(20)])

dataframe = pd.DataFrame({'var1': answers})

#create Chart
al.Chart(dataframe).mark_bar().encode(
    x=al.X('var1:N'),
    y=al.Y('count(*):Q', scale=al.Scale(domain=(0,6)))

)
</code>```

In this example I want to 'zoom in' to the yes/no answers because I do not care about the maybe-answers.

I can fix the scale, but i can't prevent the bar of maybe to go up the full 20-ticks.

答:
By design, Altair doesn't hide any data. See: https://github.com/altair-viz/altair/issues/316#issuecomment-292560808

However, if you still wish to hide some data, you'd need to use the clamp argument.

```<code>import altair as al
import pandas as pd

#Create a simple 1 variable example
answers = ['No' for _ in range(3)]
answers.extend(['Yes' for _ in range(5)])
answers.extend(['Maybe' for _ in range(20)])

dataframe = pd.DataFrame({'var1': answers})

#create Chart
al.Chart(dataframe).mark_bar().encode(
    x=al.X('var1:N'),
    y=al.Y('count(*):Q', scale=al.Scale(domain=(0, 6), clamp=True))

)
</code>```

This produces the following output.

Body:
I am currently trying to cut off a line chart in Altair. My code so far is:

    Chart(orient_frame).mark_line().encode(
    x = X('year:O'),
    y = Y('count(type:N)', scale=Scale(domain=(0,2500)),
    color = Color('type:N')
    )

the count(type:N) goes up to values over 9100 and I want to cut them out of the graph entirely. But Scale() does not cut of the line, so one line 'shoots out of the graph'.

I have also already tried

    Chart(orient_frame).mark_line().encode(
        x = X('year:O'),
        y = Y('count(type:N)'),
        color = Color('type:N')
    ).transform_data(
        filter='count(type:N) < 2500'
    )

but it just empties the output entirely. Can anyone help me here? It would be great!
This is the output of the first so far

As for a minimal working example was asked:

import altair as al
import pandas as pd

#Create a simple 1 variable example
answers = ['No' for _ in range(3)]
answers.extend(['Yes' for _ in range(5)])
answers.extend(['Maybe' for _ in range(20)])

dataframe = pd.DataFrame({'var1': answers})

#create Chart
al.Chart(dataframe).mark_bar().encode(
    x=al.X('var1:N'),
    y=al.Y('count(*):Q', scale=al.Scale(domain=(0,6)))

)

In this example I want to 'zoom in' to the yes/no answers because I do not care about the maybe-answers.

I can fix the scale, but i can't prevent the bar of maybe to go up the full 20-ticks.

Body:
By design, Altair doesn't hide any data. See: https://github.com/altair-viz/altair/issues/316#issuecomment-292560808

However, if you still wish to hide some data, you'd need to use the clamp argument.

import altair as al
import pandas as pd

#Create a simple 1 variable example
answers = ['No' for _ in range(3)]
answers.extend(['Yes' for _ in range(5)])
answers.extend(['Maybe' for _ in range(20)])

dataframe = pd.DataFrame({'var1': answers})

#create Chart
al.Chart(dataframe).mark_bar().encode(
    x=al.X('var1:N'),
    y=al.Y('count(*):Q', scale=al.Scale(domain=(0, 6), clamp=True))

)

This produces the following output.


问:
Getter returning '0' value; not passing object?
I've just started learning Java, and I encountered a bit of a problem while writing/experimenting with a simple program.

This is the method iM that calls the getter, getDateDifference() from the class VDC.

```<code> public static void iM() {

    VDC answer = new VDC();
    long theAnswer = answer.getDateDifference();
    System.out.println(theAnswer);

    }
</code>```

Which prints out a zero.

And this is class VDC.

```<code>public class VDC {

public static long dateDifference;

    public static void main(String[] args) {
        VDC.dateDifference();
        System.out.println(dateDifference);
    }

    public static void dateDifference() throws ParseException{

        String pattern = "dd/MM/yyyy/HH/mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date startDate = format.parse("22/06/2017/15/00");
        System.out.println("Start Date: " + startDate);

        Date dNow = new Date();
        System.out.println("Current date is: " + dNow);
        long diff = dNow.getTime() - startDate.getTime();
        dateDifference = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
    }

    public long getDateDifference() {
        return dateDifference;
    }

    public void setDateDifference(long dateDifference) {
        VDC.dateDifference = dateDifference;
    }
}
</code>```

I'm fairly certain that I wrote the setter and getter correctly, and running VDC.java in Eclipse gives me the correct value of dateDifference. However, if I attempt to run the class in which method iM is written in, dateDifference returns a value of 0.

After googling for far too long, I think my problem might be that the instance dateDifference isn't set to the passed dateDifference that originates from class VDC (Sorry if I'm confusing anyone).

I have tried to apply what I found in other SOF questions to my program, but I find myself unable to do so. How can I ensure that getDateDifference() returns the correct value (instead of 0) in another class?

(I am sorry if this is a bad question; I simply am unable to apply what I've found to solve my problem)

答:
dateDifference is a static variable initialized by the static method dateDifference().

You never call that method in your iM() method, so it's not initialized.

On the other hand, when you run the main of the VDC class, you call VDC.dateDifference() which initializes that variable.

That said, it is a bad idea to have an instance getter/setter methods that return/modify a static variable. Either make getDateDifference() and setDateDifference() static methods, or make dateDifference a non-static variable.

Here's one possible implementation that could make sense:

```<code>public static void iM() {
    VDC answer = new VDC();
    answer.computeDateDifference(); // initialize the instance variable
    long theAnswer = answer.setDateDifference(); // get its value
    System.out.println(theAnswer);
}

public class VDC {

    private long dateDifference;

    public void computeDateDifference() throws ParseException {

        String pattern = "dd/MM/yyyy/HH/mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date startDate = format.parse("22/06/2017/15/00");
        System.out.println("Start Date: " + startDate);

        Date dNow = new Date();
        System.out.println("Current date is: " + dNow);
        long diff = dNow.getTime() - startDate.getTime();
        this.dateDifference = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
    }

    public long getDateDifference() {
        return dateDifference;
    }

    public void setDateDifference(long dateDifference) {
        this.dateDifference = dateDifference;
    }
}
</code>```

Body:
I've just started learning Java, and I encountered a bit of a problem while writing/experimenting with a simple program.

This is the method iM that calls the getter, getDateDifference() from the class VDC.

 public static void iM() {

    VDC answer = new VDC();
    long theAnswer = answer.getDateDifference();
    System.out.println(theAnswer);

    }

Which prints out a zero.

And this is class VDC.

public class VDC {

public static long dateDifference;

    public static void main(String[] args) {
        VDC.dateDifference();
        System.out.println(dateDifference);
    }

    public static void dateDifference() throws ParseException{

        String pattern = "dd/MM/yyyy/HH/mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date startDate = format.parse("22/06/2017/15/00");
        System.out.println("Start Date: " + startDate);

        Date dNow = new Date();
        System.out.println("Current date is: " + dNow);
        long diff = dNow.getTime() - startDate.getTime();
        dateDifference = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
    }

    public long getDateDifference() {
        return dateDifference;
    }

    public void setDateDifference(long dateDifference) {
        VDC.dateDifference = dateDifference;
    }
}

I'm fairly certain that I wrote the setter and getter correctly, and running VDC.java in Eclipse gives me the correct value of dateDifference. However, if I attempt to run the class in which method iM is written in, dateDifference returns a value of 0.

After googling for far too long, I think my problem might be that the instance dateDifference isn't set to the passed dateDifference that originates from class VDC (Sorry if I'm confusing anyone).

I have tried to apply what I found in other SOF questions to my program, but I find myself unable to do so. How can I ensure that getDateDifference() returns the correct value (instead of 0) in another class?

(I am sorry if this is a bad question; I simply am unable to apply what I've found to solve my problem)

Body:
dateDifference is a static variable initialized by the static method dateDifference().

You never call that method in your iM() method, so it's not initialized.

On the other hand, when you run the main of the VDC class, you call VDC.dateDifference() which initializes that variable.

That said, it is a bad idea to have an instance getter/setter methods that return/modify a static variable. Either make getDateDifference() and setDateDifference() static methods, or make dateDifference a non-static variable.

Here's one possible implementation that could make sense:

public static void iM() {
    VDC answer = new VDC();
    answer.computeDateDifference(); // initialize the instance variable
    long theAnswer = answer.setDateDifference(); // get its value
    System.out.println(theAnswer);
}

public class VDC {

    private long dateDifference;

    public void computeDateDifference() throws ParseException {

        String pattern = "dd/MM/yyyy/HH/mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date startDate = format.parse("22/06/2017/15/00");
        System.out.println("Start Date: " + startDate);

        Date dNow = new Date();
        System.out.println("Current date is: " + dNow);
        long diff = dNow.getTime() - startDate.getTime();
        this.dateDifference = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
    }

    public long getDateDifference() {
        return dateDifference;
    }

    public void setDateDifference(long dateDifference) {
        this.dateDifference = dateDifference;
    }
}


问:
Plugable dynamic pages on azure
I have a scenario, we have a template based website and templates are aspx web pages, our designers regularly create these templates, how can we store these templates on azure such that we just have to upload templates and not have to upload whole application package for adding just even a single template ?</p>

答:
There's a technique that was used by the Microsoft research team called a generic worker. In a nutshell, this approach required that the core application was stored elsewhere (like blob storage), then would be pulled down at run time for execution. In theory, this same approach could be used for creating a package that your web app could pull down and load as updates are applied. Thus preventing you from having to redeploy each time an update occurs.

The challenge I see here is the same one that causes issues creating reusable aspx files across web sites. At least last I tried that (several years/versions ago), it wasn't doable. So you may have that same challenge this go-round.

Title: Plugable dynamic pages on azure


问:
Safari display flex not working when elements are 25%
We have an issue on iPads and Mac thats we really annoying.

We are using bootstrap, and have created 9 elements in a .row with .col-xs-12.col-sm-5.col-md-3 classes.

On the .row we have applied a .flex-start class with the following css:

```<code>.flex-start {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: start;
  -webkit-justify-content: flex-start;
      -ms-flex-pack: start;
          justify-content: flex-start;
  -webkit-box-align: start;
  -webkit-align-items: flex-start;
      -ms-flex-align: start;
          align-items: flex-start;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
      -ms-flex-direction: row;
          flex-direction: row;
  -webkit-flex-wrap: wrap;
      -ms-flex-wrap: wrap;
          flex-wrap: wrap;
}
</code>```

In safari the first flex row only contains 3 items.

Sample here and screenshot here. you must open in safari on Mac or iPad

Setting the width of col-md-3 to 24.9% fixes this, but we dont want that hack.

Has anyone else experienced this issue, and know of a fix?

答:
Simply Add "clearfix" class to row and add "float: left;" property to all columns inside the row.

This will work fine in Safari.

Body:
We have an issue on iPads and Mac thats we really annoying.

We are using bootstrap, and have created 9 elements in a .row with .col-xs-12.col-sm-5.col-md-3 classes.

On the .row we have applied a .flex-start class with the following css:

.flex-start {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: start;
  -webkit-justify-content: flex-start;
      -ms-flex-pack: start;
          justify-content: flex-start;
  -webkit-box-align: start;
  -webkit-align-items: flex-start;
      -ms-flex-align: start;
          align-items: flex-start;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
      -ms-flex-direction: row;
          flex-direction: row;
  -webkit-flex-wrap: wrap;
      -ms-flex-wrap: wrap;
          flex-wrap: wrap;
}

In safari the first flex row only contains 3 items.

Sample here and screenshot here. you must open in safari on Mac or iPad

Setting the width of col-md-3 to 24.9% fixes this, but we dont want that hack.

Has anyone else experienced this issue, and know of a fix?


问:
RobotFramework: Switching window after clicking into a new window
Is there a way to adjust the focus (i.e bring to front) the second window after a click a link that goes to this second window in RobotFramework? I have some code that does screenshot after click and it only shows the first window

```<code>Click link  xpath=//*[contains(., "Download certificate")]
sleep  20
Select Window    Title=Certificate
Page Screenshot  Completion-Certificate
</code>```

I know that the title of the popup window is Certificate but i get error

```<code>ValueError: Unable to locate window with title 'Certificate'
</code>```

答:
I think, you are trying to test pop window which appears when you click on a link. You can use below solution,</p>

```<code>Select Window    ${windowId}    # Focus popup/required window
</code>```

Body:
Is there a way to adjust the focus (i.e bring to front) the second window after a click a link that goes to this second window in RobotFramework? I have some code that does screenshot after click and it only shows the first window

Click link  xpath=//*[contains(., "Download certificate")]
sleep  20
Select Window    Title=Certificate
Page Screenshot  Completion-Certificate

I know that the title of the popup window is Certificate but i get error

ValueError: Unable to locate window with title 'Certificate'

Body:
I think, you are trying to test pop window which appears when you click on a link. You can use below solution,

Select Window    ${windowId}    # Focus popup/required window


问:
Slick carousel not allowing image to scale properly
I'm using slick to make an image carousel. I've got it working but I want to be able to have the center image scale and be bigger than the others. I have it kinda working but the height of the container does not change when the image scales meaning the image flows outside the container and doesn't scale in height properly. I want it to work like it does here on the demo for center mode http://kenwheeler.github.io/slick/

How can I get the height to change when the image is scaled?

答:
If you carefully see their demo and increase the scale size, then you can see that even in their demo the white box will get cropped.

The solution is to give a margin to the slides so the central image has place to be seen. Following code will help you achieve what you want:

```<code>.slick-slide {
    margin: 50px 0;
}
</code>```

All I have done is, added margin top and bottom. The end result is that there is white space above and below the slides that are not active, but the empty space is covered by the scaled image in the center slide.

Working CodePen:
https://codepen.io/vikrant-icd/pen/vZjMPq

Body:
If you carefully see their demo and increase the scale size, then you can see that even in their demo the white box will get cropped.

The solution is to give a margin to the slides so the central image has place to be seen. Following code will help you achieve what you want:

.slick-slide {
    margin: 50px 0;
}

All I have done is, added margin top and bottom. The end result is that there is white space above and below the slides that are not active, but the empty space is covered by the scaled image in the center slide.

Working CodePen:
https://codepen.io/vikrant-icd/pen/vZjMPq


问:
Process the command without launching MainActivity, in Android
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

```<code><application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>
</code>```

MainActivity.java

```<code>public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}
</code>```

ScreenOffAdminReceiver.java

```<code>public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}
</code>```

permissions.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>
</code>```

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks

答:
You can try decrease time of app launch (create activity) with change theme settings:

Try use in your app style:

```<code><item name="android:windowDisablePreview">true</item>
<item name="android:windowContentOverlay">@null</item>
</code>```

Body:
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

<application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>

MainActivity.java

public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}

ScreenOffAdminReceiver.java

public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}

permissions.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks

Body:
You can try decrease time of app launch (create activity) with change theme settings:

Try use in your app style:

<item name="android:windowDisablePreview">true</item>
<item name="android:windowContentOverlay">@null</item>


问:
Typescript and ThreeJS, add to the scene inside loader
I have the following code:

```<code>export class LandingPageComponent implements OnInit {
scene: THREE.Scene;
(...)
 ngOnInit() {
(...)
this.scene = new THREE.Scene();
(...)
var loader = new THREE.JSONLoader();
loader.load("../../assets/fire_lion.json",function ( obj ) {
    this.scene.add( obj ); // The line that's giving me trouble
});
</code>```

The scene is defined and working, but when I try to run this code, I get an error which says that the scene isn't declared. It makes sense, since "this" no longer references the class, but how can I add the object to the scene then?

Thanks in advance!

PS: Using ObjectLoader simply gives me an error message saying I should be using JSONLoader.

答:
Because this in load callback has changed. Need to call bind or use TypeScript syntax which transpiles to bind call.

```<code>loader.load("../../assets/fire_lion.json",function ( obj ) {
    this.scene.add( obj );
}.bind(this)); // bind here
</code>```

or

```<code>loader.load("../../assets/fire_lion.json", ( obj ) => {
    this.scene.add( obj );
}));
</code>```

Body:
I have the following code:

export class LandingPageComponent implements OnInit {
scene: THREE.Scene;
(...)
 ngOnInit() {
(...)
this.scene = new THREE.Scene();
(...)
var loader = new THREE.JSONLoader();
loader.load("../../assets/fire_lion.json",function ( obj ) {
    this.scene.add( obj ); // The line that's giving me trouble
});

The scene is defined and working, but when I try to run this code, I get an error which says that the scene isn't declared. It makes sense, since "this" no longer references the class, but how can I add the object to the scene then?

Thanks in advance!

PS: Using ObjectLoader simply gives me an error message saying I should be using JSONLoader.

Body:
Because this in load callback has changed. Need to call bind or use TypeScript syntax which transpiles to bind call.

loader.load("../../assets/fire_lion.json",function ( obj ) {
    this.scene.add( obj );
}.bind(this)); // bind here

or

loader.load("../../assets/fire_lion.json", ( obj ) => {
    this.scene.add( obj );
}));