问:
Continuous to discrete legend on ggplot2 R

I am trying to plot curves with ggplot2 and group them by maturities. In my dataset maturities are expressed in remaining time in years.

My problem is that in my whole dataset I only have two maturities (0.15 and 0.2) but the legend displays color for 0.15, 0.16, 0.17...

Here is a screenshot :

Here is my code :

```<code>    call_vol_plot = ggplot(data=df[df$type=="C",],
       aes(x=strike,
           y=impliedVol,
           group = time_to_expiry,
           colour = time_to_expiry)) + geom_line() + geom_point(size=4, shape=21, fill="white")

    call_vol_plot = call_vol_plot + labs(title="Call Implied Volatility",
                           subtitle="Options on future contracts",
                           y="Implied Volatility",
                           x="Strike") + guides(color=guide_legend("Maturity in year"))
</code>```

I tried scale_color_discrete but it didn't work. Thank you !

答:
Solution : Replacing time_to_expiry by as.character(time_to_expiry) work as expected. R can't make continuous values with variables of type characters.

Many thanks to @Highland that almost gave the solution!

Body:
I am trying to plot curves with ggplot2 and group them by maturities. In my dataset maturities are expressed in remaining time in years.

My problem is that in my whole dataset I only have two maturities (0.15 and 0.2) but the legend displays color for 0.15, 0.16, 0.17...

Here is a screenshot :

Here is my code :

    call_vol_plot = ggplot(data=df[df$type=="C",],
       aes(x=strike,
           y=impliedVol,
           group = time_to_expiry,
           colour = time_to_expiry)) + geom_line() + geom_point(size=4, shape=21, fill="white")

    call_vol_plot = call_vol_plot + labs(title="Call Implied Volatility",
                           subtitle="Options on future contracts",
                           y="Implied Volatility",
                           x="Strike") + guides(color=guide_legend("Maturity in year"))

I tried scale_color_discrete but it didn't work. Thank you !


来源: stackexchange

问:
Setting up Bind9 Nameserver. Editing /etc/init.d/sysklogd help?
I'm following along with this tutorial and I've successfully gotten as far as a part which tells me to edit the "sysklogd" file in /etc/init.d/

The tutorial tells me that in order to allow logging of bind activity, I need to replace the line

SYSLOGD=""

with

```<code>SYSLOGD="-a /var/lib/named/dev/log"
</code>```

The trouble is that I can't find the first line.

Has the sysklogd file changed since the time this tutorial was written? Should I just inset the line myself?

Here is the contents of sysklogd below. I'm sorry it looks horrendous, I tried to format it better but it's doesn't seem to be happening for me. Just hoping it might jog someones memory.

```<code>#! /bin/sh
# /etc/init.d/sysklogd: start the system log daemon.

### BEGIN INIT INFO
# Provides:             sysklogd
# Required-Start:       $remote_fs $time
# Required-Stop:        $remote_fs $time
# Should-Start:         $network
# Should-Stop:          $network
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    System logger
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin

pidfile=/var/run/syslogd.pid
binpath=/sbin/syslogd

test -x $binpath || exit 0

test ! -r /etc/default/syslogd || . /etc/default/syslogd

. /lib/lsb/init-functions

create_xconsole()
{
    # Only proceed if /dev/xconsole is used at all
    if ! grep -q '^[^#].*/dev/xconsole' /etc/syslog.conf
    then
        return
    fi

    if [ ! -e /dev/xconsole ]; then
        mknod -m 640 /dev/xconsole p
    else
        chmod 0640 /dev/xconsole
    fi
    chown root:adm /dev/xconsole
    test ! -x /sbin/restorecon || /sbin/restorecon /dev/xconsole
}
running()
{
    # No pidfile, probably no daemon present
    #
    if [ ! -f $pidfile ]
    then
        return 1
    fi

    pid=`cat $pidfile`

    # No pid, probably no daemon present
    #
    if [ -z "$pid" ]
    then
        return 1
    fi

    if [ ! -d /proc/$pid ]
    then
        return 1
    fi

    cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1`

    # No syslogd?
    #
    if [ "$cmd" != "$binpath" ]
    then
        return 1
    fi

    return 0
}

case "$1" in
  start)
    log_begin_msg "Starting system log daemon..."
    create_xconsole
    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
    log_end_msg $?
    test -d /lib/init/rw/sendsigs.omit.d || mkdir -p /lib/init/rw/sendsigs.omit.d
    test ! -f /lib/init/rw/sendsigs.omit.d/sysklogd || rm -f /lib/init/rw/sendsigs.omit.d/sysklogd
    ln -s $pidfile /lib/init/rw/sendsigs.omit.d/sysklogd
    ;;
 stop)
    log_begin_msg "Stopping system log daemon..."
    start-stop-daemon --stop --quiet --pidfile $pidfile --name syslogd
    log_end_msg $?
    ;;
  reload|force-reload)
    log_begin_msg "Reloading system log daemon..."
    start-stop-daemon --stop --quiet --signal 1 --pidfile $pidfile --name syslogd
    log_end_msg $?
    ;;
  restart)
    log_begin_msg "Restarting system log daemon..."
    start-stop-daemon --stop --retry 5 --quiet --pidfile $pidfile --name syslogd
    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
    log_end_msg $?
    ;;
  reload-or-restart)
    if running
    then
        $0 reload
    else
        $0 start
    fi
    ;;
  *)
    log_success_msg "Usage: /etc/init.d/sysklogd {start|stop|reload|restart|force-reload|reload-or-restart}"
    exit 1
esac

exit 0
</code>```

答: Look in /etc/default/syslogd.

ContentLicense: CC BY-SA 2.5

Body:
I'm following along with this tutorial and I've successfully gotten as far as a part which tells me to edit the "sysklogd" file in /etc/init.d/

The tutorial tells me that in order to allow logging of bind activity, I need to replace the line

SYSLOGD=""

with

SYSLOGD="-a /var/lib/named/dev/log"

The trouble is that I can't find the first line.

Has the sysklogd file changed since the time this tutorial was written? Should I just inset the line myself?

Here is the contents of sysklogd below. I'm sorry it looks horrendous, I tried to format it better but it's doesn't seem to be happening for me. Just hoping it might jog someones memory.

#! /bin/sh
# /etc/init.d/sysklogd: start the system log daemon.

### BEGIN INIT INFO
# Provides:             sysklogd
# Required-Start:       $remote_fs $time
# Required-Stop:        $remote_fs $time
# Should-Start:         $network
# Should-Stop:          $network
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    System logger
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin

pidfile=/var/run/syslogd.pid
binpath=/sbin/syslogd

test -x $binpath || exit 0

test ! -r /etc/default/syslogd || . /etc/default/syslogd

. /lib/lsb/init-functions

create_xconsole()
{
    # Only proceed if /dev/xconsole is used at all
    if ! grep -q '^[^#].*/dev/xconsole' /etc/syslog.conf
    then
        return
    fi

    if [ ! -e /dev/xconsole ]; then
        mknod -m 640 /dev/xconsole p
    else
        chmod 0640 /dev/xconsole
    fi
    chown root:adm /dev/xconsole
    test ! -x /sbin/restorecon || /sbin/restorecon /dev/xconsole
}
running()
{
    # No pidfile, probably no daemon present
    #
    if [ ! -f $pidfile ]
    then
        return 1
    fi

    pid=`cat $pidfile`

    # No pid, probably no daemon present
    #
    if [ -z "$pid" ]
    then
        return 1
    fi

    if [ ! -d /proc/$pid ]
    then
        return 1
    fi

    cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1`

    # No syslogd?
    #
    if [ "$cmd" != "$binpath" ]
    then
        return 1
    fi

    return 0
}

case "$1" in
  start)
    log_begin_msg "Starting system log daemon..."
    create_xconsole
    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
    log_end_msg $?
    test -d /lib/init/rw/sendsigs.omit.d || mkdir -p /lib/init/rw/sendsigs.omit.d
    test ! -f /lib/init/rw/sendsigs.omit.d/sysklogd || rm -f /lib/init/rw/sendsigs.omit.d/sysklogd
    ln -s $pidfile /lib/init/rw/sendsigs.omit.d/sysklogd
    ;;
 stop)
    log_begin_msg "Stopping system log daemon..."
    start-stop-daemon --stop --quiet --pidfile $pidfile --name syslogd
    log_end_msg $?
    ;;
  reload|force-reload)
    log_begin_msg "Reloading system log daemon..."
    start-stop-daemon --stop --quiet --signal 1 --pidfile $pidfile --name syslogd
    log_end_msg $?
    ;;
  restart)
    log_begin_msg "Restarting system log daemon..."
    start-stop-daemon --stop --retry 5 --quiet --pidfile $pidfile --name syslogd
    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
    log_end_msg $?
    ;;
  reload-or-restart)
    if running
    then
        $0 reload
    else
        $0 start
    fi
    ;;
  *)
    log_success_msg "Usage: /etc/init.d/sysklogd {start|stop|reload|restart|force-reload|reload-or-restart}"
    exit 1
esac

exit 0

Body: Look in /etc/default/syslogd.


问:
Numeric value[i] in list Python
In Django template I want get data from some list, example :

In Django template I want get data from some list, example :

```<code>list pages as data(doc in couch_db):
{
        "_id": "someone",
        "_rev": "someone",
        "is_active": true,
        "priority_questions": 1,
        "answer_<em>3</em>": "test-data3",
        "answer_<em>2</em>": "test-data2",
        "answer_<em>1</em>": "test-data1",
        "answer_<em>0</em>": "test",
        "ask_3": "test-ask3",
        "ask_2": "test-ask2",
        "ask_1": "test-ask1",
        "ask_0": "test-ask",
        "title": "new-test",
        "extra_field_count": "4",
        "priority_3": 4,
        "priority_2": 3,
        "priority_1": 3,
        "priority_0": 1,
        "type": "help"
 }
</code>```

template:

```<code>{% for page in pages %}
        <div class="box">
            {{ page.title }}
                {% for i in page.extra_field_count %}
                    {{ page.ask_<em>[i]</em> }}
                    {{ page.answer_<em>[i]</em> }}
                {% end_for %}
    {% end_for %}
</code>```

Please help me, if you can

答:
You need to remove  from page.answer_[i] and  page.ask_[i].

```<code>{% for page in pages %}
            <div class="box">
                {{ page.title }}
                    {% for i in page.extra_field_count %}
                        {{ page.ask_[i] }}
                        {{ page.answer_[i] }}
                    {% end_for %}
        {% end_for %}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Numeric value[i] in list Python

Body:
In Django template I want get data from some list, example :

In Django template I want get data from some list, example :

list pages as data(doc in couch_db):
{
        "_id": "someone",
        "_rev": "someone",
        "is_active": true,
        "priority_questions": 1,
        "answer_3": "test-data3",
        "answer_2": "test-data2",
        "answer_1": "test-data1",
        "answer_0": "test",
        "ask_3": "test-ask3",
        "ask_2": "test-ask2",
        "ask_1": "test-ask1",
        "ask_0": "test-ask",
        "title": "new-test",
        "extra_field_count": "4",
        "priority_3": 4,
        "priority_2": 3,
        "priority_1": 3,
        "priority_0": 1,
        "type": "help"
 }

template:

{% for page in pages %}

            {{ page.title }}
                {% for i in page.extra_field_count %}
                    {{ page.ask_[i] }}
                    {{ page.answer_[i] }}
                {% end_for %}
    {% end_for %}

Please help me, if you can

Body:
You need to remove <em> from page.answer_[i] and  page.ask_[i].

{% for page in pages %}
            <div class="box">
                {{ page.title }}
                    {% for i in page.extra_field_count %}
                        {{ page.ask_[i] }}
                        {{ page.answer_[i] }}
                    {% end_for %}
        {% end_for %}


问:
iOS app launch time and secondary thread
I am using time profiler to analyse my app launch time.
Does secondary/background thread also impact app launch time.

Please clarify secondary thread role at app launch time.

If we are comparing launch time for two versions of app, Should we consider time differences in secondary threads as well.
What should be the best approach?

Thanks

答: App is launched after you return true from didFinishLaunchingWithOptions. Background thread won't block launching if it was async.</p>


问:
Defining a circular area for bounds in an Android game
I want to make a simple lunar lander varient with asteroids. I've got asteroids, but I'm stumped on how to make them defined areas with bounds that if my ship crosses causes the player to lose. Any tips about defining a circle pixel area? If it helps, I know the exact coordinates of my asteroids.

Thanks for your advice.

(Looking for collision-detection advice)

Edit: My personal solution, slightly more verbose but no more helpful than the solution below :)

```<code>public boolean collisionDetection(double xa, double ya, double ra, double xb, double yb, double rb) {

        double distance = Math.sqrt(Math.pow(xa-xb, 2) + Math.pow(ya-yb, 2));

        if (distance < ra+rb)
            return true;
        else
            return false;
    }
</code>```

答:
This assumes you know the asteroids and ships co-ords and size:

```<code>float x = Asteroid.X - Ship.X;
float y = Asteroid.Y - Ship.Y;
float radius = Asteroid.Radius - Ship.Radius;

x *= x;
y *= y;
radius *= radius;

if((x+y) < radius)
{
   //collision
}
</code>```

EDIT: my function was wrong sorry, use this one

Thanks LarsH

Body:
I want to make a simple lunar lander varient with asteroids. I've got asteroids, but I'm stumped on how to make them defined areas with bounds that if my ship crosses causes the player to lose. Any tips about defining a circle pixel area? If it helps, I know the exact coordinates of my asteroids.

Thanks for your advice.

(Looking for collision-detection advice)

Edit: My personal solution, slightly more verbose but no more helpful than the solution below :)

public boolean collisionDetection(double xa, double ya, double ra, double xb, double yb, double rb) {

        double distance = Math.sqrt(Math.pow(xa-xb, 2) + Math.pow(ya-yb, 2));

        if (distance < ra+rb)
            return true;
        else
            return false;
    }

Body:
This assumes you know the asteroids and ships co-ords and size:

float x = Asteroid.X - Ship.X;
float y = Asteroid.Y - Ship.Y;
float radius = Asteroid.Radius - Ship.Radius;

x *= x;
y *= y;
radius *= radius;

if((x+y) < radius)
{
   //collision
}

EDIT: my function was wrong sorry, use this one

Thanks LarsH


问:
Set-Cookie header in Ajax response doesn't work with android webView
I've been reading answers, questions, forums and blogs for 2 days now but can't fix my issue.

I've an AngularJS webApp working in a Native (SDK) Android App with a WebView.

Everything seems to work but when my application calls services that responds with the "Set-Cookie" header those cookies are not setted in the webview and, of course are neither sent in the next calls, so my app explodes.

The app works flawlessly in browser and cordova and "document.cookie" returns an empty string, so i know this is where it fails.

My webview is initialized like this:

```<code>public class Main extends AppCompatActivity {
...

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView webview = (WebView) findViewById(R.id.webview);
    webview.setWebViewClient(new mWebViewClient());

    webview.getSettings().setAppCacheEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setSavePassword(true);
    webview.getSettings().setAllowFileAccessFromFileURLs(true);
    webview.getSettings().setAllowContentAccess(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setUserAgentString(...);
    webview.loadUrl("file:///android_asset/www/index.html");

    javascriptAPI = new JavascriptAPI(this);
    webview.addJavascriptInterface(javascriptAPI, "jsAPI");
    ...
  }
  ...
}
</code>```

I've tried also with chunks of code from here and there like:

```<code>        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().run();
        CookieManager.getInstance().setAcceptCookie(true);
</code>```

But it doesn't work neither.

My app is calling to some services that use redirect, so fetching the cookies from JS and setting them is not an option, i need the webview to work like a browser would.

This is my first SDK Android App and i'm not sure at all what info could be relevant to answer the question (manifest, jsAPI, etc) so don't hessitate to say and i'll post whatever else is needed

SOLVED

Thank you @Mark, this fixed my code:

(inside Activity onCreate)

```<code>...
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    CookieSyncManager.createInstance(this);
}
 ^^^^^^^
  THIS

WebView webview = (WebView) findViewById(R.id.webview);

CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().run();
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().setAcceptFileSchemeCookies(true); <- THIS
CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true); <- THIS

webview.setWebViewClient(new mWebViewClient());
webview.getSettings().setAppCacheEnabled(true);
...
</code>```

答:
There are three acceptCookie methods you need to worry about, and different behavior across several versions of Android to take into consideration.

1) I noticed your initial url is a file:// url. You may need to call CookieManager.getInstance().setAcceptFileSchemeCookies(true);.

2) In Android Lollipop and greater, you may need to call CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

3) For Android versions < Lollipop, if you want cookies to be persisted (e.g., survive rotation), you have to take some steps to manually manage syncing.

First, to ensure that CookieSyncManager is initialized during application startup by adding it your appplication class' onCreate(), or extend this one.

```<code>public class CookieApplication extends Application {
   @Override
   public void onCreate() {
      super.onCreate();
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
         CookieSyncManager.createInstance(this);
      }
   }
}
</code>```

Second, you need to setup syncing for pre-lollipop devices, and finally to enable cookies.  Here's an example activity that you could extend that sets up all the syncing for pre-Lollipop devices, and provides an enablesCookies(webView) that should turn on all cookie types regardless of Android version (be advised there are security considerations to be made when calling these methods!). Note that all of the CookieManager.getInstance().set*Cookie*() methods must be called after the webView is initialized.

```<code>public class AppCompatCookieActivity extends AppCompatActivity {

   @Override
   public void onResume() {
      super.onResume();
      // start cookie syncing for pre-lollipop devices
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
         CookieSyncManager.getInstance().startSync();
      }
   }

   @Override
   public void onPause() {
      // stop cookie syncing for pre-lollipop devices
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
         CookieSyncManager.getInstance().sync();
      }
      super.onPause();
   }

   public final void enableCookies(WebView webView) {
      // enable javascript (has security implications!)
      webView.getSettings().setJavaScriptEnabled(true);

      // enable cookies.
      CookieManager.getInstance().setAcceptCookie(true);

      // enable fileScheme cookies (has security implications!)
      // it is recommended to comment this out should you find it not necessary
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
         CookieManager.getInstance().setAcceptFileSchemeCookies(true);
      }

      // enable third party cookies
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
      }
   }
}
</code>```

Body:
I've been reading answers, questions, forums and blogs for 2 days now but can't fix my issue.

I've an AngularJS webApp working in a Native (SDK) Android App with a WebView.

Everything seems to work but when my application calls services that responds with the "Set-Cookie" header those cookies are not setted in the webview and, of course are neither sent in the next calls, so my app explodes.

The app works flawlessly in browser and cordova and "document.cookie" returns an empty string, so i know this is where it fails.

My webview is initialized like this:

public class Main extends AppCompatActivity {
...

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView webview = (WebView) findViewById(R.id.webview);
    webview.setWebViewClient(new mWebViewClient());

    webview.getSettings().setAppCacheEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setSavePassword(true);
    webview.getSettings().setAllowFileAccessFromFileURLs(true);
    webview.getSettings().setAllowContentAccess(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setUserAgentString(...);
    webview.loadUrl("file:///android_asset/www/index.html");

    javascriptAPI = new JavascriptAPI(this);
    webview.addJavascriptInterface(javascriptAPI, "jsAPI");
    ...
  }
  ...
}

I've tried also with chunks of code from here and there like:

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().run();
        CookieManager.getInstance().setAcceptCookie(true);

But it doesn't work neither.

My app is calling to some services that use redirect, so fetching the cookies from JS and setting them is not an option, i need the webview to work like a browser would.

This is my first SDK Android App and i'm not sure at all what info could be relevant to answer the question (manifest, jsAPI, etc) so don't hessitate to say and i'll post whatever else is needed

SOLVED

Thank you @Mark, this fixed my code:

(inside Activity onCreate)

...
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    CookieSyncManager.createInstance(this);
}
 ^^^^^^^
  THIS

WebView webview = (WebView) findViewById(R.id.webview);

CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().run();
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().setAcceptFileSchemeCookies(true); <- THIS
CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true); <- THIS

webview.setWebViewClient(new mWebViewClient());
webview.getSettings().setAppCacheEnabled(true);
...

Body:
There are three acceptCookie methods you need to worry about, and different behavior across several versions of Android to take into consideration.

1) I noticed your initial url is a file:// url. You may need to call CookieManager.getInstance().setAcceptFileSchemeCookies(true);.

2) In Android Lollipop and greater, you may need to call CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

3) For Android versions < Lollipop, if you want cookies to be persisted (e.g., survive rotation), you have to take some steps to manually manage syncing.

First, to ensure that CookieSyncManager is initialized during application startup by adding it your appplication class' onCreate(), or extend this one.

public class CookieApplication extends Application {
   @Override
   public void onCreate() {
      super.onCreate();
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
         CookieSyncManager.createInstance(this);
      }
   }
}

Second, you need to setup syncing for pre-lollipop devices, and finally to enable cookies.  Here's an example activity that you could extend that sets up all the syncing for pre-Lollipop devices, and provides an enablesCookies(webView) that should turn on all cookie types regardless of Android version (be advised there are security considerations to be made when calling these methods!). Note that all of the CookieManager.getInstance().set*Cookie*() methods must be called after the webView is initialized.

public class AppCompatCookieActivity extends AppCompatActivity {

   @Override
   public void onResume() {
      super.onResume();
      // start cookie syncing for pre-lollipop devices
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
         CookieSyncManager.getInstance().startSync();
      }
   }

   @Override
   public void onPause() {
      // stop cookie syncing for pre-lollipop devices
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
         CookieSyncManager.getInstance().sync();
      }
      super.onPause();
   }

   public final void enableCookies(WebView webView) {
      // enable javascript (has security implications!)
      webView.getSettings().setJavaScriptEnabled(true);

      // enable cookies.
      CookieManager.getInstance().setAcceptCookie(true);

      // enable fileScheme cookies (has security implications!)
      // it is recommended to comment this out should you find it not necessary
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
         CookieManager.getInstance().setAcceptFileSchemeCookies(true);
      }

      // enable third party cookies
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
      }
   }
}


问:
Rewrite a csv file by rearranging columns and rows
I have a csv file (let's call it input.csv) that looks like this:

```<code>ID; Text_1; Points_1; Text_2; Points_2
1; "Hello world one"; 33; "Hello world two"; 90
2, "Goodbye world one"; 44; "Goodbye world two";100
</code>```

I want to create another csv file (let's call it output.csv) that rearranges the columns like this:

```<code> ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100
</code>```

It does not seem as easy as a priori I thought. I wonder if there is a way to directly transcribe the file. Thanks in advance.

I've tried this with some help, but I have difficulties to read and copy the columns and rows in the order I said.

```<code>with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0]

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])
</code>```

答:
Just read each row and write out two rows with the appropriate fields:

```<code>import csv

with open('input.csv','r',newline='') as infile:
    with open('output.csv','w',newline='') as outfile:
        r = csv.reader(infile,delimiter=';')
        w = csv.writer(outfile,delimiter=';')
        next(r) # skip the original header
        w.writerow('ID Field Sent Points'.split())
        for id,t1,p1,t2,p2 in r:
            w.writerows([[id,'Text_1',t1,p1],
                         [id,'Text_2',t2,p2]])
</code>```

Output:

```<code>ID;Field;Sent;Points
1;Text_1;Hello world one;33
1;Text_2;Hello world two;90
2;Text_1;Goodbye world one;44
2;Text_2;Goodbye world two;100
</code>```

Note: Quotes are unnecessary for the .csv module unless the field contains a delimiter.  There are other options to csv.writer for quoting if you want them.

Body:
I have a csv file (let's call it input.csv) that looks like this:

ID; Text_1; Points_1; Text_2; Points_2
1; "Hello world one"; 33; "Hello world two"; 90
2, "Goodbye world one"; 44; "Goodbye world two";100

I want to create another csv file (let's call it output.csv) that rearranges the columns like this:

 ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100

It does not seem as easy as a priori I thought. I wonder if there is a way to directly transcribe the file. Thanks in advance.

I've tried this with some help, but I have difficulties to read and copy the columns and rows in the order I said.

with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0]

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])

Body:
Just read each row and write out two rows with the appropriate fields:

import csv

with open('input.csv','r',newline='') as infile:
    with open('output.csv','w',newline='') as outfile:
        r = csv.reader(infile,delimiter=';')
        w = csv.writer(outfile,delimiter=';')
        next(r) # skip the original header
        w.writerow('ID Field Sent Points'.split())
        for id,t1,p1,t2,p2 in r:
            w.writerows([[id,'Text_1',t1,p1],
                         [id,'Text_2',t2,p2]])

Output:

ID;Field;Sent;Points
1;Text_1;Hello world one;33
1;Text_2;Hello world two;90
2;Text_1;Goodbye world one;44
2;Text_2;Goodbye world two;100

Note: Quotes are unnecessary for the .csv module unless the field contains a delimiter.  There are other options to csv.writer for quoting if you want them.


问:
Android: Exit full screen and return to main activity
Main activity contains a spinner and a button. MainActivity.java code is as follows.

public class MainActivity extends AppCompatActivity implements LoadNew.VCallback {

    public Spinner dropdown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dropdown = (Spinner) findViewById(R.id.spinner1);

        //Create a list of items for the spinner.
        String[] items = new String[]{"select topic", "topic1", "topic2"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // TODO Auto-generated method stub
                String sp1 = String.valueOf(dropdown.getSelectedItem());
                if (sp1.contentEquals("select topic")) {
                    loadFun("");
                }
                if (sp1.contentEquals("topic1")) {
                    loadFun("topic1");
                }
                if (sp1.contentEquals("topic2")) {
                    loadFun("topic2");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView){
                // TODO Auto-generated method stub
            }
        });

        Button x = (Button) findViewById(R.id.full_screen);
        x.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFun("topic2", 0);
            }
        });
    }

    public void loadFun(String topicName, int i) {
        LoadNew st = new LoadNew(this);
        st.display(topicName, i);
    }
}```
</div>
</div>
</p>

<p>The xml layout for main activity is as follows (activity_main.xml).</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
            <Spinner
                android:id="@+id/spinner1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:drawable/btn_dropdown"
                android:spinnerMode="dropdown" />
        </LinearLayout>
        <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:orientation="horizontal" >
             <Button
                android:id="@+id/full_screen"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Full Screen"
                style="?android:attr/borderlessButtonStyle"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/full_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
        </LinearLayout>

    </LinearLayout>
</RelativeLayout></code>```

There is another java class LoadNew.java as follows.

public class LoadNew {

    public interface VCallback {
        //To access methods of MainActivity class
    }

    public Activity activity;

    public LoadNew(Activity _activity) {
        this.activity = _activity;
        VCallback callerActivity = (VCallback) activity;

    }

    //Display PDF
    public void display(String topicName, int i) {
        LinearLayout fullScreen = (LinearLayout) this.activity.findViewById(R.id.full_view);
        fullScreen.removeAllViews();//Clear field
        LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.activity_load, null);
        if(i ==0) {
         this.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            this.activity.setContentView(view);
        }
        TextView tv= (TextView) this.activity.findViewById(R.id.tv1);
        tv.setText(topicName);
        tv.setTextSize(100);
    }
}```
</div>
</div>
</p>

<p>The activity_load.xml file is as follows.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout> xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/tv1"
    android:layout_below="@+id/bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</RelativeLayout></code>```

When an item is selected in the spinner, the corresponding text is displayed in the textview. Upon pressing the button, the textview appears in full screen mode.
Now I want to return to the previous view (by pressing back button or by single tab on screen), i.e., the view before the button was clicked. How can I achieve this? Thanks in advance for the patience and the help.

答: Simplest would be to have the spinner and the non-fullscreen TextView on one activity and open a second activity with the fullscreen mode on button click.</p>

Body:
Main activity contains a spinner and a button. MainActivity.java code is as follows.

public class MainActivity extends AppCompatActivity implements LoadNew.VCallback {

    public Spinner dropdown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dropdown = (Spinner) findViewById(R.id.spinner1);

        //Create a list of items for the spinner.
        String[] items = new String[]{"select topic", "topic1", "topic2"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // TODO Auto-generated method stub
                String sp1 = String.valueOf(dropdown.getSelectedItem());
                if (sp1.contentEquals("select topic")) {
                    loadFun("");
                }
                if (sp1.contentEquals("topic1")) {
                    loadFun("topic1");
                }
                if (sp1.contentEquals("topic2")) {
                    loadFun("topic2");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView){
                // TODO Auto-generated method stub
            }
        });

        Button x = (Button) findViewById(R.id.full_screen);
        x.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFun("topic2", 0);
            }
        });
    }

    public void loadFun(String topicName, int i) {
        LoadNew st = new LoadNew(this);
        st.display(topicName, i);
    }
}

The xml layout for main activity is as follows (activity_main.xml).

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
            <Spinner
                android:id="@+id/spinner1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:drawable/btn_dropdown"
                android:spinnerMode="dropdown" />
        </LinearLayout>
        <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:orientation="horizontal" >
             <Button
                android:id="@+id/full_screen"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Full Screen"
                style="?android:attr/borderlessButtonStyle"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/full_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

There is another java class LoadNew.java as follows.

public class LoadNew {

    public interface VCallback {
        //To access methods of MainActivity class
    }

    public Activity activity;

    public LoadNew(Activity _activity) {
        this.activity = _activity;
        VCallback callerActivity = (VCallback) activity;

    }

    //Display PDF
    public void display(String topicName, int i) {
        LinearLayout fullScreen = (LinearLayout) this.activity.findViewById(R.id.full_view);
        fullScreen.removeAllViews();//Clear field
        LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.activity_load, null);
        if(i ==0) {
         this.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            this.activity.setContentView(view);
        }
        TextView tv= (TextView) this.activity.findViewById(R.id.tv1);
        tv.setText(topicName);
        tv.setTextSize(100);
    }
}

The activity_load.xml file is as follows.

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

<TextView
    android:id="@+id/tv1"
    android:layout_below="@+id/bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</RelativeLayout>

When an item is selected in the spinner, the corresponding text is displayed in the textview. Upon pressing the button, the textview appears in full screen mode.
Now I want to return to the previous view (by pressing back button or by single tab on screen), i.e., the view before the button was clicked. How can I achieve this? Thanks in advance for the patience and the help.


问:
NSString memory leak when parsing xml
am writing an application that parses some xml and creates a dictionary of the element names and their values using the below key methods:

```<code>- (void)parserDidStartDocument:(NSXMLParser *)parser{
    foundCharacters = [[NSMutableString alloc] init];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (accumulator) {
        [foundCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([foundCharacters length] != 0) {

                    [parsedContent setObject:[foundCharacters copy] forKey:elementName];

                }
}
</code>```

The leak occurs in the occurs on the "[parsedContent setObject:[foundCharacters copy] forKey:elementName];" line, I can't work out a way to overcome this.

Any insights would be much appreciated.

Edit:

The memory leak only occurs if the request to parse is called more than once

I've also tried "[[foundCharacters copy] autorelease]" but no to avale

答:
"copy" methods are treated like alloc/init, you're responsible for releasing them.  See here:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/copy

so change your code to:

```<code>NSString *copy = [foundCharacters copy];
[parsedContent setObject:copy forKey:elementName];
[copy release];
</code>```

Title: NSString memory leak when parsing xml

Body:
am writing an application that parses some xml and creates a dictionary of the element names and their values using the below key methods:

- (void)parserDidStartDocument:(NSXMLParser *)parser{
    foundCharacters = [[NSMutableString alloc] init];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (accumulator) {
        [foundCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([foundCharacters length] != 0) {

                    [parsedContent setObject:[foundCharacters copy] forKey:elementName];

                }
}

The leak occurs in the occurs on the "[parsedContent setObject:[foundCharacters copy] forKey:elementName];" line, I can't work out a way to overcome this.

Any insights would be much appreciated.

Edit:

The memory leak only occurs if the request to parse is called more than once

I've also tried "[[foundCharacters copy] autorelease]" but no to avale

Body:
"copy" methods are treated like alloc/init, you're responsible for releasing them.  See here:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/copy

so change your code to:

NSString *copy = [foundCharacters copy];
[parsedContent setObject:copy forKey:elementName];
[copy release];


问:
How to display a picture from library in Ionic 3
I tried to display a picture from library in Ionic project.

I used :

Ionic 3

Angular 4

iOS emulator

In Comopent :

```<code>    const options: CameraOptions = {
        quality: 100,
        sourceType: PictureSourceType.PHOTOLIBRARY,
        destinationType: this.camera.DestinationType.FILE_URI,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE
    };

    this.camera.getPicture(options)
        .then(imageUri => {
            console.log(imageUri);
            this.selectedPictureUri = imageUri;
        })
        .catch(error => {
            console.error(error);
        });
</code>```

In HTML :

```<code><img *ngIf="selectedPictureUri" [src]="selectedPictureUri">
</code>```

The URL obtained is the following :

```<code>file:///Users/...692F7E7A4086/tmp/cdv_photo_015.jpg
</code>```

In console the following error :

```<code>Not allowed to load local resource: file:///Users/...692F7E7A4086/tmp/cdv_photo_015.jpg
</code>```

答:
It depends on the renderer used with your Ionic app. If it's UIWebView then to make your example work, you need to use the Sanitizer class.

import { DomSanitizer } from '@angular/platform-browser';

// ....

constructor(private sanitizer: DomSanitizer) { }

// ...

this.camera.getPicture(options).then(imageUri => {
  this.selectedPictureUri = this.sanitizer.bypassSecurityTrustUrl(imageUri);
}).catch(console.error);
```

<p>This is needed because Angular does it's best to protect you from XSS attacks, so you need to tell angular explicitly that you want that image to appear there from the local system.</p>

<p>If you use the newer WKWebView you need to read your paths differently, you can find the details in the blog post about it on the Ionic Blog. In short:</p>

<pre class="lang-js prettyprint-override"><code>import { normalizeURL } from 'ionic-angular';

// instead of
this.selectedPictureUri = imageUri;
// you need to use
this.selectedPictureUri = normalizeURL(imageUri);
</code>```

Body:
I tried to display a picture from library in Ionic project.

I used :

Ionic 3

Angular 4

iOS emulator

In Comopent :

    const options: CameraOptions = {
        quality: 100,
        sourceType: PictureSourceType.PHOTOLIBRARY,
        destinationType: this.camera.DestinationType.FILE_URI,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE
    };

    this.camera.getPicture(options)
        .then(imageUri => {
            console.log(imageUri);
            this.selectedPictureUri = imageUri;
        })
        .catch(error => {
            console.error(error);
        });

In HTML :

The URL obtained is the following :

file:///Users/...692F7E7A4086/tmp/cdv_photo_015.jpg

In console the following error :

Not allowed to load local resource: file:///Users/...692F7E7A4086/tmp/cdv_photo_015.jpg

Body:
It depends on the renderer used with your Ionic app. If it's UIWebView then to make your example work, you need to use the Sanitizer class.

import { DomSanitizer } from '@angular/platform-browser';

// ....

constructor(private sanitizer: DomSanitizer) { }

// ...

this.camera.getPicture(options).then(imageUri => {
  this.selectedPictureUri = this.sanitizer.bypassSecurityTrustUrl(imageUri);
}).catch(console.error);

This is needed because Angular does it's best to protect you from XSS attacks, so you need to tell angular explicitly that you want that image to appear there from the local system.

If you use the newer WKWebView you need to read your paths differently, you can find the details in the blog post about it on the Ionic Blog. In short:

import { normalizeURL } from 'ionic-angular';

// instead of
this.selectedPictureUri = imageUri;
// you need to use
this.selectedPictureUri = normalizeURL(imageUri);


问:
Creating a directory shortcut in powershell
I'm writing my first powershell script and I'm having a little trouble.

Up to this point my system creates a directory tree and populates it with files. The final step is to put a shortcut on my desktop.

I've come up with the code below:

```<code>$ShortcutFile = "$home\Desktop\" + $protocol + ".lnk"
If ( (test-path -path "$ShortcutFile") -ne $true)
{
    $WScriptShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
    $Shortcut.TargetPath = $root_path
    $Shortcut.Save()
}
</code>```

This doesn't work as I'm sure any experienced powershell user knows. A file is created rather than a directory. I imagine the correct way to fix this is to change one of the object members in WScript.Shell which control's the file type. I have had no luck locating any resources on how to do this specifically, or any other way to go about doing it. I found the API on the MSDN website but there where only a few members listed. There must be more.
What is the best way to accomplish this?

Thanks

答:
Assuming that you mean the shortcut type is a File rather than a File folder then a workaround is to make an Application launcher instead, which always works.

I originally found this solution here.

```<code>    $wsshell = New-Object -ComObject WScript.Shell
    $lnk = $wsshell.CreateShortcut($ShortcutFile)
    $lnk.WindowStyle = 1
    $lnk.TargetPath = "explorer.exe"
    $lnk.Arguments = $TargetPath
    $lnk.IconLocation = "explorer.exe,0"
    $lnk.save() # This will overwrite the previous link if it existed
</code>```

Body:
I'm writing my first powershell script and I'm having a little trouble.

Up to this point my system creates a directory tree and populates it with files. The final step is to put a shortcut on my desktop.

I've come up with the code below:

$ShortcutFile = "$home\Desktop\" + $protocol + ".lnk"
If ( (test-path -path "$ShortcutFile") -ne $true)
{
    $WScriptShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
    $Shortcut.TargetPath = $root_path
    $Shortcut.Save()
}

This doesn't work as I'm sure any experienced powershell user knows. A file is created rather than a directory. I imagine the correct way to fix this is to change one of the object members in WScript.Shell which control's the file type. I have had no luck locating any resources on how to do this specifically, or any other way to go about doing it. I found the API on the MSDN website but there where only a few members listed. There must be more.
What is the best way to accomplish this?

Thanks

Body:
Assuming that you mean the shortcut type is a File rather than a File folder then a workaround is to make an Application launcher instead, which always works.

I originally found this solution here.

    $wsshell = New-Object -ComObject WScript.Shell
    $lnk = $wsshell.CreateShortcut($ShortcutFile)
    $lnk.WindowStyle = 1
    $lnk.TargetPath = "explorer.exe"
    $lnk.Arguments = $TargetPath
    $lnk.IconLocation = "explorer.exe,0"
    $lnk.save() # This will overwrite the previous link if it existed


问:
Does GWT remove unused classes during compilation?
Suppose I have a project structure that looks roughly like this:

```<code>{module-package}.webapp
    module.gwt.xml
{module-package}.webapp.client
    Client.java
    UsedByClient.java
    NotUsedByClient.java
</code>```

And the module.gwt.xml file has:

```<code><source path='client'/>
<entry-point class='{module-package}.webapp.client.Client'/>
</code>```

When I compile this project using GWT, how much of the Java code will be compiled into Javascript?

Is NotUsedByClient.java included, even though the entry point doesn't reference it?

Is UsedByClient.java fully or partially included?  E.g. if it has method m() which isn't called by Client, will m be compiled or not?

The motivation is that unfortunately I'm working with a legacy codebase that has server-side code living alongside client-side code in the same package and it would be some work to separate them.  The server-side code isn't used by the client, but I'm concerned that GWT might compile it to Javascript where someone might notice it and try to reverse engineer it.

答:
I somehow managed to stumble upon a 'deep dive' video presentation on the compiler by one of the GWT engineers which has an explanation:  https://youtu.be/n-P4RWbXAT8?t=865

Key points:

One of the compiler optimizations is called Pruner and it will "Traverse all reachable code from entrypoint, delete everything else (uses ControlFlowAnalyzer)"

It is actually an essential optimization because without it, all GWT apps would need to include gwt-user.jar in its entirety, which would greatly increase app sizes.

So it seems the GWT compiler does indeed remove unused code.

Body:
Suppose I have a project structure that looks roughly like this:

{module-package}.webapp
    module.gwt.xml
{module-package}.webapp.client
    Client.java
    UsedByClient.java
    NotUsedByClient.java

And the module.gwt.xml file has:

<source path='client'/>
<entry-point class='{module-package}.webapp.client.Client'/>

When I compile this project using GWT, how much of the Java code will be compiled into Javascript?

Is NotUsedByClient.java included, even though the entry point doesn't reference it?

Is UsedByClient.java fully or partially included?  E.g. if it has method m() which isn't called by Client, will m be compiled or not?

The motivation is that unfortunately I'm working with a legacy codebase that has server-side code living alongside client-side code in the same package and it would be some work to separate them.  The server-side code isn't used by the client, but I'm concerned that GWT might compile it to Javascript where someone might notice it and try to reverse engineer it.


问:
How do I save a level layout in a variable
Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly.

Either way, How do I do this?

ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T.

```<code>import pygame

# Storage method A
level = '''
X X X X X
X X X X X
T T X X X
X X X T T
T T T T T
'''

# Storage Method B

level2 = [
    'XXXXX',
    'XXXXX',
    'TTXXX',
    'XXXTT',
    'TTTTT'
]

# X is blank space, T is tiles

# Then what? Thats what I need to know.
# If someone already answered this and I'm just not using the right keywords let me know.
</code>```

答:
There is no magic here: "it just renders in the game" is not accurate.  There's more software behind the rendering call, a module that defines the tile sprites, scans the level character by character, and places the sprites accordingly.  The developer (e.g. you) decides on the level representation, sprite form, sprite placement, etc.

You have several bits of code to write.  The good news is that you decide the format; you just have to stay consistent when you write those modules.

Body:
Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly.

Either way, How do I do this?

ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T.

import pygame

# Storage method A
level = '''
X X X X X
X X X X X
T T X X X
X X X T T
T T T T T
'''

# Storage Method B

level2 = [
    'XXXXX',
    'XXXXX',
    'TTXXX',
    'XXXTT',
    'TTTTT'
]

# X is blank space, T is tiles

# Then what? Thats what I need to know.
# If someone already answered this and I'm just not using the right keywords let me know.


问:
Why do I need reinterpret_cast from `long &` to `int &` where both are 32-bit (Windows LLP64)?
I am working with Qt in a cross-platform environment. And we are running into the following problem: On Windows, both int and long int are 32-bit integers; on 64-bit MacOS and Linux, int is 32-bit and long int is 64 bit (see https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models).

So, cross-platform libraries tend to provide their own fixed-bit typedefs. On Windows, Qt defines quint32 to be a unsigned int and does not use unsigned long integers. Another library defines its Uint32 however to be unsigned long. So, both are in fact 32-bit unsigned integers but have a different primitive data-type.

Now, it happens, that we try to use QDataStream serialization which is defined for quint32 with Uint32 data and to our surprise (or not), Visual C++ complains about the QDataStream operators not being defined for unsigned long which is true because Qt uses the almost equivalent unsigned int instead.

OK, the workaround is to provide

```<code>#ifdef Q_OS_WIN
inline QDataStream & operator >> (QDataStream & stream, Uint32 & value)
{ return stream >> reinterpret_cast<quint32 &>(value); }

inline QDataStream & operator << (QDataStream & stream, Uint32 value)
{ return stream << quint32(value); }
#endif // def Q_OS_WIN
</code>```

My question is: Why do I need to reinterpret_cast? I would feel way more comfortable with a static_cast given that to my understanding the data-types are in fact the same. Here be dragons?

答:
int and long are different data types, even if they happen to have the same properties otherwise.

Your operator>> causes undefined behaviour due to strict aliasing violation; the correct way to write the code would be:

```<code>inline QDataStream & operator >> (QDataStream & stream, Uint32 & value)
{
     quint32_t v;
     stream >> v;
     value = v;
     return stream;
}
</code>```

(Note: I'm assuming the QDataStream>> has the same property as C++11 istream>> in that it sets value to 0 on read failure; if not then you'll need to include a branch so that value = v; is not executed if read failed).

You can use static_cast for the operator<< since it is a value transformation. In fact you should be able to omit that operator<< entirely.

The problems you are lamenting in your question are a corollary of projects making up their own typedefs instead of using the standardized ones. Unfortunately it is just something you have to deal with until such time as the projects decide to move to standardized types.  If both had used uint32_t then this problem wouldn't exist.

Body:
I am working with Qt in a cross-platform environment. And we are running into the following problem: On Windows, both int and long int are 32-bit integers; on 64-bit MacOS and Linux, int is 32-bit and long int is 64 bit (see https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models).

So, cross-platform libraries tend to provide their own fixed-bit typedefs. On Windows, Qt defines quint32 to be a unsigned int and does not use unsigned long integers. Another library defines its Uint32 however to be unsigned long. So, both are in fact 32-bit unsigned integers but have a different primitive data-type.

Now, it happens, that we try to use QDataStream serialization which is defined for quint32 with Uint32 data and to our surprise (or not), Visual C++ complains about the QDataStream operators not being defined for unsigned long which is true because Qt uses the almost equivalent unsigned int instead.

OK, the workaround is to provide

#ifdef Q_OS_WIN
inline QDataStream & operator >> (QDataStream & stream, Uint32 & value)
{ return stream >> reinterpret_cast<quint32 &>(value); }

inline QDataStream & operator << (QDataStream & stream, Uint32 value)
{ return stream << quint32(value); }
#endif // def Q_OS_WIN

My question is: Why do I need to reinterpret_cast? I would feel way more comfortable with a static_cast given that to my understanding the data-types are in fact the same. Here be dragons?

Body:
int and long are different data types, even if they happen to have the same properties otherwise.

Your operator>> causes undefined behaviour due to strict aliasing violation; the correct way to write the code would be:

inline QDataStream & operator >> (QDataStream & stream, Uint32 & value)
{
     quint32_t v;
     stream >> v;
     value = v;
     return stream;
}

(Note: I'm assuming the QDataStream>> has the same property as C++11 istream>> in that it sets value to 0 on read failure; if not then you'll need to include a branch so that value = v; is not executed if read failed).

You can use static_cast for the operator<< since it is a value transformation. In fact you should be able to omit that operator<< entirely.

The problems you are lamenting in your question are a corollary of projects making up their own typedefs instead of using the standardized ones. Unfortunately it is just something you have to deal with until such time as the projects decide to move to standardized types.  If both had used uint32_t then this problem wouldn't exist.


问:
Saving NLTK Alignments
I am using NLTK 3.2 and I was wondering how you save NLTK alignments. I have found this link: How to save Python NLTK alignment models for later use?, but it seems that there is no align() method. Also, I figured out that nltk.align has been renamed to nltk.translate, but I still cannot access the align() method. Thanks!</p>

答:
Yeah, you are right. The method align became private in the current version. So, if you want to use that method, you have to modify the source code.

To modify the source code, you have to get to the directory of the file. You can find that directory by:

Open your terminal

Type these commands:

>>> python

>>> import nltk

>>> nltk.translate.ibm1.__file__

Here is a screen-shot of what it should look like:

Now, you have to go to that directory and find the file 'ibm1.py'. Open the file and modify the method __align to align.

It's the last method in the file.

CAUTION:

The align method returns Alignment class instead of AlignedSent in earlier versions.

Title: Saving NLTK Alignments


问:
How do compilers handle interfaces under the hood?
At a high level, I understand that an interface is a way of saying

Just do this, I don't care how

In other words, it basically allows you to program declaratively instead of imperatively. You make your code more flexible when parts of it can tell other parts of it what to do, not how to do it.

I grok that concept when it comes to high-level languages like Java.

However, I am curious how compilers deal with interfaces. This may be a bigger question than I realize.

Here's my theory: It's based upon an offset in RAM.

As an example, when an object is created that implements the ICompare interface which includes the Compare method, then the compiler knows to put that Compare method at a 16 byte offset of where that object starts in RAM. In fact, every object that implements the ICompare method has its Compare method at the 16th byte. That way, when other code uses that interface to call the Compare method, the system knows to perform the instructions at the 16th byte of that object.

Is that how a compiler handles interfaces (using a standard location in every object) or does it use some kind of lookup table to know where an object's Compare method is? Or some other method entirely?

答:
For anyone else interested in this question, here is an EXCELLENT video with a visual explanation of how vtables are actually implemented in C++. The first four bytes of an object can point to a vtable that points to the correct method to use for that particular class.

Thanks @sircodesalot for the tip.


问:
Changing element position when resizing viewport with jQuery: not working on WordPress
I've done some hours of research on the topic but I haven't quite found what I was looking for. I'm building a portfolio website with WordPress, and one of the layout I had in mind was something like this,
portfolio layout
which I successfully made using overlapping rows in Bootstrap.
I would like the columns to stack when the viewport is < 768px so that the rows are not blocking each other, so I wrote the script using jQuery.

```<code>jQuery(document).ready(function(){
    $(window).resize(function(){
        var width = $(window).width();
        if (width < 768) {
            $(".col-sm-4.col-sm-offset-8.higher").removeClass("higher");
        }
        else {
            $(".col-sm-4.col-sm-offset-8").addClass("higher");
        }
    });
});
</code>```

I've tested it on CodePen and it seems to be working fine: demo but I am having a hard time making it work in WordPress. Any insight would be appreciated!

答:
I'm not completely sure how you'd like the page to behave, but I believe I achieved the column stacking behavior in the Code Pen I forked from yours.

I achieved this with Bootstrap CSS only, no JS required.

```<code><div class="row">
    <div class="col-sm-4">
        <p class="p1">R1C1</p>
    </div>

    <div class="col-sm-4">
        <p class="p1">R2C2</p>
    </div>

    <div class="col-sm-4">
        <p class="p1">R3C3</p>
    </div>
</div>
</code>```

The Bootstrap grid is laid out in 12 columns, so the number of columns used in each section should typically total 12. I separated each of the three sections into equal size sections designated by col-sm-4. Bootstrap manages the resizing event that occurs at 768 pixels.

Body:
I've done some hours of research on the topic but I haven't quite found what I was looking for. I'm building a portfolio website with WordPress, and one of the layout I had in mind was something like this,
portfolio layout
which I successfully made using overlapping rows in Bootstrap.
I would like the columns to stack when the viewport is < 768px so that the rows are not blocking each other, so I wrote the script using jQuery.

jQuery(document).ready(function(){
    $(window).resize(function(){
        var width = $(window).width();
        if (width < 768) {
            $(".col-sm-4.col-sm-offset-8.higher").removeClass("higher");
        }
        else {
            $(".col-sm-4.col-sm-offset-8").addClass("higher");
        }
    });
});

I've tested it on CodePen and it seems to be working fine: demo but I am having a hard time making it work in WordPress. Any insight would be appreciated!

Body:
I'm not completely sure how you'd like the page to behave, but I believe I achieved the column stacking behavior in the Code Pen I forked from yours.

I achieved this with Bootstrap CSS only, no JS required.

<div class="row">
    <div class="col-sm-4">
        <p class="p1">R1C1</p>
    </div>

    <div class="col-sm-4">
        <p class="p1">R2C2</p>
    </div>

    <div class="col-sm-4">
        <p class="p1">R3C3</p>
    </div>
</div>

The Bootstrap grid is laid out in 12 columns, so the number of columns used in each section should typically total 12. I separated each of the three sections into equal size sections designated by col-sm-4. Bootstrap manages the resizing event that occurs at 768 pixels.


问:
401 Unauthorized error while logging in Manager-App of Tomcat
I am trying to log in to the Manager App in Tomcat 7.0.22 for Mac OS X 10.7. Here is the error I am getting: http://f.cl.ly/items/421q1K3f1i0X1H1M181v/so.tiff

```<code>401 Unauthorized

You are not authorized to view this page. If you have not changed any configuration files, please examine the file conf/tomcat-users.xml in your installation. That file must contain the credentials to let you use this webapp.

For example, to add the manager-gui role to a user named tomcat with a password of s3cret, add the following to the config file listed above.

<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
</code>```

I have added this in my tomcat-users.xml, still its not taking the same username/password.

```<code><tomcat-users>
<role rolename="manager-gui"/>
<user name="tomcat" password="s3cret" roles="standard,manager-gui"/>
</tomcat-users>
</code>```

答:
In my case, I had multiple <Engine><Host>...</Host></Engine> sections in my context.xml and I had to copy and paste the <Realm className="org.apache.catalina.realm.LockOutRealm">...</Realm> into each <Engine>...</Engine> section because I had the manager app deployed in each one of these hosts that were part of a separate Engine.

The answer from @swapnil chaudhari about the IP address restriction in the app's META-INF/context.xml is also helpful, however I found it more beneficial to override the Context in my server's server.xml.

In the end, I have something like this for each one of my Engines:

```<code>    <Engine name="CatalinaMyUniqueEngine"
            defaultHost="MyUniqueHost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
      <Host name="MyUniqueHost"
            appBase="/opt/tomcat/webapps/MyUniqueHost"
            unpackWARs="true" autoDeploy="true">
        <Context path="/manager" privileged="true" antiResourceLocking="false"
                 docBase="manager">
          <!-- Wider allowance than the default.
               Or you can remove to allow all IPs, which probably isn't
               a good idea. -->
          <Valve className="org.apache.catalina.valves.RemoteAddrValve"
                 allow="127\.0\.0\.1|10\.244\.\d+.\d+" />
      </Host>
    </Engine>
</code>```

docBase is relative to appBase.  In /opt/tomcat/webapps/MyUniqueHost, I have a symbolic link to the manager application installed by my system's package manager (Debian-based), which placed it at /usr/share/tomcat8-admin/manager.  These symbolic links allow me to use the manager app in all my Hosts without copying the manager application.

Body:
I am trying to log in to the Manager App in Tomcat 7.0.22 for Mac OS X 10.7. Here is the error I am getting: http://f.cl.ly/items/421q1K3f1i0X1H1M181v/so.tiff

401 Unauthorized

You are not authorized to view this page. If you have not changed any configuration files, please examine the file conf/tomcat-users.xml in your installation. That file must contain the credentials to let you use this webapp.

For example, to add the manager-gui role to a user named tomcat with a password of s3cret, add the following to the config file listed above.

<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>

I have added this in my tomcat-users.xml, still its not taking the same username/password.

<tomcat-users>
<role rolename="manager-gui"/>
<user name="tomcat" password="s3cret" roles="standard,manager-gui"/>
</tomcat-users>

Body:
In my case, I had multiple <Engine><Host>...</Host></Engine> sections in my context.xml and I had to copy and paste the <Realm className="org.apache.catalina.realm.LockOutRealm">...</Realm> into each <Engine>...</Engine> section because I had the manager app deployed in each one of these hosts that were part of a separate Engine.

The answer from @swapnil chaudhari about the IP address restriction in the app's META-INF/context.xml is also helpful, however I found it more beneficial to override the Context in my server's server.xml.

In the end, I have something like this for each one of my Engines:

    <Engine name="CatalinaMyUniqueEngine"
            defaultHost="MyUniqueHost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
      <Host name="MyUniqueHost"
            appBase="/opt/tomcat/webapps/MyUniqueHost"
            unpackWARs="true" autoDeploy="true">
        <Context path="/manager" privileged="true" antiResourceLocking="false"
                 docBase="manager">
          <!-- Wider allowance than the default.
               Or you can remove to allow all IPs, which probably isn't
               a good idea. -->
          <Valve className="org.apache.catalina.valves.RemoteAddrValve"
                 allow="127\.0\.0\.1|10\.244\.\d+.\d+" />
      </Host>
    </Engine>

docBase is relative to appBase.  In /opt/tomcat/webapps/MyUniqueHost, I have a symbolic link to the manager application installed by my system's package manager (Debian-based), which placed it at /usr/share/tomcat8-admin/manager.  These symbolic links allow me to use the manager app in all my Hosts without copying the manager application.


问:
Enabling HTTPS on an express server
I'm trying to configure my express server to use HTTPS but I am running into some issues. I followed the documentation to setup my HTTPS server but I am still encountering some errors.

Here's my app.js

var express = require('express');
var app = express();
var server = require('https').createServer(options, app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var fs = require('fs');

var options = {
  key: fs.readFileSync('/test/key.pem'),
  cert: fs.readFileSync('/test/cert.pem')
};

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});```

When starting my server I encounter

    https.js:32
      if (process.features.tls_npn && !opts.NPNProtocols) {
                                           ^
    TypeError: Cannot read property 'NPNProtocols' of undefined
        at new Server (https.js:32:40)
        at Object.exports.createServer (https.js:56:10)

So, I tried to define NPNProtocols within options, but that did not work. Anyone have any pointers here?
Thank you.

答:
IMO, the issue is not with the extension of the keys, rather the ssl configuration used. Use https node module with correct ssl options for ca, cert, and key to enable https with express.

```<code>// server/index.js
const express = require('express');
const fse = require('fs-extra');
const helmet = require('helmet');
const https = require('https');
const path = require('path');

// path to cert files
const paths = {
  certFile: '/path/to/cert.pem',
  chainFile: '/path/to/fullchain.pem',
  privateFile: '/path/to/privkey.pem',
};

/* Express implementation (ignore) */
const app = express();
app.use(helmet());
app.use(express.static(path.join(__dirname, '..')));
app.get('/', (request, response) => {
  response.sendFile(path.join('index.html'));
});

// setup https
const setupHttps = () => {
  const promises = [
    fse.readFile(paths.chainFile),
    fse.readFile(paths.privateFile),
    fse.readFile(paths.certFile),
  ];

  return Promise
    .all(promises)
    .then(data => {
      const [ chainData, privateData, certData ] = data;
      const options = {
        ca: chainData.toString('utf-8'),
        cert: certData.toString('utf-8'),
        key: privateData.toString('utf-8'),
      };
      return https.createServer(
        options,
        app
      ).listen(443);
    })
    .catch(err => console.log(err));
};

return setupHttps();
</code>```

EDIT: I used helmetjs for better security with http headers.

Title: Enabling HTTPS on an express server

Body:
I'm trying to configure my express server to use HTTPS but I am running into some issues. I followed the documentation to setup my HTTPS server but I am still encountering some errors.

Here's my app.js

var express = require('express');
var app = express();
var server = require('https').createServer(options, app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var fs = require('fs');

var options = {
  key: fs.readFileSync('/test/key.pem'),
  cert: fs.readFileSync('/test/cert.pem')
};

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

When starting my server I encounter

    https.js:32
      if (process.features.tls_npn && !opts.NPNProtocols) {
                                           ^
    TypeError: Cannot read property 'NPNProtocols' of undefined
        at new Server (https.js:32:40)
        at Object.exports.createServer (https.js:56:10)

So, I tried to define NPNProtocols within options, but that did not work. Anyone have any pointers here?
Thank you.

Body:
IMO, the issue is not with the extension of the keys, rather the ssl configuration used. Use https node module with correct ssl options for ca, cert, and key to enable https with express.

// server/index.js
const express = require('express');
const fse = require('fs-extra');
const helmet = require('helmet');
const https = require('https');
const path = require('path');

// path to cert files
const paths = {
  certFile: '/path/to/cert.pem',
  chainFile: '/path/to/fullchain.pem',
  privateFile: '/path/to/privkey.pem',
};

/* Express implementation (ignore) */
const app = express();
app.use(helmet());
app.use(express.static(path.join(__dirname, '..')));
app.get('/', (request, response) => {
  response.sendFile(path.join('index.html'));
});

// setup https
const setupHttps = () => {
  const promises = [
    fse.readFile(paths.chainFile),
    fse.readFile(paths.privateFile),
    fse.readFile(paths.certFile),
  ];

  return Promise
    .all(promises)
    .then(data => {
      const [ chainData, privateData, certData ] = data;
      const options = {
        ca: chainData.toString('utf-8'),
        cert: certData.toString('utf-8'),
        key: privateData.toString('utf-8'),
      };
      return https.createServer(
        options,
        app
      ).listen(443);
    })
    .catch(err => console.log(err));
};

return setupHttps();

EDIT: I used helmetjs for better security with http headers.


问:
How to use the Developer Tools in IE 7?
could any one tell me how to use the Developer Tools in IE 7?I am using the .Net programming language .Wanna to debug the javascript and jquery.</p>

答:
If you want to debug your JS code using IE(x) native developer tools you first have to (as sreddhar said) put a "debugger" inside of it.

Then, you obv have to open the dev tools (F12), and under the tab "Script" just press "Start Debugging". It refreshes your page and whenever it finds "debugger" inside your code it stops in that particular point, then you can decide to put some breakpoints, view the call stack, watch and evaluate variables and so on...

Title: How to use the Developer Tools in IE 7?


问:
JavaScript Object with children need to convert into SQL like Array (nosql data format to sql)
I have array of data and some of the properties are arrays. I wan to flatten that array so none of the properties are array as explained below.

Input

```<code>[{
    "name": "James",
    "education": [
        { "year": 2014, "degree": "MS" },
        { "year": 2012, "degree": "BS" }]
}, {
    "name": "Bond",
    "education": [
        { "year": 2011, "degree": "MS" },
        { "year": 2009, "degree": "BS" }]
}]
</code>```

Output

```<code>[
    {"name":"James","education_year":2014,"education_degree":"MS"},
    {"name":"James","education_year":2012,"education_degree":"BS"},
    {"name":"Bond","education_year":2011,"education_degree":"MS"},
    {"name":"Bond","education_year":2009,"education_degree":"BS"}
]
</code>```

https://sqlify.io/convert does that when i ask it to convert to CSV format. But i cant use that service.

Is there any way so i can produce desired output,

答:
Iterate with Array#map, and then map education to new objects in the requested format. Flatten the results using spread and Array#concat:

create the object with Object#assign. Inside the assign, Array#map each property to the required format, and spread:

const data = [{
    "name": "James",
    "education": [
        { "year": 2014, "degree": "MS" },
        { "year": 2012, "degree": "BS" }]
}, {
    "name": "Bond",
    "education": [
        { "year": 2011, "degree": "MS" },
        { "year": 2009, "degree": "BS" }]
}];

const result = [].concat(...data.map(({ name, education }) =>
  education.map(({ year, degree }) => ({ name, education_year: year, education_degree: degree })
)));

console.log(result);```
</div>
</div>
</p>

<p>A generic version that can handle multiple sub arrays in objects:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [{"name":"James","lname":"Parker","education":[{"year":2014,"degree":"MS"},{"year":2012,"degree":"BS"}],"job":[{"year":2017,"title":"senior developer"},{"year":2017,"title":"developer"},{"year":2014,"title":"junior"}]},{"name":"Bond","lname":"Peter","education":[{"year":2011,"degree":"MS"},{"year":2009,"degree":"BS"}],"job":[{"year":2014,"title":"ninja"},{"year":2012,"title":"rogue"}]}];

const createKey = (prefix, key) => `${prefix}_${key}`;

const result = [].concat(...data.map((el) =>
 Object.entries(el)
    .map(([k, v]) => Array.isArray(v) ?
      v.map((o) => Object.entries(o).reduce((r, [key, val]) => Object.assign(r, { [createKey(k, key)]: val }), {}))
      :
      { [k]: v }
    )
   .reduce((r, s) =>
     Array.isArray(s) ?
       [].concat(...r.map((o) => s.map((q) => Object.assign({}, o, q))))
        :
        r.map((o) => Object.assign({}, o, s))
      , [{}])
));

console.log(result);</code>```

Body:
I have array of data and some of the properties are arrays. I wan to flatten that array so none of the properties are array as explained below.

Input

[{
    "name": "James",
    "education": [
        { "year": 2014, "degree": "MS" },
        { "year": 2012, "degree": "BS" }]
}, {
    "name": "Bond",
    "education": [
        { "year": 2011, "degree": "MS" },
        { "year": 2009, "degree": "BS" }]
}]

Output

[
    {"name":"James","education_year":2014,"education_degree":"MS"},
    {"name":"James","education_year":2012,"education_degree":"BS"},
    {"name":"Bond","education_year":2011,"education_degree":"MS"},
    {"name":"Bond","education_year":2009,"education_degree":"BS"}
]

https://sqlify.io/convert does that when i ask it to convert to CSV format. But i cant use that service.

Is there any way so i can produce desired output,

Body:
Iterate with Array#map, and then map education to new objects in the requested format. Flatten the results using spread and Array#concat:

create the object with Object#assign. Inside the assign, Array#map each property to the required format, and spread:

const data = [{
    "name": "James",
    "education": [
        { "year": 2014, "degree": "MS" },
        { "year": 2012, "degree": "BS" }]
}, {
    "name": "Bond",
    "education": [
        { "year": 2011, "degree": "MS" },
        { "year": 2009, "degree": "BS" }]
}];

const result = [].concat(...data.map(({ name, education }) =>
  education.map(({ year, degree }) => ({ name, education_year: year, education_degree: degree })
)));

console.log(result);

A generic version that can handle multiple sub arrays in objects:

const data = [{"name":"James","lname":"Parker","education":[{"year":2014,"degree":"MS"},{"year":2012,"degree":"BS"}],"job":[{"year":2017,"title":"senior developer"},{"year":2017,"title":"developer"},{"year":2014,"title":"junior"}]},{"name":"Bond","lname":"Peter","education":[{"year":2011,"degree":"MS"},{"year":2009,"degree":"BS"}],"job":[{"year":2014,"title":"ninja"},{"year":2012,"title":"rogue"}]}];

const createKey = (prefix, key) => `${prefix}_${key}`;

const result = [].concat(...data.map((el) =>
 Object.entries(el)
    .map(([k, v]) => Array.isArray(v) ?
      v.map((o) => Object.entries(o).reduce((r, [key, val]) => Object.assign(r, { [createKey(k, key)]: val }), {}))
      :
      { [k]: v }
    )
   .reduce((r, s) =>
     Array.isArray(s) ?
       [].concat(...r.map((o) => s.map((q) => Object.assign({}, o, q))))
        :
        r.map((o) => Object.assign({}, o, s))
      , [{}])
));

console.log(result);


问:
Iterating through JSON objects even if key is missing
I have a JSON have the following data:

```<code>        {
       "results":[
          {
             "name":"Sydney Showboats",
             "photos":[
                {
                   "photo_reference":"Pic062"
                }
             ]
          },
          {
             "name":"Blue Line Cruises"
          },
          {
             "name":"Rhythmboat Cruises",
             "photos":[
                {
                   "photo_reference":"Pic678"
                }
             ]
          },
          {
             "name":"Flying Fish Restaurant & Bar",
             "photos":[
                {
                   "photo_reference":"Pic345"
                }
             ]
          }
       ],
       "status":"OK"
    }
</code>```

I'm trying to loop through this JSON to display every name value in the .name div and every image in the .photo div:

```<code>$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    $('.name').html('<p>' + data.results[index].name + '</p>');
    $('.photo').html('<img src="' + data.results[index].photos[0].photo_reference + '.jpg">');
  })
});
</code>```

It works fine with the name value and works fine with the first image too. However, since there is no "photos" property in the second object, the script stops because of an

Uncaught TypeError: Cannot read property '0' of undefined.

So is there a way to either:
Delete the objects which do not have the photos object nested inside?
Use a more complex loop to iterate through the JSON and store every image available?
Any possible solution allowing me to display every image available dynamically?

If anyone can enlighten me it would be gratefully appreciated!

答:
Any time you have an "Uncaught TypeError: Cannot read property 'prop-name' of undefined" you have a situation in which you need to add a guard against undefined:

```<code>$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    if (typeof data.results[index].photos !== "undefined" && typeof data.results[index].name !== "undefined") { // <- Here
      $('.name').html('<p>' + data.results[index].name + '</p>');
      $('.photo').html('<img src="' + data.results[index].photos[0].photo_reference + '.jpg">');
    }
  })
});
</code>```

If you need to ensure that ancestors are defined, it can be chained, like:

```<code>if (typeof a !== "undefined" && typeof a.b !== "undefined" && typeof a.b.c !== "undefined")
</code>```

and so on.

Also note Pablo's answer featuring in which is more concise.

Alternatively, you can filter your list:

const json_parsed = {
  "results": [{
      "name": "Sydney Showboats",
      "photos": [{
        "photo_reference": "Pic062"
      }]
    },
    {
      "name": "Blue Line Cruises"
    },
    {
      "name": "Rhythmboat Cruises",
      "photos": [{
        "photo_reference": "Pic678"
      }]
    },
    {
      "name": "Flying Fish Restaurant & Bar",
      "photos": [{
        "photo_reference": "Pic345"
      }]
    }
  ],
  "status": "OK"
}

clean_list = json_parsed['results'].filter(item => typeof item.photos !== "undefined" && typeof item.name !== "undefined");

console.dir(clean_list);```

Body:
I have a JSON have the following data:

        {
       "results":[
          {
             "name":"Sydney Showboats",
             "photos":[
                {
                   "photo_reference":"Pic062"
                }
             ]
          },
          {
             "name":"Blue Line Cruises"
          },
          {
             "name":"Rhythmboat Cruises",
             "photos":[
                {
                   "photo_reference":"Pic678"
                }
             ]
          },
          {
             "name":"Flying Fish Restaurant & Bar",
             "photos":[
                {
                   "photo_reference":"Pic345"
                }
             ]
          }
       ],
       "status":"OK"
    }

I'm trying to loop through this JSON to display every name value in the .name div and every image in the .photo div:

$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    $('.name').html('
' + data.results[index].name + '
');
    $('.photo').html('');
  })
});

It works fine with the name value and works fine with the first image too. However, since there is no "photos" property in the second object, the script stops because of an

Uncaught TypeError: Cannot read property '0' of undefined.

So is there a way to either:
Delete the objects which do not have the photos object nested inside?
Use a more complex loop to iterate through the JSON and store every image available?
Any possible solution allowing me to display every image available dynamically?

If anyone can enlighten me it would be gratefully appreciated!

Body:
Any time you have an "Uncaught TypeError: Cannot read property 'prop-name' of undefined" you have a situation in which you need to add a guard against undefined:

$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    if (typeof data.results[index].photos !== "undefined" && typeof data.results[index].name !== "undefined") { // <- Here
      $('.name').html('<p>' + data.results[index].name + '</p>');
      $('.photo').html('<img src="' + data.results[index].photos[0].photo_reference + '.jpg">');
    }
  })
});

If you need to ensure that ancestors are defined, it can be chained, like:

if (typeof a !== "undefined" && typeof a.b !== "undefined" && typeof a.b.c !== "undefined")

and so on.

Also note Pablo's answer featuring in which is more concise.

Alternatively, you can filter your list:

const json_parsed = {
  "results": [{
      "name": "Sydney Showboats",
      "photos": [{
        "photo_reference": "Pic062"
      }]
    },
    {
      "name": "Blue Line Cruises"
    },
    {
      "name": "Rhythmboat Cruises",
      "photos": [{
        "photo_reference": "Pic678"
      }]
    },
    {
      "name": "Flying Fish Restaurant & Bar",
      "photos": [{
        "photo_reference": "Pic345"
      }]
    }
  ],
  "status": "OK"
}

clean_list = json_parsed['results'].filter(item => typeof item.photos !== "undefined" && typeof item.name !== "undefined");

console.dir(clean_list);


答:
All of the above and more happen:

unreferenced classes are removed

unreferenced methods and fields are removed

constants may be inlined

various operations on constants (like !, ==, +, &&, etc) may be simplified (based on some field always being null, or true, etc)

un-overridden methods may be made final...

...and final methods may be made static in certain situations (leading to smaller callsites, and no "this" reference inside that method)...

and small, frequently called static methods may be inlined

And this process repeats, with even more optimizations that I skipped, to further assist in removing code, both big and small. At the end, all classes, methods, fields, and local variables are renamed in a way to further reduce output size, including reordering methods in the output so that they are ordered by length, letting gzip more efficiently compress your content on the way to the client.

So while some aspects of your code could be reverse engineered (just like any machine code could be reverse engineered), code which isn't referenced won't be available, and code which is may not even be readable.

Title: Does GWT remove unused classes during compilation?


问:
BigQueryIO.Write in dataflow 2.X
Below code worked for Dataflow 1.9 sdk, migrating to 2.X

```<code>PCollection<TableRow> tableRow = ...

tableRow.apply(BigQueryIO.Write()
                .to(String.format("%1$s:%2$s.%3$s",projectId, bqDataSet, bqTable))
                .withSchema(schema)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
</code>```

I get

```<code>The method apply(PTransform<? super PCollection<TableRow>,OutputT>) in the type PCollection<TableRow> is not applicable for the arguments (BigQueryIO.Write<Object>)
</code>```

Release notes are not much of a help here and documentation on 2.X is non existant redirects to beam API page.

答:
You can try providing TableRow type explicitly (BigQuery.<TableRow>write()...) or use BigQuery.writeTableRows() as suggested above.

Looks like the interface was made generic in 2.x. Earlier version had TableRow hard coded.

Title: BigQueryIO.Write in dataflow 2.X

Body:
Below code worked for Dataflow 1.9 sdk, migrating to 2.X

PCollection<TableRow> tableRow = ...

tableRow.apply(BigQueryIO.Write()
                .to(String.format("%1$s:%2$s.%3$s",projectId, bqDataSet, bqTable))
                .withSchema(schema)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));

I get

The method apply(PTransform<? super PCollection<TableRow>,OutputT>) in the type PCollection<TableRow> is not applicable for the arguments (BigQueryIO.Write<Object>)

Release notes are not much of a help here and documentation on 2.X is non existant redirects to beam API page.


问:
json object from javascript nested array
I'm using a nested array with the following structure:

```<code>arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
</code>```

now I'm trying to get a nested Json Object from this array

```<code>arr{
 {
 id: example0,
 name: name00,
 },
{
 id: example1,
 name: name01,
 },
{
 id: example2,
 name: name02,
 }
}
</code>```

I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.

Thank you!

答:
You need to make a valid array:

```<code>arr = [
 {
 id: 'example0',
 name: 'name00',
 },
{
 id: 'example1',
 name: 'name01',
 },
{
 id: 'example2',
 name: 'name02',
 }
];

console.log(JSON.stringify(arr));
</code>```

Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

Body:
I'm using a nested array with the following structure:

arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";

now I'm trying to get a nested Json Object from this array

arr{
 {
 id: example0,
 name: name00,
 },
{
 id: example1,
 name: name01,
 },
{
 id: example2,
 name: name02,
 }
}

I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.

Thank you!

Body:
You need to make a valid array:

arr = [
 {
 id: 'example0',
 name: 'name00',
 },
{
 id: 'example1',
 name: 'name01',
 },
{
 id: 'example2',
 name: 'name02',
 }
];

console.log(JSON.stringify(arr));

Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.


问:
What is your method of "folksonomy" tagging for files on your local machine?
Way back in the days when "delicious" was just "del.icio.us", I had assumed that everyone had finally caught on that Ontology is overrated.

So why am I still having to roll my own tagging system using sqlite and a bunch of ruby scripts in order to address this obvious deficiency on my own local machine? I can tag on-line web links, blog posts, questions on stackoverflow.com, and all kinds of web-centric miscellany, but this very basic concept still seems to be missing (or hideously crippled) in the few operating systems I get to use. Perhaps I am just using the wrong OSs?

From what I've seen out there, the pickins' seem pretty slim.

What do you use?

答:
http://pages.stern.nyu.edu/~marriaga/software/oyepa/

ugly, but it works....also, there is find;)

OwnerDisplayName: dreftymac

OwnerDisplayName: Kim


问:
event-drive TLS server
I'm working on a server-side software that receives requests from clients via TLS (over TCP). For better performance and user experience, I'd like to avoid a full handshake for every request. Ideally, the client can just establish a TLS session with the server for hours, although most of the time the session might be idle. At the same time, high throughput is also required.

One easy way to do it is to dedicate a thread for each session and use a big thread pool to boost throughput. But the performance overhead of this method could be huge, if I want, say, 10s thousands of concurrent sessions.

The requirement of high throughput leads to me the event-driven model. The idea is when the connection is idle (namely no IO event on the underlying socket), the TLS server can switch context to serve other connections. One of the challenges is to sort of freeze the entire TLS session context while the socket is idle and retrieve it when the socket becomes readable/writable.

I'm wondering if there is support already in TLS for this kind of feature? Both cache and ticket seem relevant. Also, I'm wondering if people have implemented this idea.

答:
You are talking about SSL Session resumption, and it is already implemented in both OpenSSL and JSSE, and no doubt every other SSL API you would be using. SSL sessions already  survive connections. So there is nothing for you to do to get this.

The part about 'freezing the SSL session context' is completely pointless.

Title: event-drive TLS server