问:
referencing linq and other variables in HTML
How do you reference a LINQ object that you have created such as a list, (or any other variables in your code behind) in your HTML? I have seen examples of how to do this using MVC, but I am using Web Forms. I want to do something like this :

```                    <% if (customReports.Count > 0) %>
                    <% { %>
                    <% Response.Write("hello"); %>
                    <% } %> </code>
</code>```

答:
ASPX files are converted by the ASP.NET runtime into classes, which in turn inherit from their associated code-behind. This means that the standard rules of inheritance apply to variable scoping -i.e. if you have a public or protected member variable declared in your code-behind class, it will be directly accessible in the ASPX just like in your example.

Example code-behind:

```<code>public partial class MyPage : Page
{
    protected int test = 3; // This member will be accessible from the ASPX.

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
</code>```

Example ASPX:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>

<p>Hello world, my variable is <%=test%>.</p>
</code>```

Body:
How do you reference a LINQ object that you have created such as a list, (or any other variables in your code behind) in your HTML? I have seen examples of how to do this using MVC, but I am using Web Forms. I want to do something like this :

                    <% if (customReports.Count > 0) %>
                    <% { %>
                    <% Response.Write("hello"); %>
                    <% } %>

Body:
ASPX files are converted by the ASP.NET runtime into classes, which in turn inherit from their associated code-behind. This means that the standard rules of inheritance apply to variable scoping -i.e. if you have a public or protected member variable declared in your code-behind class, it will be directly accessible in the ASPX just like in your example.

Example code-behind:

public partial class MyPage : Page
{
    protected int test = 3; // This member will be accessible from the ASPX.

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

Example ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>

<p>Hello world, my variable is <%=test%>.</p>


来源: stackexchange

问:
Use database in embedded-server mode outside the `$objectdb` home directory
I'm trying to setup ObjectDB. I am able to create a database and view it with the explorer, using the embedded-server mode to be able to keep the explorer open while running my program. This all works fine, when my database is in the $objectdb/db/ directory.

However, I'd like to be able to do this when my database is in another directory (thus not in $objectdb/db/). When I'm not using the explorer, the database looks fine. I can also open the explorer to view the database. But... I can not keep the connection to my database open in the explorer while running my program (and thus making changes to the database).

What I have tried/have been thinking about:

The database and the explorer have to use the same .conf file. I think the explorer uses the conf file in the $objectdb home directory, but I can't figure out how to configure my database in the other directory to listen to that conf file, too. How can I create a project (or database) specific conf file for a database that's not in the $objectdb home directory?

In general it feels strange to me that there would be one conf file for all your ObjectDB databases.

I copied both the explorer.exe and objectdb.conf to the directory my database is in, hoping this would work. However, nothing happens when I try to run the exe file. I think this is because the exe (and the explorer.jar, tried that one, too) rely on objectdb.jar, but I couldn't find that anywhere. I found objectdb-2.7.1_01.jar and copied that into the directory the database and explorer were in, but that didn't help.

As for an MWE, I followed this tutorial, using IntelliJ.

答:
Try the following:

Open the database in embedded mode with a path that specifies a free port for the embedded server, e.g. "$objectdb/db/my.odb;port=9999"

Access this database in client mode using "objectdb://localhost:9999", or in the Explorer, select File -> Open C/S Connection, specify 9999 as the port and keep the database path empty or /

objectdb.jar is available when you download ObjectDB as a zip file (in which you also find the Explorer), you can also rename the file from Maven, which contains a version number to objectdb.jar.

ContentLicense: CC BY-SA 3.0


问:
Android application ClassNotFoundException after download and install update
I have an android app with a custom Application class.

```<code>public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Utils.isThereUpdatedVersion(this);
    }
}
</code>```

The isThereUpdatedVersion function asks a php page is. There is a new version of my app available and there is a button one goes to another activity with a button to download an install the new version.

I added the android:name attribute to my Manifest

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name=".application.MyApplication">
</code>```

When I run my app through Android Studio, the app is running perfectly. Is there is a new version i can download it and install it. But after the installation, I open the app and I get this error and the app crashes.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.andre_jacq_ing.preleveurgmail, PID: 2915
    java.lang.RuntimeException: Unable to instantiate application com.andre_jacq_ing.preleveurgmail.application.MyApplication: java.lang.ClassNotFoundException: Didn't find class "com.andre_jacq_ing.preleveurgmail.application.MyApplication" on path: DexPathList[[zip file "/data/app/com.andre_jacq_ing.preleveurgmail-1/base.apk"],nativeLibraryDirectories=[/data/app/com.andre_jacq_ing.preleveurgmail-1/lib/arm64, /system/lib64, /vendor/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:839)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5855)
        at android.app.ActivityThread.-wrap3(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6688)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.andre_jacq_ing.preleveurgmail.application.MyApplication" on path: DexPathList[[zip file "/data/app/com.andre_jacq_ing.preleveurgmail-1/base.apk"],nativeLibraryDirectories=[/data/app/com.andre_jacq_ing.preleveurgmail-1/lib/arm64, /system/lib64, /vendor/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:828)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5855)
        at android.app.ActivityThread.-wrap3(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6688)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

Can someone help my with this one ?

Edit

I am calling an URL on my server that redirect me to my .apk and i use this code :

```<code>URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lenghtOfFile = c.getContentLength();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "app.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int count;
            long total = 0;
            while ((count = is.read(buffer)) != -1) {
                total += count;
                fos.write(buffer, 0, count);
                publishProgress((int) (total * 100 / lenghtOfFile));
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
</code>```

答:
Well, actually it was because of Android Studio's Instant Run. I just disable it and it worked like a charm.

Despite all thank's for your help.

Body:
I have an android app with a custom Application class.

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Utils.isThereUpdatedVersion(this);
    }
}

The isThereUpdatedVersion function asks a php page is. There is a new version of my app available and there is a button one goes to another activity with a button to download an install the new version.

I added the android:name attribute to my Manifest

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:name=".application.MyApplication">

When I run my app through Android Studio, the app is running perfectly. Is there is a new version i can download it and install it. But after the installation, I open the app and I get this error and the app crashes.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.andre_jacq_ing.preleveurgmail, PID: 2915
    java.lang.RuntimeException: Unable to instantiate application com.andre_jacq_ing.preleveurgmail.application.MyApplication: java.lang.ClassNotFoundException: Didn't find class "com.andre_jacq_ing.preleveurgmail.application.MyApplication" on path: DexPathList[[zip file "/data/app/com.andre_jacq_ing.preleveurgmail-1/base.apk"],nativeLibraryDirectories=[/data/app/com.andre_jacq_ing.preleveurgmail-1/lib/arm64, /system/lib64, /vendor/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:839)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5855)
        at android.app.ActivityThread.-wrap3(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6688)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.andre_jacq_ing.preleveurgmail.application.MyApplication" on path: DexPathList[[zip file "/data/app/com.andre_jacq_ing.preleveurgmail-1/base.apk"],nativeLibraryDirectories=[/data/app/com.andre_jacq_ing.preleveurgmail-1/lib/arm64, /system/lib64, /vendor/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1000)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:828)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5855)
        at android.app.ActivityThread.-wrap3(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6688)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

Can someone help my with this one ?

Edit

I am calling an URL on my server that redirect me to my .apk and i use this code :

URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lenghtOfFile = c.getContentLength();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "app.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int count;
            long total = 0;
            while ((count = is.read(buffer)) != -1) {
                total += count;
                fos.write(buffer, 0, count);
                publishProgress((int) (total * 100 / lenghtOfFile));
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);


问:
Drawing Pixels in WPF
how would I manage pixel-by-pixel rendering in WPF (like, say, for a raytracer)? My initial guess was to create a BitmapImage, modify the buffer, and display that in an Image control, but I couldn't figure out how to create one (the create method requires a block of unmanaged memory)</p>

答:
you could place 1X1 Rectangle objects onto a Canvas

```<code>  private void AddPixel(double x, double y)
  {
     Rectangle rec = new Rectangle();
     Canvas.SetTop(rec, y);
     Canvas.SetLeft(rec, x);
     rec.Width = 1;
     rec.Height = 1;
     rec.Fill = new SolidColorBrush(Colors.Red);
     myCanvas.Children.Add(rec);
  }
</code>```

That should be pretty close to what you want

OwnerDisplayName: Jimmy

ContentLicense: CC BY-SA 2.5

Title: Drawing Pixels in WPF

LastEditorDisplayName: Jimmy

Body:
you could place 1X1 Rectangle objects onto a Canvas

  private void AddPixel(double x, double y)
  {
     Rectangle rec = new Rectangle();
     Canvas.SetTop(rec, y);
     Canvas.SetLeft(rec, x);
     rec.Width = 1;
     rec.Height = 1;
     rec.Fill = new SolidColorBrush(Colors.Red);
     myCanvas.Children.Add(rec);
  }

That should be pretty close to what you want

OwnerDisplayName: wegrata


问:
Flutter - Running unit tests on Windows
I am trying to run some unit tests I wrote from my command-line. It's now where I figure out that Flutter does not yet support running them on Windows. I saw some issues filed on GitHub about the problem. However, it has been a couple of months ago already. Has anything changed since then?

Or do I have any other way of running my unit tests? Developing without them seems to be a bit tedious to be honest...

Thanks

答:
Update, 12 December 2017: This is now supported!

This is unfortunately currently not supported; tracking bug is https://github.com/flutter/flutter/issues/8516.

If this is important to you, please up-vote it by clicking "thumbs up" on the top comment in bug 8516.

Title: Flutter - Running unit tests on Windows


问:
What is the difference between UnityEngine.Events.Unityaction vs System.Action?
What is the difference between UnityEngine.Events.Unityaction vs System.Action.

Can i use System.Action in Unity?

Can i use lambda as UnityAction?

答:
Yes to both questions. For example, these two lines of code are formally the same:

System.Action<GameObject> myaction = (gameobj) => { Debug.Log(gameobj.name); } ;

UnityEngine.Events.UnityAction<GameObject> myaction = (gameobj) => { Debug.Log(gameobj.name); } ;


问:
Backdrop-filter in chrome has black border
I tried to add the future-property backdrop-filter in chrome:

```<code>.glass {
    --webkit-backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px); /* chrome */
}
</code>```

After activating it in chrome://flags/#enable-experimental-web-platform-features it finally works, but, I get a black border. Anybody an idea how to remove that border??

Edit

There is no zero-data-bug or something (tested with the SO-page):

If I take 3px instead of 10px the border is smaller, but not away:

Here is a fiddle but better, you copy it local, because fiddle also just the right boder in example. Then it looks like this:

答:
I used filter instead of backdrop-filter, but it might not be quite what you want it to be, but it does blur the text as expected, as the bug report in chrome might still remain, described in this post for the backdrop-filter.

body{margin:0;}

        .front{
            position: fixed;
            width: 100%;
            text-align: center;
            font-size: 20px;
            -webkit-filter: blur(5px);
            -moz-filter: blur(5px);
            -o-filter: blur(5px);
            -ms-filter: blur(5px);
        }

        .back {
            margin: 20px;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

    <div class="front">
        <p> this is in the front </p>

    </div>

    <div class="back">
    <p> this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back </p>
    </div>

</body></code>```

This would blur the front, but in my next example I have: JSFiddle

Body:
I tried to add the future-property backdrop-filter in chrome:

.glass {
    --webkit-backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px); /* chrome */
}

After activating it in chrome://flags/#enable-experimental-web-platform-features it finally works, but, I get a black border. Anybody an idea how to remove that border??

Edit

There is no zero-data-bug or something (tested with the SO-page):

If I take 3px instead of 10px the border is smaller, but not away:

Here is a fiddle but better, you copy it local, because fiddle also just the right boder in example. Then it looks like this:

Body:
I used filter instead of backdrop-filter, but it might not be quite what you want it to be, but it does blur the text as expected, as the bug report in chrome might still remain, described in this post for the backdrop-filter.

body{margin:0;}

        .front{
            position: fixed;
            width: 100%;
            text-align: center;
            font-size: 20px;
            -webkit-filter: blur(5px);
            -moz-filter: blur(5px);
            -o-filter: blur(5px);
            -ms-filter: blur(5px);
        }

        .back {
            margin: 20px;
        }

<body>

    <div class="front">
        <p> this is in the front </p>

    </div>

    <div class="back">
    <p> this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back this is in the back </p>
    </div>

</body>

This would blur the front, but in my next example I have: JSFiddle


问:
Tidy up PHP echo code
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11];
    echo $arr[12];
    echo $arr[13];
    echo $arr[14];
    echo $arr[15];
    echo $arr[16];
} else {
    echo 'No';
}
?>```

Thanks in advance.

答:
The code you posted probably has bugs, because the way it's written, it looks like it's intended to do something different from what it is actually going to do.

str_split() will take a string and output an array of single characters. It looks like you're trying to pass it two parameters, but enclosing them in quotes means it's actually just a single string.

Thus, if $url is equal to abc, your str_split() call will output an array of a, b, c, ,, , P, H, P, _, U, R, L, _ ... etc.

I don't think that's what you intended.

However, if it is what you intended, then you are splitting the string, only to re-join some of the characters back together again with echo. You can therefore can simplify the whole thing as follows:

```<code>$url = get_field('bothscoreno');
if ($url) {
   echo substr($url, 11, 6);
} else {
    echo "No.";
}
</code>```

If I'm right and this isn't what you actually want to do, then I suggest either editing the question to clarify or asking a whole new one.

Title: Tidy up PHP echo code

Body:
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11];
    echo $arr[12];
    echo $arr[13];
    echo $arr[14];
    echo $arr[15];
    echo $arr[16];
} else {
    echo 'No';
}
?>

Thanks in advance.

Body:
The code you posted probably has bugs, because the way it's written, it looks like it's intended to do something different from what it is actually going to do.

str_split() will take a string and output an array of single characters. It looks like you're trying to pass it two parameters, but enclosing them in quotes means it's actually just a single string.

Thus, if $url is equal to abc, your str_split() call will output an array of a, b, c, ,, , P, H, P, _, U, R, L, _ ... etc.

I don't think that's what you intended.

However, if it is what you intended, then you are splitting the string, only to re-join some of the characters back together again with echo. You can therefore can simplify the whole thing as follows:

$url = get_field('bothscoreno');
if ($url) {
   echo substr($url, 11, 6);
} else {
    echo "No.";
}

If I'm right and this isn't what you actually want to do, then I suggest either editing the question to clarify or asking a whole new one.


问:
ionic 2 Side menu and log out and back key navigation
I am trying to achieve a log out functionality. I am using FB authentication. My problem here is after I do a logout successfully(This happens from the Side menu ) I return to the Login Screen. But now if I tap the device's back button it is taking me to the homepage(. Any idea how to prevent this ?

This is my app.component.ts

```<code>import { Component, ViewChild } from '@angular/core';
import { Platform, Nav, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { LoginPage } from '../pages/login/login';
import { NativeStorage } from '@ionic-native/native-storage';
import { TabsPage } from '../pages/tabs/tabs';
import { Facebook } from 'ionic-native';
@Component({
  templateUrl: 'app.html',

})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  rootPage: any = LoginPage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private nativeStorage: NativeStorage, private alertCtrl: AlertController) {
    platform.ready().then(() => platform.ready().then(() => {
      this.nativeStorage.getItem("userId").then((data) => {
        console.log(data.userExists);
        this.rootPage = TabsPage;
        this.nav.push(TabsPage);

      }, (error) => {
        console.log("No data in storage");
        this.nav.push(LoginPage);
      })
      statusBar.styleDefault();
      splashScreen.hide();
    })

    )
  }

  presentConfirm() {
    let alert = this.alertCtrl.create({
      title: "Confirm Logout",
      message: "Do you really really want to quit this awesome app?",
      buttons: [{
        text: 'Nah! Just Kidding!', role: 'cancel', handler: () => {
        }
      },
      {
        text: "Ok",
        handler: () => {
          this.nativeStorage.clear();
          this.nav.push(LoginPage);
          this.rootPage = LoginPage;
          Facebook.logout().then((response) => {
          }, (error) => {
          })
        }
      }]
    });
    alert.present();
  }

}
</code>```

This is my login page. Login.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
import { NativeStorage } from '@ionic-native/native-storage';
import { TabsPage } from '../tabs/tabs'

@Component({
  selector: 'login-home',
  templateUrl: 'login.html'
})
export class LoginPage {

  constructor(public navCtrl: NavController, private nativeStorage: NativeStorage) {

  }

  FBLogin() {
    //this.navCtrl.push(TabsPage); - To be used on browser environment
    Facebook.login(['email']).then((response) => {
      Facebook.getLoginStatus().then((response) => {
        if (response.status == 'connected') {
           this.navCtrl.push(TabsPage); // - to be used on device
          console.log("Setting Storage")
          this.nativeStorage.setItem("userId", { userExists: true });
          Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response) => {
          }, (error) => {
            alert(error)
          })
        }
        else
          alert("Not Logged in");
      })

    }, (error) => {
      console.log((error));
    })
  }

}
</code>```

This is my Menu

```<code><ion-menu swipeEnabled="false" side="right" [content]="content">
  <ion-toolbar>
    <ion-title>Menu</ion-title>
  </ion-toolbar>
   <ion-content>
    <ion-list>
     <p> </p>
      <button  menuClose padding-top ion-item> Test 1 </button>
      <button menuClose ion-item> Test 2 </button>
      <button menuClose ion-item (click)="presentConfirm()"><ion-icon name="power"></ion-icon>  Logout </button>
    </ion-list>
  </ion-content>
 </ion-menu>
<ion-nav id="nav" [root]="rootPage" #content swipe-back-enabled="false"></ion-nav>
</code>```

答:
Your issue is you are doing:

```<code>      this.nav.push(LoginPage);
</code>```

in your logout handler.
This means LoginPage is added on top of your old navigation stack. You need to set a new stack and set LoginPage as root.
Do :

```<code>this.nav.setRoot(LoginPage);
</code>```

Body:
I am trying to achieve a log out functionality. I am using FB authentication. My problem here is after I do a logout successfully(This happens from the Side menu ) I return to the Login Screen. But now if I tap the device's back button it is taking me to the homepage(. Any idea how to prevent this ?

This is my app.component.ts

import { Component, ViewChild } from '@angular/core';
import { Platform, Nav, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { LoginPage } from '../pages/login/login';
import { NativeStorage } from '@ionic-native/native-storage';
import { TabsPage } from '../pages/tabs/tabs';
import { Facebook } from 'ionic-native';
@Component({
  templateUrl: 'app.html',

})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  rootPage: any = LoginPage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private nativeStorage: NativeStorage, private alertCtrl: AlertController) {
    platform.ready().then(() => platform.ready().then(() => {
      this.nativeStorage.getItem("userId").then((data) => {
        console.log(data.userExists);
        this.rootPage = TabsPage;
        this.nav.push(TabsPage);

      }, (error) => {
        console.log("No data in storage");
        this.nav.push(LoginPage);
      })
      statusBar.styleDefault();
      splashScreen.hide();
    })

    )
  }

  presentConfirm() {
    let alert = this.alertCtrl.create({
      title: "Confirm Logout",
      message: "Do you really really want to quit this awesome app?",
      buttons: [{
        text: 'Nah! Just Kidding!', role: 'cancel', handler: () => {
        }
      },
      {
        text: "Ok",
        handler: () => {
          this.nativeStorage.clear();
          this.nav.push(LoginPage);
          this.rootPage = LoginPage;
          Facebook.logout().then((response) => {
          }, (error) => {
          })
        }
      }]
    });
    alert.present();
  }

}

This is my login page. Login.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
import { NativeStorage } from '@ionic-native/native-storage';
import { TabsPage } from '../tabs/tabs'

@Component({
  selector: 'login-home',
  templateUrl: 'login.html'
})
export class LoginPage {

  constructor(public navCtrl: NavController, private nativeStorage: NativeStorage) {

  }

  FBLogin() {
    //this.navCtrl.push(TabsPage); - To be used on browser environment
    Facebook.login(['email']).then((response) => {
      Facebook.getLoginStatus().then((response) => {
        if (response.status == 'connected') {
           this.navCtrl.push(TabsPage); // - to be used on device
          console.log("Setting Storage")
          this.nativeStorage.setItem("userId", { userExists: true });
          Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response) => {
          }, (error) => {
            alert(error)
          })
        }
        else
          alert("Not Logged in");
      })

    }, (error) => {
      console.log((error));
    })
  }

}

This is my Menu

<ion-menu swipeEnabled="false" side="right" [content]="content">
  <ion-toolbar>
    <ion-title>Menu</ion-title>
  </ion-toolbar>
   <ion-content>
    <ion-list>

      <button  menuClose padding-top ion-item> Test 1 </button>
      <button menuClose ion-item> Test 2 </button>
      <button menuClose ion-item (click)="presentConfirm()"><ion-icon name="power"></ion-icon>  Logout </button>
    </ion-list>
  </ion-content>
 </ion-menu>
<ion-nav id="nav" [root]="rootPage" #content swipe-back-enabled="false"></ion-nav>

Body:
Your issue is you are doing:

      this.nav.push(LoginPage);

in your logout handler.
This means LoginPage is added on top of your old navigation stack. You need to set a new stack and set LoginPage as root.
Do :

this.nav.setRoot(LoginPage);


问:
API Import Export tool not creating custom sequences
I am using WSO2 APIM2.0 and enabled the import/export tool (api-import-export-2.0.0-v0). I am able to export the API ok. My API has got custom input and output sequence attached to it. I can see the custom sequences in the exported zip file. But when I import the same into any other environment the APIs are created properly but the custom sequences neither created nor attached to the imported APIs. Am I missing something here?

Thanks in advance

答: I think it's fixed by now. Please get latest tool (v2) from https://docs.wso2.com/display/AM200/Migrating+the+APIs+to+a+Different+Environment</p>


问:
notifyDataSetChanged not working in android
The list view is not updating data when the notifyDataChanged() method called.

In onCreate() method i initialized the the listview with no data.

```<code>            ListView videoList = (ListView)findViewById(R.id.videos_list);
    videoList.setOnItemClickListener(listener);
    listAdapter = new PHVideosListAdapter(PHVideosActivity.this, videos);
    videoList.setAdapter(listAdapter);
</code>```

After this I started fetching list of video using new VideosCategoryFetchTask().execute();

in the post execute method I called

```<code>            @Override
    protected void onPostExecute(Boolean success) {
        if(success) {
             listAdapter.notifyDataSetChanged();
        } else {
            //show dialog
        }
    }
</code>```

but nothing is displayed on the list. If anybody knew the solution please help...

```<code> private class VideosDetailsFetchTask extends AsyncTask<String, Void, Boolean> {
    @Override
    public void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        Boolean success = false;
        try {
            if (params.length >= 0) {
                videos = (Videos)videoAPI.videosForCategoryId(params[0],new VideosParser());
                success = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return success;
    }

    @Override
    protected void onPostExecute(Boolean success) {

        if(success) {
              progressBar.setVisibility(View.INVISIBLE);
              onFinishVideoFetch();
        } else {
            //show dialog
        }
    }
}
</code>```

here  using two Async classes sec one is called on the onPostExecute() of first one..

```<code>   private void onFinishVideoFetch() {
    if(videos != null) {

        listAdapter.notifyDataSetChanged();
    }
}
</code>```

I 'm not fetching videos one by one.. here a list of videos is returned....

After getting the list of videos i wanted to refresh the list.

```<code>@Override
protected void onProgressUpdate(Videos... values) {

    videos = values[0];
 //add published object to list which holds
    listAdapter.notifyDataSetChanged();

}
</code>```

I tried this but no luck please help..

this is the adapter class used

public class PHVideosListAdapter extends BaseAdapter{

```<code>private Videos videoTitles;
private LayoutInflater inflater;

public PHVideosListAdapter(Context context, Videos videoTitles) {

    inflater = LayoutInflater.from(context);
    this.videoTitles = videoTitles;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    if(videoTitles != null) {
        return videoTitles.size();
    }
    else {
        return 0;
    }
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return videoTitles.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    VideoListViewHolder holder = null;

    if (convertView == null) {

            holder = new VideoListViewHolder();
            convertView = inflater.inflate(R.layout.videos_list, null);
            holder.videoTitle = (TextView) convertView.findViewById(R.id.video_title);
            holder.videoImage = (ImageView) convertView.findViewById(R.id.video_image);
            holder.videoDuration = (TextView) convertView.findViewById(R.id.video_duration);

            convertView.setTag(holder);
    } else {
        holder = (VideoListViewHolder)convertView.getTag();
    }

    holder.videoImage.setImageResource(R.drawable.icon);
    holder.videoDuration.setText("00:10");
    holder.videoTitle.setText(videoTitles.get(position).getVideoTitle());
    return convertView;
}

   private class VideoListViewHolder {

     ImageView videoImage;
     TextView  videoTitle;
     TextView  videoDuration;
}
</code>```

}

答:
You need to override onProgressUpdate() of AsynTask class

Heres an example of AsyncTask assuming your list is videos which holds Objects of type Video and your extended adapter is VideosAdapter

```<code>private class VideosDetailsFetchTask extends AsyncTask<String, Video, Boolean> {
    @Override
    public void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
    //utilize string you are passing otherwise use Void as first generic param.
    Boolean success = false;
        try {
            if (params.length >= 0) {
                Videos videoFetched = (Videos)PrimeraHoraAPI.videosForCategoryId(params[0],new VideosParser());
                success = true;
                publishProgress(videoFetched);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return success;
    }

    @Override
    protected void onPostExecute(Boolean success) {

        if(success) {
              progressBar.setVisibility(View.INVISIBLE);
              onFinishVideoFetch();
        } else {
            //show dialog
        }
    }

    @Override
    protected void onProgressUpdate(Video... values) {
        videos.add(values[0]);//add published object to list which holds
        ((VideosAdapter)getListAdapter()).notifyDataSetChanged();

    }
}
</code>```

Body:
The list view is not updating data when the notifyDataChanged() method called.

In onCreate() method i initialized the the listview with no data.

            ListView videoList = (ListView)findViewById(R.id.videos_list);
    videoList.setOnItemClickListener(listener);
    listAdapter = new PHVideosListAdapter(PHVideosActivity.this, videos);
    videoList.setAdapter(listAdapter);

After this I started fetching list of video using new VideosCategoryFetchTask().execute();

in the post execute method I called

            @Override
    protected void onPostExecute(Boolean success) {
        if(success) {
             listAdapter.notifyDataSetChanged();
        } else {
            //show dialog
        }
    }

but nothing is displayed on the list. If anybody knew the solution please help...

 private class VideosDetailsFetchTask extends AsyncTask<String, Void, Boolean> {
    @Override
    public void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        Boolean success = false;
        try {
            if (params.length >= 0) {
                videos = (Videos)videoAPI.videosForCategoryId(params[0],new VideosParser());
                success = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return success;
    }

    @Override
    protected void onPostExecute(Boolean success) {

        if(success) {
              progressBar.setVisibility(View.INVISIBLE);
              onFinishVideoFetch();
        } else {
            //show dialog
        }
    }
}

here  using two Async classes sec one is called on the onPostExecute() of first one..

   private void onFinishVideoFetch() {
    if(videos != null) {

        listAdapter.notifyDataSetChanged();
    }
}

I 'm not fetching videos one by one.. here a list of videos is returned....

After getting the list of videos i wanted to refresh the list.

@Override
protected void onProgressUpdate(Videos... values) {

    videos = values[0];
 //add published object to list which holds
    listAdapter.notifyDataSetChanged();

}

I tried this but no luck please help..

this is the adapter class used

public class PHVideosListAdapter extends BaseAdapter{

private Videos videoTitles;
private LayoutInflater inflater;

public PHVideosListAdapter(Context context, Videos videoTitles) {

    inflater = LayoutInflater.from(context);
    this.videoTitles = videoTitles;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    if(videoTitles != null) {
        return videoTitles.size();
    }
    else {
        return 0;
    }
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return videoTitles.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    VideoListViewHolder holder = null;

    if (convertView == null) {

            holder = new VideoListViewHolder();
            convertView = inflater.inflate(R.layout.videos_list, null);
            holder.videoTitle = (TextView) convertView.findViewById(R.id.video_title);
            holder.videoImage = (ImageView) convertView.findViewById(R.id.video_image);
            holder.videoDuration = (TextView) convertView.findViewById(R.id.video_duration);

            convertView.setTag(holder);
    } else {
        holder = (VideoListViewHolder)convertView.getTag();
    }

    holder.videoImage.setImageResource(R.drawable.icon);
    holder.videoDuration.setText("00:10");
    holder.videoTitle.setText(videoTitles.get(position).getVideoTitle());
    return convertView;
}

   private class VideoListViewHolder {

     ImageView videoImage;
     TextView  videoTitle;
     TextView  videoDuration;
}

}

Body:
You need to override onProgressUpdate() of AsynTask class

Heres an example of AsyncTask assuming your list is videos which holds Objects of type Video and your extended adapter is VideosAdapter

private class VideosDetailsFetchTask extends AsyncTask<String, Video, Boolean> {
    @Override
    public void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
    //utilize string you are passing otherwise use Void as first generic param.
    Boolean success = false;
        try {
            if (params.length >= 0) {
                Videos videoFetched = (Videos)PrimeraHoraAPI.videosForCategoryId(params[0],new VideosParser());
                success = true;
                publishProgress(videoFetched);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return success;
    }

    @Override
    protected void onPostExecute(Boolean success) {

        if(success) {
              progressBar.setVisibility(View.INVISIBLE);
              onFinishVideoFetch();
        } else {
            //show dialog
        }
    }

    @Override
    protected void onProgressUpdate(Video... values) {
        videos.add(values[0]);//add published object to list which holds
        ((VideosAdapter)getListAdapter()).notifyDataSetChanged();

    }
}


问:
OkHttp and Retrofit, refresh token with concurrent requests
In my application I implemented Retrofit to call WebServices and I'm using OkHttp to use Interceptor and Authenticator. Some requests need token, and I have implemented Authenticator interface to handle the refresh (following the official documentation). But I have the following issue : time to time in my app I have to call more than one request at once. Because of that, for one of them I will have the 401 error.

Here is my code for request calls :

```<code>public static <S> S createServiceAuthentication(Class<S> serviceClass, boolean hasPagination) {

        final String jwt = JWT.getJWTValue(); //Get jwt value from Realm

        if (hasPagination) {
            Gson gson = new GsonBuilder().
                    registerTypeAdapter(Pagination.class, new PaginationTypeAdapter()).create();

            builder =
                    new Retrofit.Builder()
                            .baseUrl(APIConstant.API_URL)
                            .addConverterFactory(GsonConverterFactory.create(gson));
        }

        OkHttpClient.Builder httpClient =
                new OkHttpClient.Builder();

        httpClient.addInterceptor(new AuthenticationInterceptor(jwt));
        httpClient.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                if (responseCount(response) >= 2) {
                    // If both the original call and the call with refreshed token failed,
                    // it will probably keep failing, so don't try again.
                    return null;
                }

                if (jwt.equals(response.request().header("Authorization"))) {
                    return null; // If we already failed with these credentials, don't retry.
                }

                APIRest apiRest = createService(APIRest.class, false);
                Call<JWTResponse> call = apiRest.refreshToken(new JWTBody(jwt));
                try {
                    retrofit2.Response<JWTResponse> refreshTokenResponse = call.execute();
                    if (refreshTokenResponse.isSuccessful()) {

                        JWT.storeJwt(refreshTokenResponse.body().getJwt());

                        return response.request().newBuilder()
                                .header(CONTENT_TYPE, APPLICATION_JSON)
                                .header(ACCEPT, APPLICATION)
                                .header(AUTHORIZATION, "Bearer " + refreshTokenResponse.body().getJwt())
                                .build();
                    } else {
                        return null;
                    }
                } catch (IOException e) {
                    return null;
                }
            }
        });

        builder.client(httpClient.build());
        retrofit = builder.build();

        return retrofit.create(serviceClass);
    }

    private static int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }
</code>```

The issue is simple, the first request will refresh the token successfully but others will failed because they will try to refresh a token already refreshed. The WebService return an error 500. Is there any elegant solution to avoid this ?

Thank you !

答:
If I understand your issue, some requests are sent while the token is being updated, this gives you an error.

You could try to prevent all the requests while a token is being updated (with a 'synchronized' object) but this will not cover the case of an already sent request.

Since the issue is difficult to avoid completely, maybe the right approach here is to have a good fallback behavior. Handling the error you get when you've made a request during a token update by re-running the request with the updated token for instance.

Body:
In my application I implemented Retrofit to call WebServices and I'm using OkHttp to use Interceptor and Authenticator. Some requests need token, and I have implemented Authenticator interface to handle the refresh (following the official documentation). But I have the following issue : time to time in my app I have to call more than one request at once. Because of that, for one of them I will have the 401 error.

Here is my code for request calls :

public static <S> S createServiceAuthentication(Class<S> serviceClass, boolean hasPagination) {

        final String jwt = JWT.getJWTValue(); //Get jwt value from Realm

        if (hasPagination) {
            Gson gson = new GsonBuilder().
                    registerTypeAdapter(Pagination.class, new PaginationTypeAdapter()).create();

            builder =
                    new Retrofit.Builder()
                            .baseUrl(APIConstant.API_URL)
                            .addConverterFactory(GsonConverterFactory.create(gson));
        }

        OkHttpClient.Builder httpClient =
                new OkHttpClient.Builder();

        httpClient.addInterceptor(new AuthenticationInterceptor(jwt));
        httpClient.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                if (responseCount(response) >= 2) {
                    // If both the original call and the call with refreshed token failed,
                    // it will probably keep failing, so don't try again.
                    return null;
                }

                if (jwt.equals(response.request().header("Authorization"))) {
                    return null; // If we already failed with these credentials, don't retry.
                }

                APIRest apiRest = createService(APIRest.class, false);
                Call<JWTResponse> call = apiRest.refreshToken(new JWTBody(jwt));
                try {
                    retrofit2.Response<JWTResponse> refreshTokenResponse = call.execute();
                    if (refreshTokenResponse.isSuccessful()) {

                        JWT.storeJwt(refreshTokenResponse.body().getJwt());

                        return response.request().newBuilder()
                                .header(CONTENT_TYPE, APPLICATION_JSON)
                                .header(ACCEPT, APPLICATION)
                                .header(AUTHORIZATION, "Bearer " + refreshTokenResponse.body().getJwt())
                                .build();
                    } else {
                        return null;
                    }
                } catch (IOException e) {
                    return null;
                }
            }
        });

        builder.client(httpClient.build());
        retrofit = builder.build();

        return retrofit.create(serviceClass);
    }

    private static int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }

The issue is simple, the first request will refresh the token successfully but others will failed because they will try to refresh a token already refreshed. The WebService return an error 500. Is there any elegant solution to avoid this ?

Thank you !


问:
Can't center divs HTML CSS
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div></code>```

答:
p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: auto;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-align: center;
}
#page:after {
  content: '';
  display: table;
  clear: both;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}
.item {
  display: inline-block;
}
#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01" class="item">
  </div>

  <div id="bg_02" class="item">
  </div>

  <div id="bg_03" class="item">
  </div>

  <div id="bg_04" class="item">
  </div>

  <div id="bg_05" class="item">
  </div>
</div></code>```

Title: Can't center divs HTML CSS

Body:
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

Colour

Body:
p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: auto;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-align: center;
}
#page:after {
  content: '';
  display: table;
  clear: both;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}
.item {
  display: inline-block;
}
#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

<div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01" class="item">
  </div>

  <div id="bg_02" class="item">
  </div>

  <div id="bg_03" class="item">
  </div>

  <div id="bg_04" class="item">
  </div>

  <div id="bg_05" class="item">
  </div>
</div>


问:
Cannot connect to node js server hosted on vagrant machine
I'm trying out vagrant as a local testing server and I'm having difficulty connecting to nodejs app server from the hosting windows machine, but I can connect to nginx server just fine.

My vagrant file:

```<code>Vagrant.configure("2") do |config|
  config.vm.define "web" do |web|
    web.vm.box = "ubuntu/trusty64"
    web.vm.network "private_network", ip: "55.55.55.55"
  end

  config.vm.define "app_0" do |app_0|
    app_0.vm.box = "ubuntu/trusty64"
    app_0.vm.network "private_network", ip: "55.55.55.1"
  end

  config.vm.define "db" do |db|
    db.vm.box = "ubuntu/trusty64"
    db.vm.network "private_network", ip: "55.55.55.56"
  end
end
</code>```

My node js index.js(helloworld) from app_0 at 55.55.55.1:

```<code>// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 80, IP defaults to 127.0.0.1
server.listen(80, '0.0.0.0', function() {
    console.log('Listening to port:  ' + 80);
});
</code>```

Which is run with sudo node index.js and is visible locally on the vagrant machine, but I cannot connect to it from hosting machine at 55.55.55.1:80

Please do not mark this duplicate of this: Connect to node js server running on vagrant machine as it does not use port-forwarding.

答:
I see 2 things:

55.55.55.x is not a private network IP (see https://en.wikipedia.org/wiki/Private_network) so you might reach a valid IP and even when setting your host file, you might have conflict.

Do not use address with .1 at the end, it is the default gateway/router
so how vagrant will reach the host.

Pick a valid IP from the private network range and it will work

```<code>Vagrant.configure("2") do |config|
  config.vm.define "web" do |web|
    web.vm.box = "ubuntu/trusty64"
    web.vm.network "private_network", ip: "192.168.55.10"
  end

  config.vm.define "app_0" do |app_0|
    app_0.vm.box = "ubuntu/trusty64"
    app_0.vm.network "private_network", ip: "192.168.55.11"
  end

  config.vm.define "db" do |db|
    db.vm.box = "ubuntu/trusty64"
    db.vm.network "private_network", ip: "192.168.55.12"
  end
end
</code>```

Body:
I'm trying out vagrant as a local testing server and I'm having difficulty connecting to nodejs app server from the hosting windows machine, but I can connect to nginx server just fine.

My vagrant file:

Vagrant.configure("2") do |config|
  config.vm.define "web" do |web|
    web.vm.box = "ubuntu/trusty64"
    web.vm.network "private_network", ip: "55.55.55.55"
  end

  config.vm.define "app_0" do |app_0|
    app_0.vm.box = "ubuntu/trusty64"
    app_0.vm.network "private_network", ip: "55.55.55.1"
  end

  config.vm.define "db" do |db|
    db.vm.box = "ubuntu/trusty64"
    db.vm.network "private_network", ip: "55.55.55.56"
  end
end

My node js index.js(helloworld) from app_0 at 55.55.55.1:

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 80, IP defaults to 127.0.0.1
server.listen(80, '0.0.0.0', function() {
    console.log('Listening to port:  ' + 80);
});

Which is run with sudo node index.js and is visible locally on the vagrant machine, but I cannot connect to it from hosting machine at 55.55.55.1:80

Please do not mark this duplicate of this: Connect to node js server running on vagrant machine as it does not use port-forwarding.

Body:
I see 2 things:

55.55.55.x is not a private network IP (see https://en.wikipedia.org/wiki/Private_network) so you might reach a valid IP and even when setting your host file, you might have conflict.

Do not use address with .1 at the end, it is the default gateway/router
so how vagrant will reach the host.

Pick a valid IP from the private network range and it will work

Vagrant.configure("2") do |config|
  config.vm.define "web" do |web|
    web.vm.box = "ubuntu/trusty64"
    web.vm.network "private_network", ip: "192.168.55.10"
  end

  config.vm.define "app_0" do |app_0|
    app_0.vm.box = "ubuntu/trusty64"
    app_0.vm.network "private_network", ip: "192.168.55.11"
  end

  config.vm.define "db" do |db|
    db.vm.box = "ubuntu/trusty64"
    db.vm.network "private_network", ip: "192.168.55.12"
  end
end


问:
Vectorize Pandas Dataframe into Numpy Array
I have a problem where I need to convert a pandas dataframe into an array of list of lists.

Sample:

```<code>import pandas as pd
df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])
</code>```

I know there is the as_matrix() function which returns below:

```<code>df.as_matrix():
# result:array([[1, 2, 3],
                [2, 2, 4],
                [3, 2, 4]])
</code>```

However, I require something in this format

```<code>  [array([[1], [2], [3]]),
   array([[2], [2], [4]],
   array([[3], [2], [4]])]
</code>```

IE. I need a list of arrays containing list of lists where the inner most list contains a single element and the outer most list in the array represents the row of the dataframe. The effect of this is that it basically vectorizes each row of the dataframe into a vector of dimension 3.

This is useful especially when I need to do matrix / vector operations in numpy and currently the data source I have is in .csv format and I am struggling to find a way to convert a dataframe into a vector.

答:
Extract the underlying array data , add a newaxis along the last one and then split along the first axis with np.vsplit -

```<code>np.vsplit(df.values[...,None],df.shape[0])
</code>```

Sample run -

```<code>In [327]: df
Out[327]:
   0  1  2
0  1  2  3
1  2  2  4
2  3  2  4

In [328]: expected_output = [np.array([[1], [2], [3]]),
     ...: np.array([[2], [2], [4]]),
     ...: np.array([[3], [2], [4]])]

In [329]: expected_output
Out[329]:
[array([[1],
        [2],
        [3]]), array([[2],
        [2],
        [4]]), array([[3],
        [2],
        [4]])]

In [330]: np.vsplit(df.values[...,None],df.shape[0])
Out[330]:
[array([[[1],
         [2],
         [3]]]), array([[[2],
         [2],
         [4]]]), array([[[3],
         [2],
         [4]]])]
</code>```

If you are working with NumPy funcs, then in most scenarios, you should be able to do away with the splitting and directly use the extended array version.

Now, under the hoods np.vsplit  makes use of np.array_split and that's basically a loop. So, a bit more performant way would be to avoid the function overhead, like so -

```<code>np.array_split(df.values[...,None],df.shape[0])
</code>```

Note that this would have one extra dimension than as listed in the expected output. If you want a squeezed out version, we could use a list comprehension on the new-axis extended array version, like so -

```<code>In [357]: [i for i in df.values[...,None]]
Out[357]:
[array([[1],
        [2],
        [3]]), array([[2],
        [2],
        [4]]), array([[3],
        [2],
        [4]])]
</code>```

Thus, another way would be to add the new axis within the looping -

```<code>[i[...,None] for i in df.values]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem where I need to convert a pandas dataframe into an array of list of lists.

Sample:

import pandas as pd
df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])

I know there is the as_matrix() function which returns below:

df.as_matrix():
# result:array([[1, 2, 3],
                [2, 2, 4],
                [3, 2, 4]])

However, I require something in this format

  [array([[1], [2], [3]]),
   array([[2], [2], [4]],
   array([[3], [2], [4]])]

IE. I need a list of arrays containing list of lists where the inner most list contains a single element and the outer most list in the array represents the row of the dataframe. The effect of this is that it basically vectorizes each row of the dataframe into a vector of dimension 3.

This is useful especially when I need to do matrix / vector operations in numpy and currently the data source I have is in .csv format and I am struggling to find a way to convert a dataframe into a vector.

Body:
Extract the underlying array data , add a newaxis along the last one and then split along the first axis with np.vsplit -

np.vsplit(df.values[...,None],df.shape[0])

Sample run -

In [327]: df
Out[327]:
   0  1  2
0  1  2  3
1  2  2  4
2  3  2  4

In [328]: expected_output = [np.array([[1], [2], [3]]),
     ...: np.array([[2], [2], [4]]),
     ...: np.array([[3], [2], [4]])]

In [329]: expected_output
Out[329]:
[array([[1],
        [2],
        [3]]), array([[2],
        [2],
        [4]]), array([[3],
        [2],
        [4]])]

In [330]: np.vsplit(df.values[...,None],df.shape[0])
Out[330]:
[array([[[1],
         [2],
         [3]]]), array([[[2],
         [2],
         [4]]]), array([[[3],
         [2],
         [4]]])]

If you are working with NumPy funcs, then in most scenarios, you should be able to do away with the splitting and directly use the extended array version.

Now, under the hoods np.vsplit  makes use of np.array_split and that's basically a loop. So, a bit more performant way would be to avoid the function overhead, like so -

np.array_split(df.values[...,None],df.shape[0])

Note that this would have one extra dimension than as listed in the expected output. If you want a squeezed out version, we could use a list comprehension on the new-axis extended array version, like so -

In [357]: [i for i in df.values[...,None]]
Out[357]:
[array([[1],
        [2],
        [3]]), array([[2],
        [2],
        [4]]), array([[3],
        [2],
        [4]])]

Thus, another way would be to add the new axis within the looping -

[i[...,None] for i in df.values]


答:
Use array_slice

```<code><?php
    $values = get_field('bothscoreno');
    $url    = "$values";
    $arr    = str_split("$url, PHP_URL_QUERY");
    if ($url) {
        $subArr = array_slice($arr, 11, 6);
        print_r($subArr);

        // Or...
        foreach ($subArr as $val) {
          echo $val;
        }
    } else {
        echo 'No';
    }
    ?>
</code>```

Title: Tidy up PHP echo code

Body:
Use array_slice

<?php
    $values = get_field('bothscoreno');
    $url    = "$values";
    $arr    = str_split("$url, PHP_URL_QUERY");
    if ($url) {
        $subArr = array_slice($arr, 11, 6);
        print_r($subArr);

        // Or...
        foreach ($subArr as $val) {
          echo $val;
        }
    } else {
        echo 'No';
    }
    ?>


问:
How to start a django cms project
I decided to take a look to django-cms. After looking at the docs I cloned the repository using

```<code>git clone https://github.com/divio/django-cms.git
</code>```

Then I installed it using

```<code>sudo python setup.py install
</code>```

I already have django 1.2.3 installed. I moved to the example directory an ran syncdb which created the following tables:

```<code>Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_admin_log
Creating table django_site
Creating table sampleapp_category
Creating table sampleapp_picture
Creating table south_migrationhistory

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes...
</code>```

We can clearly see that the cms tables are not created. I'm obviously facing that problem when running the server and browsing http://localhost:8000/

```<code>DatabaseError: no such table: cms_page
</code>```

I've looked at the docs and seen that I meet the requirements regarding the versions but clearly, I'm doing something wrong. Any help would be greatly appreciated.

答: Did you put 'cms' in INSTALLED_APPS in settings.py? Django-CMS furthermore requires also menus, publisher and mptt installed as well as some middleware. This is some nice to read documentation on it!

Title: How to start a django cms project

Body:
I decided to take a look to django-cms. After looking at the docs I cloned the repository using

git clone https://github.com/divio/django-cms.git

Then I installed it using

sudo python setup.py install

I already have django 1.2.3 installed. I moved to the example directory an ran syncdb which created the following tables:

Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_admin_log
Creating table django_site
Creating table sampleapp_category
Creating table sampleapp_picture
Creating table south_migrationhistory

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes...

We can clearly see that the cms tables are not created. I'm obviously facing that problem when running the server and browsing http://localhost:8000/

DatabaseError: no such table: cms_page

I've looked at the docs and seen that I meet the requirements regarding the versions but clearly, I'm doing something wrong. Any help would be greatly appreciated.


问:
setOnScrollChangeListener on a ScrollView : Error
When an user is at the end of my ScrollView, I want to detect it and load some new items. I have done it, but it appears that function I use doesn't work with some old version of Android.

I have this code :

```<code>scrollView = (ScrollView) findViewById(R.id.scrollView);
    scrollView.setOnScrollChangeListener(new ScrollListener(this));
</code>```

then :

```<code>@TargetApi(Build.VERSION_CODES.M)
public class ScrollListener implements View.OnScrollChangeListener {

ScrollingActivity context;

public ScrollListener(ScrollingActivity context) {
    this.context = context;
}

@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    ScrollView scrollView = (ScrollView) v;
    View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
    int diff = (view.getBottom() - (scrollView.getHeight() + scrollY));
    int oldDiff = (view.getBottom() - (scrollView.getHeight() + oldScrollY));
    // Si on a atteint le bas de la scrollView et qu'on était en train de descendre
    if(diff == 0 && oldDiff > 0) {
        context.endOfScroll(); // function I call to load data...
    }
}}
</code>```

I have this error :

```<code>08-19 21:27:35.135 26504-26504/com.histoire_horreur E/AndroidRuntime: FATAL EXCEPTION: main
                                                              java.lang.NoClassDefFoundError: com.histoire_horreur.Listener.ScrollListener
                                                                  at com.histoire_horreur.MainActivity.createView(MainActivity.java:59)
                                                                  at com.histoire_horreur.MainActivity.onCreate(MainActivity.java:47)
                                                                  at android.app.Activity.performCreate(Activity.java:5122)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:165)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                  at android.os.Looper.loop(Looper.java:194)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5391)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:525)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                  at dalvik.system.NativeStart.main(Native Method)
</code>```

As I told, this code works fine for some versions of Android, but for my Wiko 4.2.2 it doesn't.
My error is the same than here : https://forums.xamarin.com/discussion/62241/problem-setting-on-scroll-listener-to-android-horizontal-scroll-view-class-not-found-exception
Solution there was to use ViewTreeObserver, however, I don't succeed to detect when scroll is at the bottom. I tried to do this :

```<code>scrollView = (ScrollView) findViewById(R.id.scrollView);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
// How to get X, Y, Old X and Old Y ?
}
});
</code>```

But I can't get scrollX, scrollY, oldScrollX and oldScrollY.

Do you know a way to make it work on all verisons of Android ?

答:
i have same problem.
if you use ViewTreeObserver the code working correctly with no exception, and only issue is detect when scroll view on the bottom.
this snip code can help you:</p>

```<code>@Override
public void onScrollChanged() {

    View v = myScrollView.getChildAt(myScrollView.getChildCount() - 1);
    int diff = (v.getBottom() - (myScrollView.getHeight() + myScrollView.getScrollY()));
    if (diff <= 0) {
        //load data here, there is bottom of scrollview
     }
}
</code>```

Body:
When an user is at the end of my ScrollView, I want to detect it and load some new items. I have done it, but it appears that function I use doesn't work with some old version of Android.

I have this code :

scrollView = (ScrollView) findViewById(R.id.scrollView);
    scrollView.setOnScrollChangeListener(new ScrollListener(this));

then :

@TargetApi(Build.VERSION_CODES.M)
public class ScrollListener implements View.OnScrollChangeListener {

ScrollingActivity context;

public ScrollListener(ScrollingActivity context) {
    this.context = context;
}

@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    ScrollView scrollView = (ScrollView) v;
    View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
    int diff = (view.getBottom() - (scrollView.getHeight() + scrollY));
    int oldDiff = (view.getBottom() - (scrollView.getHeight() + oldScrollY));
    // Si on a atteint le bas de la scrollView et qu'on était en train de descendre
    if(diff == 0 && oldDiff > 0) {
        context.endOfScroll(); // function I call to load data...
    }
}}

I have this error :

08-19 21:27:35.135 26504-26504/com.histoire_horreur E/AndroidRuntime: FATAL EXCEPTION: main
                                                              java.lang.NoClassDefFoundError: com.histoire_horreur.Listener.ScrollListener
                                                                  at com.histoire_horreur.MainActivity.createView(MainActivity.java:59)
                                                                  at com.histoire_horreur.MainActivity.onCreate(MainActivity.java:47)
                                                                  at android.app.Activity.performCreate(Activity.java:5122)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:165)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                  at android.os.Looper.loop(Looper.java:194)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5391)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:525)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                  at dalvik.system.NativeStart.main(Native Method)

As I told, this code works fine for some versions of Android, but for my Wiko 4.2.2 it doesn't.
My error is the same than here : https://forums.xamarin.com/discussion/62241/problem-setting-on-scroll-listener-to-android-horizontal-scroll-view-class-not-found-exception
Solution there was to use ViewTreeObserver, however, I don't succeed to detect when scroll is at the bottom. I tried to do this :

scrollView = (ScrollView) findViewById(R.id.scrollView);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
// How to get X, Y, Old X and Old Y ?
}
});

But I can't get scrollX, scrollY, oldScrollX and oldScrollY.

Do you know a way to make it work on all verisons of Android ?

Body:
i have same problem.
if you use ViewTreeObserver the code working correctly with no exception, and only issue is detect when scroll view on the bottom.
this snip code can help you:

@Override
public void onScrollChanged() {

    View v = myScrollView.getChildAt(myScrollView.getChildCount() - 1);
    int diff = (v.getBottom() - (myScrollView.getHeight() + myScrollView.getScrollY()));
    if (diff <= 0) {
        //load data here, there is bottom of scrollview
     }
}


问:
Changing the entire string in a string builder object
I have the following code:

```<code>using System;
using System.Text;

public class Program
{
    private static StringBuilder mystrb = new StringBuilder("hello");
    public static void Main()
    {
        mystrb.Clear();
        mystrb.Append("chau");
    }
}
</code>```

is there any other way of entirly replacing the string in the string builder, i am looking for a one sentence way of doing it if it exist.

答:
What's wrong with just re-constructing the StringBuilder? The old one will just be garbage collected.</p>

```<code>mystrb = new StringBuilder("chau");
</code>```

Body:
I have the following code:

using System;
using System.Text;

public class Program
{
    private static StringBuilder mystrb = new StringBuilder("hello");
    public static void Main()
    {
        mystrb.Clear();
        mystrb.Append("chau");
    }
}

is there any other way of entirly replacing the string in the string builder, i am looking for a one sentence way of doing it if it exist.

Body:
What's wrong with just re-constructing the StringBuilder? The old one will just be garbage collected.

mystrb = new StringBuilder("chau");


问:
Generic extension methods using where T : Interface
Does these 2 extension methods are the same or is there some danger in using 1 of the 2

```<code>public static T  GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface
{
    //do somthing that returns an item of T
}
</code>```

Versus

```<code>public static IMyInterface GetSomthingFromList(this List<IMyInterface> list)
{
    //do somthing that returns an item of IMyInterface
}
</code>```

答:
The only real difference is in the return type, the first one will return the type itself and constrain it so that it has to implement IMyInterface, and the second will just return the IMyInterface instance.

The second is useful for when you just want to expose the interface's members; the first is good for when you need to return the original type, but make sure that you can treat it in the method as an IMyInterface.

Body:
Does these 2 extension methods are the same or is there some danger in using 1 of the 2

public static T  GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface
{
    //do somthing that returns an item of T
}

Versus

public static IMyInterface GetSomthingFromList(this List<IMyInterface> list)
{
    //do somthing that returns an item of IMyInterface
}


问:
NgFor doesn't update data with Pipe in Angular2
In this scenario, I'm displaying a list of students (array) to the view with ngFor:

```<code><li *ngFor="#student of students">{{student.name}}</li>
</code>```

It's wonderful that it updates whenever I add other student to the list.

However, when I give it a pipe to filter by the student name,

```<code><li *ngFor="#student of students | sortByName:queryElem.value ">{{student.name}}</li>
</code>```

It does not update the list until I type something in the filtering student name field.

Here's a link to plnkr.

Hello_world.html

```<code><h1>Students:</h1>
<label for="newStudentName"></label>
<input type="text" name="newStudentName" placeholder="newStudentName" #newStudentElem>
<button (click)="addNewStudent(newStudentElem.value)">Add New Student</button>
<br>
<input type="text" placeholder="Search" #queryElem (keyup)="0">
<ul>
    <li *ngFor="#student of students | sortByName:queryElem.value ">{{student.name}}</li>
</ul>
</code>```

sort_by_name_pipe.ts

```<code>import {Pipe} from 'angular2/core';

@Pipe({
    name: 'sortByName'
})
export class SortByNamePipe {

    transform(value, [queryString]) {
        // console.log(value, queryString);
        return value.filter((student) => new RegExp(queryString).test(student.name))
        // return value;
    }
}
</code>```

答:
From the angular documentation

Pure and impure pipes

There are two categories of pipes: pure and impure. Pipes are pure by default. Every pipe you've seen so far has been pure. You make a pipe impure by setting its pure flag to false. You could make the FlyingHeroesPipe impure like this:

@Pipe({
  name: 'flyingHeroesImpure',
  pure: false
})

Before doing that, understand the difference between pure and impure, starting with a pure pipe.

Pure pipes
Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.

This may seem restrictive but it's also fast. An object reference check is fast—much faster than a deep check for differences—so Angular can quickly determine if it can skip both the pipe execution and a view update.

For this reason, a pure pipe is preferable when you can live with the change detection strategy. When you can't, you can use the impure pipe.

Body:
In this scenario, I'm displaying a list of students (array) to the view with ngFor:

{{student.name}}

It's wonderful that it updates whenever I add other student to the list.

However, when I give it a pipe to filter by the student name,

{{student.name}}

It does not update the list until I type something in the filtering student name field.

Here's a link to plnkr.

Hello_world.html

Students:

<input type="text" name="newStudentName" placeholder="newStudentName" #newStudentElem>
<button (click)="addNewStudent(newStudentElem.value)">Add New Student</button>

<input type="text" placeholder="Search" #queryElem (keyup)="0">

{{student.name}}

sort_by_name_pipe.ts

import {Pipe} from 'angular2/core';

@Pipe({
    name: 'sortByName'
})
export class SortByNamePipe {

    transform(value, [queryString]) {
        // console.log(value, queryString);
        return value.filter((student) => new RegExp(queryString).test(student.name))
        // return value;
    }
}


问:
Connect to gce instance and run command
I have a simple request. I want to connect to an already existing google compute engine instance, run a command, and close the connection.

I have used the great sample code here for instance creation and deletion.

Additionally, I have a startup script running which works perfectly.

Now I am reading this article to use paramiko to connect to my instance. This may or may not be the best thing to do, so please correct me if I am going down the wrong path.

I have the following sample code:

```<code>import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())

ssh.connect('35.***.***.**',username='user',password='pass')
stdin, stdout, stderr = ssh.exec_command("sudo su -")
stdin, stdout, stderr = ssh.exec_command("ls -l")
stdout.readlines()
</code>```

Now - I am not sure which username or password I am supposed to use.

When I run this code, I do not get the list of files and directories in my root as I want, but I do get a list of files and directories in the default user account's home - so it is connecting.

My goal is to connect to a gce instance, run a command, and that is it! For some reason it is trickier than I anticipated. Am I doing something wrong here?

答:
If you are facing a similar use case you can explore gcloud ssh. It worked for me, but I cannot comment if this is best practice or not.

My solution here was something like the following:

```<code>import subprocess
def check_for_completion(instance_name = ""):
    cmd = "gcloud compute ssh  %s --zone=us-east1-b --command=\"sudo -S -i -u root -p '' ls /root/temp/ \""%(instance_name)
    try:
        res = subprocess.check_output(cmd, shell=True)
        items = str(res).split('\n')

        return {'response':items,'complete':False}
    except:
        return {'response':None,'complete':True}
</code>```

Title: Connect to gce instance and run command

Body:
I have a simple request. I want to connect to an already existing google compute engine instance, run a command, and close the connection.

I have used the great sample code here for instance creation and deletion.

Additionally, I have a startup script running which works perfectly.

Now I am reading this article to use paramiko to connect to my instance. This may or may not be the best thing to do, so please correct me if I am going down the wrong path.

I have the following sample code:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())

ssh.connect('35.***.***.**',username='user',password='pass')
stdin, stdout, stderr = ssh.exec_command("sudo su -")
stdin, stdout, stderr = ssh.exec_command("ls -l")
stdout.readlines()

Now - I am not sure which username or password I am supposed to use.

When I run this code, I do not get the list of files and directories in my root as I want, but I do get a list of files and directories in the default user account's home - so it is connecting.

My goal is to connect to a gce instance, run a command, and that is it! For some reason it is trickier than I anticipated. Am I doing something wrong here?

Body:
If you are facing a similar use case you can explore gcloud ssh. It worked for me, but I cannot comment if this is best practice or not.

My solution here was something like the following:

import subprocess
def check_for_completion(instance_name = ""):
    cmd = "gcloud compute ssh  %s --zone=us-east1-b --command=\"sudo -S -i -u root -p '' ls /root/temp/ \""%(instance_name)
    try:
        res = subprocess.check_output(cmd, shell=True)
        items = str(res).split('\n')

        return {'response':items,'complete':False}
    except:
        return {'response':None,'complete':True}


问:
make width of  equal to its text contents
I have below snippet where td takes up space unnecessarily. For e.g. if the text contents inside td take 20 pixels width, td should also be 20 pixels wide. Can you help me fix it?

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
}

span {
   background-color: #7e7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table></code>```

答:
By default, table cells will expand in order to fit all their content and the width of the cell will depend on the widest cell in that column.

So trying to shrink-wrap a table-cell doesn't really make much sense.

If you do actually want a table-like layout, but you want a particular column to take up as little space as possible - you could set the cell  width: 1px; - that will make the column as wide as the longest word in the cells of that column.

table {
  table-layout: fixed;
}

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
   width: 1px; /* <--- */
}

span {
   background-color: #7e7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table></code>```

Title: make width of <td> equal to its text contents

Body:
I have below snippet where td takes up space unnecessarily. For e.g. if the text contents inside td take 20 pixels width, td should also be 20 pixels wide. Can you help me fix it?

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
}

span {
   background-color: #7e7;
}

The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily

    <input type="checkbox" name="checkbox" value="value">
    Excessive exhaust materialssss

    <input type="checkbox" name="checkbox" value="value">
    Excessive

Body:
By default, table cells will expand in order to fit all their content and the width of the cell will depend on the widest cell in that column.

So trying to shrink-wrap a table-cell doesn't really make much sense.

If you do actually want a table-like layout, but you want a particular column to take up as little space as possible - you could set the cell  width: 1px; - that will make the column as wide as the longest word in the cells of that column.

table {
  table-layout: fixed;
}

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
   width: 1px; /* <--- */
}

span {
   background-color: #7e7;
}

<h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table>