问:
How to create a sticky footer that plays well with Bootstrap 3
With or without a top nav, it is very common for sites to have a sticky footer.  Bootstrap has a facility to easily create fixed footers, but no such facility for creating sticky footers - there is a big difference.

Googling this question will reveal that hundreds if not thousands of developers have the same question but with no good answer.

Ironically, the Bootstrap documentation page itself has a sticky footer alongside bootstrap styling and a fixed top navbar.  It's all custom css though, and not part of the framework.  So an obvious route is to take and refactor their custom styling, since it obviously plays well within the Bootstrap framework, but that seems more painful than it ought to be.

See this plunkr for an example page with a Bootstrap top navbar, and an undesirable, non-sticky footer.

Problem:

(Thanks Softlayer - for the graphics)

Desired Solution:

Of course the footer should be responsive and cross-browser friendly as well...

答:
In case your html has the (rough) structure:

```<code><div class="wrapper">
   <div>....</div>
   ...
   <div>....</div>
</div>
<div class="footer">
   ...
</div>
</code>```

then the simplest css that fixes footer to the bottom of your screen is

```<code>html, body {
    height: 100%;
}
.wrapper {
  min-height: calc(100vh - 80px);
}
.footer {
   height: 80px;
}
</code>```

... where the height of the footer is 80px. calc calculates the height of the wrapper  to be equal to the window's height minus the height of the footer (80px) which is out of the .wrapper

Body:
In case your html has the (rough) structure:

<div class="wrapper">
   <div>....</div>
   ...
   <div>....</div>
</div>
<div class="footer">
   ...
</div>

then the simplest css that fixes footer to the bottom of your screen is

html, body {
    height: 100%;
}
.wrapper {
  min-height: calc(100vh - 80px);
}
.footer {
   height: 80px;
}

... where the height of the footer is 80px. calc calculates the height of the wrapper  to be equal to the window's height minus the height of the footer (80px) which is out of the .wrapper


来源: stackexchange

问:
Error: Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" (ionic 2 and firebase)
```<code>saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object('request/${auth.uid}').set(this.request)
    .then();
  })
</code>```

After executing this method, an error: Firebase.child failed: First argument was an invalid path: "request/${auth.uid}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" is being shown. Tried removing $ but that doesn't work. Pretty sure i am not passing in empty strings too.

答:
If you are going to use string interpolation, you need to use back ticks (`), and not single quotes ('), to wrap a string. See below.

```<code>saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object(`request/${auth.uid}`).set(this.request)
    .then();
  })
</code>```

Easy one to forget! :)

ContentLicense: CC BY-SA 3.0

Body:
saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object('request/${auth.uid}').set(this.request)
    .then();
  })

After executing this method, an error: Firebase.child failed: First argument was an invalid path: "request/${auth.uid}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" is being shown. Tried removing $ but that doesn't work. Pretty sure i am not passing in empty strings too.

Body:
If you are going to use string interpolation, you need to use back ticks (`), and not single quotes ('), to wrap a string. See below.

saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object(`request/${auth.uid}`).set(this.request)
    .then();
  })

Easy one to forget! :)


问:
PHP Slimframework CORS
I'm in a bit trouble with this CORS thing. Angular 4 is running on localhost:4200, while Slimframework is running on localhost:8080.

My front-end HTTP request:

```<code>....
createPartner(partner: Partner): Observable<Partner> {
    let headers = new Headers({ 'Content-Type' : 'application/json'});
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.regUrl, partner, options)
           .map((res: Response) => {
              return res.json();
           })
           .catch(this.handleError);
  }
....
</code>```

My middleware:

```<code>....
$app->add(function($request, $response, $next) {
$route = $request->getAttribute("route");

$methods = [];

if (!empty($route)) {
    $pattern = $route->getPattern();

    foreach ($this->router->getRoutes() as $route) {
        if ($pattern === $route->getPattern()) {
            $methods = array_merge_recursive($methods, $route->getMethods());
        }
    }
} else {
    $methods[] = $request->getMethod();
}

$response = $next($request, $response);

return $response->withHeader("Access-Control-Allow-Methods", implode(",", $methods));
});
</code>```

I added "determineRouteBeforeAppMiddleware" => true, to my settings array.

The browser's (chrome) console says:

XMLHttpRequest cannot load http://lvh.me/api/partner. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

What did I do wrong, guys? :/

Edit:

Forgot the 8080 port of the backend URI, now that I added, the new error is:

```<code>OPTIONS http://lvh.me:8080/api/partner net::ERR_CONNECTION_REFUSED
</code>```

答: Resolved via skype by adding Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers to Slim framework middlware.

Title: PHP Slimframework CORS

Body:
I'm in a bit trouble with this CORS thing. Angular 4 is running on localhost:4200, while Slimframework is running on localhost:8080.

My front-end HTTP request:

....
createPartner(partner: Partner): Observable<Partner> {
    let headers = new Headers({ 'Content-Type' : 'application/json'});
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.regUrl, partner, options)
           .map((res: Response) => {
              return res.json();
           })
           .catch(this.handleError);
  }
....

My middleware:

....
$app->add(function($request, $response, $next) {
$route = $request->getAttribute("route");

$methods = [];

if (!empty($route)) {
    $pattern = $route->getPattern();

    foreach ($this->router->getRoutes() as $route) {
        if ($pattern === $route->getPattern()) {
            $methods = array_merge_recursive($methods, $route->getMethods());
        }
    }
} else {
    $methods[] = $request->getMethod();
}

$response = $next($request, $response);

return $response->withHeader("Access-Control-Allow-Methods", implode(",", $methods));
});

I added "determineRouteBeforeAppMiddleware" => true, to my settings array.

The browser's (chrome) console says:

XMLHttpRequest cannot load http://lvh.me/api/partner. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

What did I do wrong, guys? :/

Edit:

Forgot the 8080 port of the backend URI, now that I added, the new error is:

OPTIONS http://lvh.me:8080/api/partner net::ERR_CONNECTION_REFUSED


问:
Why can't I access a variable declared in derived class with the object of base class
Good Evening everyone

I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class  is a derived class from Shape. I have declared a public variable  in Rectangle called num and initialized a value to it.

In the main class I have created an object of type class in following manner.

```<code>Shape s = new Rectangle();
</code>```

Now when I am trying to access num variable of rectangle class it gives error saying

“ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error
  CS1061: 'Shape' does not contain a definition for 'num' and no
  extension method 'num' accepting a first argument of type 'Shape'
  could be found (are you missing a using directive or an assembly
  reference?) (CS1061) (Practice)”

My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.

Pls find the attached screenshot.

答:
A object object of type Shape can access only members defined in Shape class. You have two options:

Define num in Shape class itself and it will be available to Rectangle class.

Cast object s to Rectangle  type to be able to use it.

The principle wise, I prefer option#1. One should define properties and methods to be used by both base and sub-class in base class.

Body:
Good Evening everyone

I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class  is a derived class from Shape. I have declared a public variable  in Rectangle called num and initialized a value to it.

In the main class I have created an object of type class in following manner.

Shape s = new Rectangle();

Now when I am trying to access num variable of rectangle class it gives error saying

“ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error
  CS1061: 'Shape' does not contain a definition for 'num' and no
  extension method 'num' accepting a first argument of type 'Shape'
  could be found (are you missing a using directive or an assembly
  reference?) (CS1061) (Practice)”

My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.

Pls find the attached screenshot.


问:
Any benefit to starting an Activity via an intent one way versus another?
I know of two ways to start an Activity with an intent. Let's say I'm in Activity A and I want to start Activity B. I could do the following.

1)
In Activity B I have some static method:

```<code>public static Intent newIntent(Context packageContext){
    Intent intent = new Intent(packageContext, ActivityB.class);
    return intent;
}
</code>```

And from Activity A I can call:

```<code>startActivity(ActivityB.newIntent(this));
</code>```

2) The other method is the one I see more often:

From Activity A I do the following

```<code>Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
</code>```

Are there any benefits or drawbacks to using one versus the other? I think method 1 is a bit cleaner because it keeps the intent information in the class that will actually be started with the intent.

答:
case first

Pros :

This follows the DRY principle mean don't repeat your self

Cons :

It is only limited to one class i.e ActivityB.class

Unclear naming convention for a Utility class

Note flexible to add extra properties unless method definition is modified to accept some map or something

Second case

Pros:

More flexible as any activity can be started

Any attribute can be added to intent object i.g putExtra and so many other

Cons :

Does not follow the DRY principle

Inefficient when duplicated many times

Improvements

Give your method proper naming

Can be overloaded to accept a map for key-value

Apply Class<?> to accept any class as parameter

Body:
I know of two ways to start an Activity with an intent. Let's say I'm in Activity A and I want to start Activity B. I could do the following.

1)
In Activity B I have some static method:

public static Intent newIntent(Context packageContext){
    Intent intent = new Intent(packageContext, ActivityB.class);
    return intent;
}

And from Activity A I can call:

startActivity(ActivityB.newIntent(this));

2) The other method is the one I see more often:

From Activity A I do the following

Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);

Are there any benefits or drawbacks to using one versus the other? I think method 1 is a bit cleaner because it keeps the intent information in the class that will actually be started with the intent.


问:
Unable to launch audio link from Android app
I'm trying to launch an intent from my application that will play audio from a streaming server.  I've got a url for that stream and I'm using bit.ly to simplify the url to launch (I've tried without bit.ly and have the same results)

```<code>intent = new Intent( Intent.ACTION_VIEW, Uri.parse( "http://bit.ly/gKltQE" ) );
intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); // i tried with and without this, no luck
startActivity( intent );
</code>```

The browser starts, loads up the bit.ly link, redirects to the audio link then closes and returns to my app

```<code>12-15 14:27:58.559  1259  8370 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://bit.ly/gKltQE flg=0x10000000 cmp=com.android.browser/.BrowserActivity (has extras) }
12-15 14:14:23.903  1259  1383 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 cmp=com.android.browser/.BrowserActivity }
12-15 14:14:24.387  8848  8848 D webviewglue: nativeDestroy view: 0x3bb018
12-15 14:14:24.387  1259  1600 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 typ=audio/mpeg cmp=com.android.music/.StreamStarter }
12-15 14:14:24.387  1259  1929 I ActivityManager: moveTaskToBack: 12
</code>```

When I launch the same bit.ly link in the browser manually, it works fine (launches the audio streaming app):

```<code>12-15 14:26:21.403  8848  8848 D SearchDialog: launching Intent { act=android.intent.action.VIEW dat=http://bit.ly/gKltQE flg=0x10000000 cmp=com.android.browser/.BrowserActivity (has extras) }
12-15 14:26:21.411  8848  8848 I SearchDialog: Starting (as ourselves) http://bit.ly/gKltQE#Intent;action=android.intent.action.VIEW;launchFlags=0x10000000;component=com.android.browser/.BrowserActivity;S.query=http%3A%2F%2Fbit.ly%2FgKltQE;S.user_query=bit;end
12-15 14:26:21.411  1259  1259 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://bit.ly/gKltQE flg=0x10000000 cmp=com.android.browser/.BrowserActivity (has extras) }12-15 14:26:21.879  1259  1267 V DeviceStorageMonitorService: freeMemory=6210887680
12-15 14:26:21.879  1259  1267 V DeviceStorageMonitorService: Threshold Percentage=10
12-15 14:26:21.879  1259  1267 V DeviceStorageMonitorService: mTotalMemory = 70264913
12-15 14:26:21.879  1259  1267 I DeviceStorageMonitorService: Posting Message again
12-15 14:26:21.997  8848  8864 D dalvikvm: GC_FOR_MALLOC freed 14790 objects / 467656 bytes in 85ms
12-15 14:26:22.192  1259  1436 D dalvikvm: GC_FOR_MALLOC freed 47823 objects / 2142584 bytes in 154ms
12-15 14:26:22.208  1259  1263 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 cmp=com.android.browser/.BrowserActivity }
12-15 14:26:22.676  1259  1259 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 typ=audio/mpeg cmp=com.android.music/.StreamStarter }
12-15 14:26:22.770  1259  8719 I AudioService:   Remote Control   registerMediaButtonEventReceiver() for ComponentInfo{com.android.music/com.android.music.MediaButtonIntentReceiver}
12-15 14:26:22.801  8217  8217 V MediaPlaybackService: reloadQueue end
12-15 14:26:22.809  8217  8217 V MediaPlaybackService: onCreate end
12-15 14:26:22.809  8217  8217 V MediaPlaybackService: onStartCommand end
</code>```

I've tried fiddling with various intent.setFlags parameters but to no avail.  Maybe a permissions issue?  Or something to do with how I'm calling startActivity?

答:
Not a permissions issue, it's just the BrowserActivity ending prematurely, maybe because there's no current tab. Best thing to do is to give an extra clue to the Intent resolver that it's not actually the Browser that should be handling the data:

```<code>intent.setType("audio/mpeg");
</code>```

No other flags are needed... Sound Player (or your media player of choice) will now handle it.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to launch an intent from my application that will play audio from a streaming server.  I've got a url for that stream and I'm using bit.ly to simplify the url to launch (I've tried without bit.ly and have the same results)

intent = new Intent( Intent.ACTION_VIEW, Uri.parse( "http://bit.ly/gKltQE" ) );
intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); // i tried with and without this, no luck
startActivity( intent );

The browser starts, loads up the bit.ly link, redirects to the audio link then closes and returns to my app

12-15 14:27:58.559  1259  8370 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://bit.ly/gKltQE flg=0x10000000 cmp=com.android.browser/.BrowserActivity (has extras) }
12-15 14:14:23.903  1259  1383 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 cmp=com.android.browser/.BrowserActivity }
12-15 14:14:24.387  8848  8848 D webviewglue: nativeDestroy view: 0x3bb018
12-15 14:14:24.387  1259  1600 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 typ=audio/mpeg cmp=com.android.music/.StreamStarter }
12-15 14:14:24.387  1259  1929 I ActivityManager: moveTaskToBack: 12

When I launch the same bit.ly link in the browser manually, it works fine (launches the audio streaming app):

12-15 14:26:21.403  8848  8848 D SearchDialog: launching Intent { act=android.intent.action.VIEW dat=http://bit.ly/gKltQE flg=0x10000000 cmp=com.android.browser/.BrowserActivity (has extras) }
12-15 14:26:21.411  8848  8848 I SearchDialog: Starting (as ourselves) http://bit.ly/gKltQE#Intent;action=android.intent.action.VIEW;launchFlags=0x10000000;component=com.android.browser/.BrowserActivity;S.query=http%3A%2F%2Fbit.ly%2FgKltQE;S.user_query=bit;end
12-15 14:26:21.411  1259  1259 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://bit.ly/gKltQE flg=0x10000000 cmp=com.android.browser/.BrowserActivity (has extras) }12-15 14:26:21.879  1259  1267 V DeviceStorageMonitorService: freeMemory=6210887680
12-15 14:26:21.879  1259  1267 V DeviceStorageMonitorService: Threshold Percentage=10
12-15 14:26:21.879  1259  1267 V DeviceStorageMonitorService: mTotalMemory = 70264913
12-15 14:26:21.879  1259  1267 I DeviceStorageMonitorService: Posting Message again
12-15 14:26:21.997  8848  8864 D dalvikvm: GC_FOR_MALLOC freed 14790 objects / 467656 bytes in 85ms
12-15 14:26:22.192  1259  1436 D dalvikvm: GC_FOR_MALLOC freed 47823 objects / 2142584 bytes in 154ms
12-15 14:26:22.208  1259  1263 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 cmp=com.android.browser/.BrowserActivity }
12-15 14:26:22.676  1259  1259 I ActivityManager: Starting activity: Intent { act=android.intent.action.VIEW dat=http://216.235.81.102:15532/play?now=65&membername;=&session=kxlu1:0&tag=live365&s=kxlu1&d=live365&r=0&app_id=live365:BROWSER%28pro%29 typ=audio/mpeg cmp=com.android.music/.StreamStarter }
12-15 14:26:22.770  1259  8719 I AudioService:   Remote Control   registerMediaButtonEventReceiver() for ComponentInfo{com.android.music/com.android.music.MediaButtonIntentReceiver}
12-15 14:26:22.801  8217  8217 V MediaPlaybackService: reloadQueue end
12-15 14:26:22.809  8217  8217 V MediaPlaybackService: onCreate end
12-15 14:26:22.809  8217  8217 V MediaPlaybackService: onStartCommand end

I've tried fiddling with various intent.setFlags parameters but to no avail.  Maybe a permissions issue?  Or something to do with how I'm calling startActivity?

Body:
Not a permissions issue, it's just the BrowserActivity ending prematurely, maybe because there's no current tab. Best thing to do is to give an extra clue to the Intent resolver that it's not actually the Browser that should be handling the data:

intent.setType("audio/mpeg");

No other flags are needed... Sound Player (or your media player of choice) will now handle it.


问:
How to show the Bluetooth Le Device connected/Disconnected status constantly
I am trying to develop an application where the user can know the status of his/her Bluetooth Le device once he/she launches the app and the connection status is updated in text view in Home Fragment.I have tried to implement it by sending Broadcast from Ble service and catching it in onResume of Home fragment and subsequently updating it in status text view. The status does gets updated but if I change the fragment and come back to the home fragment the text view to show the status gets blank although the Bluetooth Le device is connected.How can I resolve this problem so that the status shows connected all through out if the device is connected and disconnected if it is disconnected?

Any Kind of guidance will be highly appreciated.

here are the code segments I have used to implement the above

In Bleservice.java

```<code> private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;

        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;

            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");

            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:" +
                    mBluetoothGatt.discoverServices());

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

 private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}
</code>```

In HomeFragment.java

```<code>public class HomeFragment extends Fragment
{
    private BroadcastReceiver mReceiver;
@Override
protected void onResume() {
    super.onResume();
mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (Bleservice.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                updateConnectionState(R.string.connected);

            } else if (Bleservice.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                updateConnectionState(R.string.disconnected);

            }
        }

    };
    getActivity().registerReceiver(mReceiver,makeGattUpdateIntentFilter());

}

private void updateConnectionState(final int resourceId) {
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            tv_connected_disconnected.setText(resourceId);

        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    getActivity().unregisterReceiver(mReceiver);
}

 private static IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Bleservice.ACTION_GATT_CONNECTED);
    intentFilter.addAction(Bleservice.ACTION_GATT_DISCONNECTED);
    return intentFilter;

}
</code>```

答:
Connect to your BleService by bindService. Check out example with Activity and Service.

```<code>private BleService mBluetoothLeService;
private boolean isConnected;

@Override
protected void onStart() {
    super.onStart();
    Intent bindIntent = new Intent(this, BleService.class);
    startService(bindIntent);
    bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    registerServiceReceiver(); //register here your mGattCallback that get actions from BleService
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mServiceConnection);
    mBluetoothLeService = null;
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mGattUpdateReceiver);
}
</code>```

In method bindService you need to pass a ServiceConnection that manage Service Lifecycle.

```<code>// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {

        mBluetoothLeService = ((BleService.LocalBinder) service).getService();
        isConnected = (mBluetoothLeService.getConnectionState() != BleService.STATE_CONNECTED)

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};
</code>```

In Service you need to declare Binder.

```<code>private final IBinder mBinder = new LocalBinder();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
public class LocalBinder extends Binder {
    public BleService getService() {
        return BleService.this;
    }
}

public int getConnectionState() {
    return mConnectionState;
}
</code>```

So now, after binding to BleService, you can get a connection state.

Body:
I am trying to develop an application where the user can know the status of his/her Bluetooth Le device once he/she launches the app and the connection status is updated in text view in Home Fragment.I have tried to implement it by sending Broadcast from Ble service and catching it in onResume of Home fragment and subsequently updating it in status text view. The status does gets updated but if I change the fragment and come back to the home fragment the text view to show the status gets blank although the Bluetooth Le device is connected.How can I resolve this problem so that the status shows connected all through out if the device is connected and disconnected if it is disconnected?

Any Kind of guidance will be highly appreciated.

here are the code segments I have used to implement the above

In Bleservice.java

 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;

        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;

            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");

            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:" +
                    mBluetoothGatt.discoverServices());

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

 private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

In HomeFragment.java

public class HomeFragment extends Fragment
{
    private BroadcastReceiver mReceiver;
@Override
protected void onResume() {
    super.onResume();
mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (Bleservice.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                updateConnectionState(R.string.connected);

            } else if (Bleservice.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                updateConnectionState(R.string.disconnected);

            }
        }

    };
    getActivity().registerReceiver(mReceiver,makeGattUpdateIntentFilter());

}

private void updateConnectionState(final int resourceId) {
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            tv_connected_disconnected.setText(resourceId);

        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    getActivity().unregisterReceiver(mReceiver);
}

 private static IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Bleservice.ACTION_GATT_CONNECTED);
    intentFilter.addAction(Bleservice.ACTION_GATT_DISCONNECTED);
    return intentFilter;

}

Body:
Connect to your BleService by bindService. Check out example with Activity and Service.

private BleService mBluetoothLeService;
private boolean isConnected;

@Override
protected void onStart() {
    super.onStart();
    Intent bindIntent = new Intent(this, BleService.class);
    startService(bindIntent);
    bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    registerServiceReceiver(); //register here your mGattCallback that get actions from BleService
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mServiceConnection);
    mBluetoothLeService = null;
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mGattUpdateReceiver);
}

In method bindService you need to pass a ServiceConnection that manage Service Lifecycle.

// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {

        mBluetoothLeService = ((BleService.LocalBinder) service).getService();
        isConnected = (mBluetoothLeService.getConnectionState() != BleService.STATE_CONNECTED)

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};

In Service you need to declare Binder.

private final IBinder mBinder = new LocalBinder();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
public class LocalBinder extends Binder {
    public BleService getService() {
        return BleService.this;
    }
}

public int getConnectionState() {
    return mConnectionState;
}

So now, after binding to BleService, you can get a connection state.


问:
using std::conditional to choose member type based on template parameter
Here is my program that attempts to use std::conditional to set the type of a member variable based on the value of an integer template parameter.

```<code>#include <stdio.h>
#include <type_traits>
using namespace std;

class cool{
public:
  cool(){ printf("Cool!\n");  }
};

class notcool{
public:
  notcool(){ printf("Not cool!\n");  }
};

template<int N>
class myclass{
public:
  typedef std::conditional<N==5,cool,notcool> thetype;
  thetype theinst;
};

int main(){
  printf("Testing\n");
  myclass<5> myc5;
  myclass<6> myc6;
  printf("Done testing\n");
  return 0;
}
</code>```

I would expect my program to give the following output:

Testing

Cool!

Not cool!

Done testing

Instead, the output is

Testing

Done testing

My compiler is GCC 4.9, and the way I compiled this program was using the command g++ test -std=c++11 -o test

Can anyone tell me why the program does not give the output I expect?

答:
```<code>typedef typename std::conditional<N==5,cool,notcool>::type thetype;
//      ^^^^^^^^                                    ^^^^^^
</code>```

Body:
Here is my program that attempts to use std::conditional to set the type of a member variable based on the value of an integer template parameter.

#include <stdio.h>
#include <type_traits>
using namespace std;

class cool{
public:
  cool(){ printf("Cool!\n");  }
};

class notcool{
public:
  notcool(){ printf("Not cool!\n");  }
};

template<int N>
class myclass{
public:
  typedef std::conditional<N==5,cool,notcool> thetype;
  thetype theinst;
};

int main(){
  printf("Testing\n");
  myclass<5> myc5;
  myclass<6> myc6;
  printf("Done testing\n");
  return 0;
}

I would expect my program to give the following output:

Testing

Cool!

Not cool!

Done testing

Instead, the output is

Testing

Done testing

My compiler is GCC 4.9, and the way I compiled this program was using the command g++ test -std=c++11 -o test

Can anyone tell me why the program does not give the output I expect?


问:
Is it possible to find out which columns are (not) explicitly queried in MySQL/MariaDB?
We have a very large, very old table with a few hundred columns. Some of the columns are historical and aren't used in any writing client. They are mostly empty (expect in very old records). I want to clean up the DB and get rid of old, unused columns in certain tables.

The problem are all the third party clients that access this DB (reading only). I can't expect all providers to update their clients. As long as they are querying for SELECT * ..., it doesn't matter. But I expect them to query explicitly (SELECT colA, colB, ...). Removing colA from the table would result in errors on the client side, obviously.

Now I would like to know which columns are explicitly used by any query statements, so I can remove the unused ones. I guess I could use the query log, analyze it and find explicitly used columns, but:

We receive a few millions queries per hour.

Some clients access our DB maybe once a week if at all, some every single second.

That means the query log would have to run for months in a production environment and I don't know if that could/would have any negative impact on the servers or overall performance.

Is there any other, more solid solution? Are my concerns regarding the query log exaggerated? I was hoping that MariaDB/MySQL are storing statistical data somewhere, showing the usage of columns, but I couldn't find anything I need.

答:
There no log of what columns are mentioned in queries.

The "general log" copies every query to a file.  This can be a serious disk hog (space and speed), especially with "millions of queries per hour".  But it would have an attempt at the answer...

The general log can, I think, be summarized via pt-query-digest.

Another possibility is to use tcpdump together with pt-query-digest to grab all the queries.

The advantage of the digest is that it consolidates multiple 'similar' queries into a single entry.  You would still have to manually (or problematically) sift through the output.

Most columns are not worth removing, even if they are never used.  I would suggest focusing on the 10% that are the bulkiest.  There might be a way to use tcpdump | egrep to look for just those column names.  Refine that a few times, and you might discover some prime candidate(s) for removal.

Unfortunately, if the clients do SELECT *, then "all" columns are being used.


问:
Send message from server at specific time in php?
Is there any way to send mail at specific time in php?

Please give me hint for that file. I forget to that file which is used to send mail to specific time.

答: Unfortunately you can't do this with only PHP. You would need to run a cron which would then run the specific PHP script.  If you want to send the mail at the same time each day, then you would run the cron at that time each day and the PHP script would then send your email.</p>


问:
Apply function to each cell in DataFrame multithreadedly in pandas
Is it possible to apply function to each cell in a DataFrame multithreadedly in pandas?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow multithreading natively:

```<code>import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
</code>```

returns:

```<code>               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06
</code>```

Instead, I would like to use more than one core to perform the operation, since the applied function may be complex.

答:
Split by columns:

```<code>from multiprocessing import Pool

def format(col):
    return col.apply(lambda x: '%.2f' % x)

cores = 5
pool = Pool(cores)
for out_col in pool.imap(format, [frame[i] for i in frame]):
    frame[out_col.name] = out_col
pool.close()
pool.join()
</code>```

Or split by partitions size as mentioned in comments:

```<code>size = 10
frame_split = np.array_split(frame, size)
frame = pd.concat(pool.imap(func, frame_split))
</code>```

Body:
Is it possible to apply function to each cell in a DataFrame multithreadedly in pandas?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow multithreading natively:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)

returns:

               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06

Instead, I would like to use more than one core to perform the operation, since the applied function may be complex.

Body:
Split by columns:

from multiprocessing import Pool

def format(col):
    return col.apply(lambda x: '%.2f' % x)

cores = 5
pool = Pool(cores)
for out_col in pool.imap(format, [frame[i] for i in frame]):
    frame[out_col.name] = out_col
pool.close()
pool.join()

Or split by partitions size as mentioned in comments:

size = 10
frame_split = np.array_split(frame, size)
frame = pd.concat(pool.imap(func, frame_split))


问:
How to check if a pandas Series contains Timestamps?
Following seems to work at least in some cases:

```<code>series.dtype == np.dtype('<M8[ns]')
</code>```

but it doesn't look pretty and I'm not sure if it works always (with all(?) kinds of Timestamps).

Is there a nicer way for testing whether a column contains Timestamps?

答:
The approach in @shivsn's answer is simpler and most likely better.  This is a harder way that nonetheless may be informative.

See here for more details on dtypes.  But in a nutshell, the second character of the dtype string should be 'M' for a Datetime and 'm' for a Timedelta.  Hence, you could test dtype.str[1] == 'M' to detect a Datetime only or dtype.str[1].lower() == 'm' to detect either a Datetime or Timedelta.

```<code>>>> dr = pd.date_range('1-1-2017',periods=4,freq='d')
>>> df = pd.DataFrame({ 'i':range(3), 'x':[1.1,2.2,3.3],
                        'ts':dr[:3], 'td':dr[1:]-dr[:3] })

   i     td         ts    x
0  0 1 days 2017-01-01  1.1
1  1 1 days 2017-01-02  2.2
2  2 1 days 2017-01-03  3.3

>>> for v in df.columns:
        print( '\ncolumn ' + v + ': ')
        print( 'dtype.str: ', df[v].dtype.str )
        print( 'dtype:     ', df[v].dtype )
        print( 'timestamp? ', df[v].dtype.str[1] == 'M' )

column i:
dtype.str:  <i8
dtype:      int64
timestamp?  False

column td:
dtype.str:  <m8[ns]
dtype:      timedelta64[ns]
timestamp?  False

column ts:
dtype.str:  <M8[ns]
dtype:      datetime64[ns]
timestamp?  True

column x:
dtype.str:  <f8
dtype:      float64
timestamp?  False
</code>```

Body:
Following seems to work at least in some cases:

series.dtype == np.dtype('<M8[ns]')

but it doesn't look pretty and I'm not sure if it works always (with all(?) kinds of Timestamps).

Is there a nicer way for testing whether a column contains Timestamps?

Body:
The approach in @shivsn's answer is simpler and most likely better.  This is a harder way that nonetheless may be informative.

See here for more details on dtypes.  But in a nutshell, the second character of the dtype string should be 'M' for a Datetime and 'm' for a Timedelta.  Hence, you could test dtype.str[1] == 'M' to detect a Datetime only or dtype.str[1].lower() == 'm' to detect either a Datetime or Timedelta.

>>> dr = pd.date_range('1-1-2017',periods=4,freq='d')
>>> df = pd.DataFrame({ 'i':range(3), 'x':[1.1,2.2,3.3],
                        'ts':dr[:3], 'td':dr[1:]-dr[:3] })

   i     td         ts    x
0  0 1 days 2017-01-01  1.1
1  1 1 days 2017-01-02  2.2
2  2 1 days 2017-01-03  3.3

>>> for v in df.columns:
        print( '\ncolumn ' + v + ': ')
        print( 'dtype.str: ', df[v].dtype.str )
        print( 'dtype:     ', df[v].dtype )
        print( 'timestamp? ', df[v].dtype.str[1] == 'M' )

column i:
dtype.str:  <i8
dtype:      int64
timestamp?  False

column td:
dtype.str:  <m8[ns]
dtype:      timedelta64[ns]
timestamp?  False

column ts:
dtype.str:  <M8[ns]
dtype:      datetime64[ns]
timestamp?  True

column x:
dtype.str:  <f8
dtype:      float64
timestamp?  False


问:
How to save repeated computation in list comprehension in Python?
In the following Python code:

```<code>keyboards = [3, 1]
drivers = [5, 2, 8]
upper_limit = 10
sums = [k + d for k in keyboards for d in drivers if (k + d) <= upper_limit]
</code>```

I'd like to store the result of k+d in the list comprehension so that it can be referred in the list comprehension. Is it possible in Python3?

I know that we can do the following:

```<code>sums = []
for k in keyboards:
    for d in drivers:
        s = k + d
        if s <= upper_limit:
            sums.append(s)
</code>```

But I wish to avoid the side effect operation of append.

答:
If you are using Python 3.8 or newer, you can use the assignment operator (a.k.a. the walrus operator) to create a new local name and assign to it, inside a list comprehension. For your specific example, you'd do that in the left-hand operand for the <= comparison:

```<code>sums = [
    s
    for k in keyboards
    for d in drivers
    if (s := k + d) <= upper_limit
]
</code>```

Note that you have to use parentheses around the assignment here, as the walrus operator has the lowest precedence of all Python operators; without parentheses you'd be assigning the result of k + d <= upper_limit to s, so a boolean value.

Take into account that s will be visible in the surrounding scope, the name s will have the same scope as sums has; local inside a function, global if you run the list comprehension at the module level. k and d, on the other hand, are local to the list comprehension loop, and are not visible outside of the comprehension.

Demo:

```<code>>>> keyboards = [3, 1]
>>> drivers = [5, 2, 8]
>>> upper_limit = 10
>>> [s for k in keyboards for d in drivers if (s := k + d) <= upper_limit]
[8, 5, 6, 3, 9]
>>> s
9
>>> k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
</code>```

In earlier Python versions, only names in the target of for loops  can be used to assign to a new name in a list comprehension, so if you need a 'local' variable to reference a calculation, you need to find ways to add an extra loop.

So in Python 3.7 or older, you can add another loop over a single element tuple that calculates k + d:

```<code>sums = [
    s
    for k in keyboards
    for d in drivers
    for s in (k + d,)
    if s <= upper_limit
]
</code>```

(k + d,) is a single-element tuple, and so the for s in (k + d,) execute exactly once for each iteration over keyboards and drivers, effectively assigning k + d to s.

You could also use a generator expression to produce k + d sums for the two nested for loops, then iterate over the results of that expression:

```<code>sums = [
    s
    for s in (
        k + d
        for k in keyboards
        for d in drivers
    )
    if s <= upper_limit
]
</code>```

In the latter case you can store that expression as a separate variable first:

```<code>s_calc = (k + d for k in keyboards for d in drivers)
sums = [s for s in s_calc if s <= upper_limit]
</code>```

With these options, s is always local to the comprehension loop and is not visible at the sums scope level. It doesn't 'bleed' out of the comprehension expression.

Demo of the latter options:

```<code>>>> [s for k in keyboards for d in drivers for s in (k + d,) if s <= upper_limit]
[8, 5, 6, 3, 9]
>>> [s for s in (k + d for k in keyboards for d in drivers) if s <= upper_limit]
[8, 5, 6, 3, 9]
>>> s_calc = (k + d for k in keyboards for d in drivers)
>>> [s for s in s_calc if s <= upper_limit]
[8, 5, 6, 3, 9]
</code>```

Body:
In the following Python code:

keyboards = [3, 1]
drivers = [5, 2, 8]
upper_limit = 10
sums = [k + d for k in keyboards for d in drivers if (k + d) <= upper_limit]

I'd like to store the result of k+d in the list comprehension so that it can be referred in the list comprehension. Is it possible in Python3?

I know that we can do the following:

sums = []
for k in keyboards:
    for d in drivers:
        s = k + d
        if s <= upper_limit:
            sums.append(s)

But I wish to avoid the side effect operation of append.

Body:
If you are using Python 3.8 or newer, you can use the assignment operator (a.k.a. the walrus operator) to create a new local name and assign to it, inside a list comprehension. For your specific example, you'd do that in the left-hand operand for the <= comparison:

sums = [
    s
    for k in keyboards
    for d in drivers
    if (s := k + d) <= upper_limit
]

Note that you have to use parentheses around the assignment here, as the walrus operator has the lowest precedence of all Python operators; without parentheses you'd be assigning the result of k + d <= upper_limit to s, so a boolean value.

Take into account that s will be visible in the surrounding scope, the name s will have the same scope as sums has; local inside a function, global if you run the list comprehension at the module level. k and d, on the other hand, are local to the list comprehension loop, and are not visible outside of the comprehension.

Demo:

>>> keyboards = [3, 1]
>>> drivers = [5, 2, 8]
>>> upper_limit = 10
>>> [s for k in keyboards for d in drivers if (s := k + d) <= upper_limit]
[8, 5, 6, 3, 9]
>>> s
9
>>> k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

In earlier Python versions, only names in the target of for loops  can be used to assign to a new name in a list comprehension, so if you need a 'local' variable to reference a calculation, you need to find ways to add an extra loop.

So in Python 3.7 or older, you can add another loop over a single element tuple that calculates k + d:

sums = [
    s
    for k in keyboards
    for d in drivers
    for s in (k + d,)
    if s <= upper_limit
]

(k + d,) is a single-element tuple, and so the for s in (k + d,) execute exactly once for each iteration over keyboards and drivers, effectively assigning k + d to s.

You could also use a generator expression to produce k + d sums for the two nested for loops, then iterate over the results of that expression:

sums = [
    s
    for s in (
        k + d
        for k in keyboards
        for d in drivers
    )
    if s <= upper_limit
]

In the latter case you can store that expression as a separate variable first:

s_calc = (k + d for k in keyboards for d in drivers)
sums = [s for s in s_calc if s <= upper_limit]

With these options, s is always local to the comprehension loop and is not visible at the sums scope level. It doesn't 'bleed' out of the comprehension expression.

Demo of the latter options:

>>> [s for k in keyboards for d in drivers for s in (k + d,) if s <= upper_limit]
[8, 5, 6, 3, 9]
>>> [s for s in (k + d for k in keyboards for d in drivers) if s <= upper_limit]
[8, 5, 6, 3, 9]
>>> s_calc = (k + d for k in keyboards for d in drivers)
>>> [s for s in s_calc if s <= upper_limit]
[8, 5, 6, 3, 9]

ContentLicense: CC BY-SA 4.0


问:
laravel 5 vue.js csrf token
I've been at it for a while to get this csrf token to work with the vue.js example.

but it keeps saying i don't have a token. I've tried all kinds of variations.

bottom (not head, before end of body)

```<code>    <script>
    window.myToken =  <?php echo json_encode([
        '_token' => csrf_token(),
    ]); ?>
    </script>

    <script src="/js/manifest.js"></script>
    <script src="/js/vendor.js"></script>
    <script src="/js/app.js"></script>
</code>```

html

```<code><div id="app">
@section('content')
<example></example>
@endsection
</div>
</code>```

console output

```<code>CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

vendor.js:7635 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
</code>```

Example doesn't seem to do much either, but I guess i need the token.

答:
if you look into

/resources/assets/js/bootstrap.js

You will find

```<code>let token = document.head.querySelector('meta[name="csrf-token"]');
</code>```

You should add in your  tag this:

```<code> <meta name="csrf-token" content="{{csrf_token()}}">
</code>```

This error will not be shown anymore.

I hope this helps

Title: laravel 5 vue.js csrf token

Body:
I've been at it for a while to get this csrf token to work with the vue.js example.

but it keeps saying i don't have a token. I've tried all kinds of variations.

bottom (not head, before end of body)

html

@section('content')
<example></example>
@endsection

console output

CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

vendor.js:7635 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html

Example doesn't seem to do much either, but I guess i need the token.

Body:
if you look into

/resources/assets/js/bootstrap.js

You will find

let token = document.head.querySelector('meta[name="csrf-token"]');

You should add in your <head> tag this:

 <meta name="csrf-token" content="{{csrf_token()}}">

This error will not be shown anymore.

I hope this helps


问:
What's your most controversial programming opinion?
This is definitely subjective, but I'd like to try to avoid it becoming argumentative. I think it could be an interesting question if people treat it appropriately.

The idea for this question came from the comment thread from my answer to the "What are five things you hate about your favorite language?" question. I contended that classes in C# should be sealed by default - I won't put my reasoning in the question, but I might write a fuller explanation as an answer to this question. I was surprised at the heat of the discussion in the comments (25 comments currently).

So, what contentious opinions do you hold? I'd rather avoid the kind of thing which ends up being pretty religious with relatively little basis (e.g. brace placing) but examples might include things like "unit testing isn't actually terribly helpful" or "public fields are okay really". The important thing (to me, anyway) is that you've got reasons behind your opinions.

Please present your opinion and reasoning - I would encourage people to vote for opinions which are well-argued and interesting, whether or not you happen to agree with them.

答:
Tcl/Tk is the best GUI language/toolkit combo ever

It may lack specific widgets and be less good-looking than the new kids on the block, but its model is elegant and so easy to use that one can build working GUIs faster by typing commands interactively than by using a visual interface builder. Its expressive power is unbeatable: other solutions (Gtk, Java, .NET, MFC...) typically require ten to one hundred LOC to get the same result as a Tcl/Tk one-liner. All without even sacrificing readability or stability.

```<code>pack [label .l -text "Hello world!"] [button .b -text "Quit" -command exit]
</code>```

OwnerDisplayName: Jon Skeet

LastEditorDisplayName: brian d foy

Body:
Tcl/Tk is the best GUI language/toolkit combo ever

It may lack specific widgets and be less good-looking than the new kids on the block, but its model is elegant and so easy to use that one can build working GUIs faster by typing commands interactively than by using a visual interface builder. Its expressive power is unbeatable: other solutions (Gtk, Java, .NET, MFC...) typically require ten to one hundred LOC to get the same result as a Tcl/Tk one-liner. All without even sacrificing readability or stability.

pack [label .l -text "Hello world!"] [button .b -text "Quit" -command exit]

OwnerDisplayName: fbonnet


问:
How to change dynamically the xib of a UIVIewController
I have an UIVIewController "controller1" for instance. This controller is instanciated with initWithNibName... with "file1.xib".
I want to dynamically change the xib file of my "controller1" to "file2.xib"

To resume :

"controller1" <-> "file1.xib"
and I want to dynamically have :
"controler1" <-> "file2.xib"

How can I do this ?

Hope I was clear.

答:
I have two responses :

1) Why - this isn't something that you would normally do - what makes this case special? In fact, I'm going to edit this to be more emphatic --> DON'T DO IT <-- there will be all sorts of dependencies in UIViewController that you don't know about (for example if there is a low memory warning and your view controller unloads it's view, which xib would it load the view from when it had to display it again?)

2) If you desperately had to you can remove the view and reload it though NSBundle's loadNibNamed:owner: passing in the new xib and self as the owner.


问:
python - urllib.request.urlretrieve throws unexpected exception unknown url type: ' '
I am trying to download files using urllib.request.retrieve()

I am using Python 3 and the downloads are successful, but I don't know why it throws exception.

For some reason it throws an exception.

This is the main file:

```<code>import os
import urllib.request

zip_file_open = open("urls.txt")

if not os.path.exists('zip'):
    os.makedirs('zip')

num=1

true = True
b = true

for i in zip_file_open.read().splitlines():
    try:
        print(str(i))
        #response = urllib.request.urlopen(str(i))
        #print(response)
        #html = response.read()
        urllib.request.urlretrieve(i, "zip/code"+str(num)+".zip")
        if(b):
            num+=1
            b=False
        else:
            b=true
    except Exception as e:
        print("Exception: "+str(e))
        if(b):
            num+=1
            b=False
        else:
            b=true
</code>```

This is urls.txt:

```<code>http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip
........
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c25_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip
</code>```

Here is how I create the txt file:

```<code>f = open("urls.txt","w")

k = """http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c"""
k1 = """_code.zip"""

import os

for i in range(26):
    if(i<9):
        f.write(k+str(0)+str(i+1)+k1+os.linesep)
    else:
        f.write(k+str(i+1)+k1+os.linesep)
f.close()
</code>```

Here is the output

```<code>http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip

Exception2: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip

Exception3: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c03_code.zip
Exception3: HTTP Error 404: Not Found

........

Exception26: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip

Exception27: unknown url type: ''
</code>```

I didn't include all the lines of output as they were same. The code is functional but I would like to know if we can remove the exception.

答:
It looks like you have some blank lines in your file, so urllib throws a ValueError exception when you try to fetch '', which is clearly not a url.

You can fix this error if you add a condition in the loop to check for empty strings.

```<code>for i in zip_file_open.read().splitlines():
    if not i.strip():
        continue
    ...
</code>```

But this won't work for non-empty strings that are not urls, for example 'not a url'.

A better approach would be to check the url scheme with urlparse.

```<code>for i in zip_file_open.read().splitlines():
    if not urllib.parse.urlparse(i).scheme:
        continue
    ...
</code>```

Body:
I am trying to download files using urllib.request.retrieve()

I am using Python 3 and the downloads are successful, but I don't know why it throws exception.

For some reason it throws an exception.

This is the main file:

import os
import urllib.request

zip_file_open = open("urls.txt")

if not os.path.exists('zip'):
    os.makedirs('zip')

num=1

true = True
b = true

for i in zip_file_open.read().splitlines():
    try:
        print(str(i))
        #response = urllib.request.urlopen(str(i))
        #print(response)
        #html = response.read()
        urllib.request.urlretrieve(i, "zip/code"+str(num)+".zip")
        if(b):
            num+=1
            b=False
        else:
            b=true
    except Exception as e:
        print("Exception: "+str(e))
        if(b):
            num+=1
            b=False
        else:
            b=true

This is urls.txt:

http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip
........
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c25_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip

Here is how I create the txt file:

f = open("urls.txt","w")

k = """http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c"""
k1 = """_code.zip"""

import os

for i in range(26):
    if(i<9):
        f.write(k+str(0)+str(i+1)+k1+os.linesep)
    else:
        f.write(k+str(i+1)+k1+os.linesep)
f.close()

Here is the output

http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip

Exception2: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip

Exception3: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c03_code.zip
Exception3: HTTP Error 404: Not Found

........

Exception26: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip

Exception27: unknown url type: ''

I didn't include all the lines of output as they were same. The code is functional but I would like to know if we can remove the exception.

Body:
It looks like you have some blank lines in your file, so urllib throws a ValueError exception when you try to fetch '', which is clearly not a url.

You can fix this error if you add a condition in the loop to check for empty strings.

for i in zip_file_open.read().splitlines():
    if not i.strip():
        continue
    ...

But this won't work for non-empty strings that are not urls, for example 'not a url'.

A better approach would be to check the url scheme with urlparse.

for i in zip_file_open.read().splitlines():
    if not urllib.parse.urlparse(i).scheme:
        continue
    ...


问:
How to Html Input value echo in php
I have made some classes in css and i have a html form and i also have some html elements and i want to echo them by php but i want them to echo by the value of html form submition
For eg

```<code>    <form action="index.php"  method="post">
<select name="slideNumber">
 <option value="3" name="slideNumber">3 Image Slider</option>
<option value="right-3" name="slideNumber">3 Image Right Slider</option>
<option value="4" name="slideNumber">4 Image Slider</option>
<option value="right-4" name="slideNumber">4 Image Right Slider</option>
<!--And more just like this-->
</select>
<input type="submit" value="submit" />
</form>

<?php
 $i= trim($_POST['slideNumber']);
if(($i = '3') || ($i = 'right-3')){
     $x= '3';
}
else if(($i = '4') || ($i = 'right-4')){
     $x= '4';
}
echo "
         <div class=\"slider-".$x."\">
         </div>
";
?>
</code>```

It is showing only first $x
I mean it is showing slider-3 even if i had give the value 4 in form please help me to solve this

答:
Additionally, You should check value of POST data by isset first...</p>

```<code>if (isset($_POST['slideNumber']))
{}
</code>```

Title: How to Html Input value echo in php

Body:
I have made some classes in css and i have a html form and i also have some html elements and i want to echo them by php but i want them to echo by the value of html form submition
For eg

    <form action="index.php"  method="post">
<select name="slideNumber">
 <option value="3" name="slideNumber">3 Image Slider</option>
<option value="right-3" name="slideNumber">3 Image Right Slider</option>
<option value="4" name="slideNumber">4 Image Slider</option>
<option value="right-4" name="slideNumber">4 Image Right Slider</option>

</select>
<input type="submit" value="submit" />
</form>

<?php
 $i= trim($_POST['slideNumber']);
if(($i = '3') || ($i = 'right-3')){
     $x= '3';
}
else if(($i = '4') || ($i = 'right-4')){
     $x= '4';
}
echo "

";
?>

It is showing only first $x
I mean it is showing slider-3 even if i had give the value 4 in form please help me to solve this

Body:
Additionally, You should check value of POST data by isset first...

if (isset($_POST['slideNumber']))
{}


问:
Parsing nested JSON in go language
How could I parse and extract certain values from below JSON

Here is the sample JSON response

```<code>{
   "success":true,
   "endpoint":"https://api.abcxyz.com",
   "info":{
      "Guestconnected":134,
      "Guestratio":100000.06963,
      "symbol1":{
         "code":"NY",
         "symbol":"*",
         "name":"newyear",
         "codev":391.78161,
         "symbolAppearsAfter":false,
         "local":true
      },
      "symbol2":{
         "code":"HNY",
         "symbol":"@",
         "name":"HappyNewYear",
         "codev":1000000.0960,
         "symbolAppearsAfter":true,
         "local":false
      },
      "latest":{
         "value":1597509,
         "autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height":474696,
         "time":1499527696
      }
   },
   "Allguest":{
      "all":4,
      "filtered":4,
      "total_invitations":15430,
      "sent_invitations":15430,
      "final_invitations":0
   },
   "Guestlist":[
      {
         "GuestCode":"369AR",
         "all":2,
         "total_invitations":5430,
         "sent_invitations":5430,
         "final_invitations":0,
         "change":0,
         "accounts":0
      },
      {
         "GuestCode":"6POIA96TY",
         "all":2,
         "total_invitations":10000,
         "sent_invitations":10000,
         "final_invitations":0,
         "change":0,
         "accounts":0
      }
   ]
}
</code>```

My Code is :

```<code>package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func main() {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

 var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)

}
</code>```

The problem is :

If the response is null it is giving index out of range error how can we avoid this ?

Applying condition if TotalInvitations value is greater than 100 then save in 100.csv else save in others.csv

答:
use gjson pkg to get value from json document an simple way

example:

```<code>package main

import (
    "fmt"

    "github.com/tidwall/gjson"
)

func main() {
    data := []byte(`{
   "success": true,
   "endpoint": "https://api.abcxyz.com",
   "info": {
      "Guestconnected": 134,
      "Guestratio": 100000.06963,
      "symbol1": {
         "code": "NY",
         "symbol": "*",
         "name": "newyear",
         "codev": 391.78161,
         "symbolAppearsAfter": false,
         "local": true
      },
      "symbol2": {
         "code": "HNY",
         "symbol": "@",
         "name": "HappyNewYear",
         "codev": 1000000.096,
         "symbolAppearsAfter": true,
         "local": false
      },
      "latest": {
         "value": 1597509,
         "autovalue": "00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height": 474696,
         "time": 1499527696
      }
   },
   "Allguest": {
      "all": 4,
      "filtered": 4,
      "total_invitations": 15430,
      "sent_invitations": 15430,
      "final_invitations": 0
   },
   "Guestlist": [
      {
         "GuestCode": "369AR",
         "all": 2,
         "total_invitations": 5430,
         "sent_invitations": 5430,
         "final_invitations": 0,
         "change": 0,
         "accounts": 0
      },
      {
         "GuestCode": "6POIA96TY",
         "all": 2,
         "total_invitations": 10000,
         "sent_invitations": 10000,
         "final_invitations": 0,
         "change": 0,
         "accounts": 0
      }
   ]
    }
    `)

    r := gjson.GetBytes(data, "Allguest.total_invitations")
    fmt.Println(r.Value()) // output 15430

    r = gjson.GetBytes(data, "Guestlist.#.total_invitations")
    fmt.Println(r.Value()) // output [5430 10000]
}
</code>```

Title: Parsing nested JSON in go language

Body:
How could I parse and extract certain values from below JSON

Here is the sample JSON response

{
   "success":true,
   "endpoint":"https://api.abcxyz.com",
   "info":{
      "Guestconnected":134,
      "Guestratio":100000.06963,
      "symbol1":{
         "code":"NY",
         "symbol":"*",
         "name":"newyear",
         "codev":391.78161,
         "symbolAppearsAfter":false,
         "local":true
      },
      "symbol2":{
         "code":"HNY",
         "symbol":"@",
         "name":"HappyNewYear",
         "codev":1000000.0960,
         "symbolAppearsAfter":true,
         "local":false
      },
      "latest":{
         "value":1597509,
         "autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height":474696,
         "time":1499527696
      }
   },
   "Allguest":{
      "all":4,
      "filtered":4,
      "total_invitations":15430,
      "sent_invitations":15430,
      "final_invitations":0
   },
   "Guestlist":[
      {
         "GuestCode":"369AR",
         "all":2,
         "total_invitations":5430,
         "sent_invitations":5430,
         "final_invitations":0,
         "change":0,
         "accounts":0
      },
      {
         "GuestCode":"6POIA96TY",
         "all":2,
         "total_invitations":10000,
         "sent_invitations":10000,
         "final_invitations":0,
         "change":0,
         "accounts":0
      }
   ]
}

My Code is :

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func main() {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

 var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)

}

The problem is :

If the response is null it is giving index out of range error how can we avoid this ?

Applying condition if TotalInvitations value is greater than 100 then save in 100.csv else save in others.csv

Body:
use gjson pkg to get value from json document an simple way

example:

package main

import (
    "fmt"

    "github.com/tidwall/gjson"
)

func main() {
    data := []byte(`{
   "success": true,
   "endpoint": "https://api.abcxyz.com",
   "info": {
      "Guestconnected": 134,
      "Guestratio": 100000.06963,
      "symbol1": {
         "code": "NY",
         "symbol": "*",
         "name": "newyear",
         "codev": 391.78161,
         "symbolAppearsAfter": false,
         "local": true
      },
      "symbol2": {
         "code": "HNY",
         "symbol": "@",
         "name": "HappyNewYear",
         "codev": 1000000.096,
         "symbolAppearsAfter": true,
         "local": false
      },
      "latest": {
         "value": 1597509,
         "autovalue": "00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height": 474696,
         "time": 1499527696
      }
   },
   "Allguest": {
      "all": 4,
      "filtered": 4,
      "total_invitations": 15430,
      "sent_invitations": 15430,
      "final_invitations": 0
   },
   "Guestlist": [
      {
         "GuestCode": "369AR",
         "all": 2,
         "total_invitations": 5430,
         "sent_invitations": 5430,
         "final_invitations": 0,
         "change": 0,
         "accounts": 0
      },
      {
         "GuestCode": "6POIA96TY",
         "all": 2,
         "total_invitations": 10000,
         "sent_invitations": 10000,
         "final_invitations": 0,
         "change": 0,
         "accounts": 0
      }
   ]
    }
    `)

    r := gjson.GetBytes(data, "Allguest.total_invitations")
    fmt.Println(r.Value()) // output 15430

    r = gjson.GetBytes(data, "Guestlist.#.total_invitations")
    fmt.Println(r.Value()) // output [5430 10000]
}


问:
Cassandra-Spark Connector uploading by parsing arguments
I am using the spark-cassandra-connector in scala and I want to upload some entries into a table. I have seen the following uploading method using the session construct for the python driver:

```<code>session.execute(
    """
    INSERT INTO users (name, credits, user_id)
    VALUES (%s, %s, %s)
    """,
    ("John O'Reilly", 42, uuid.uuid1())
)
</code>```

Does the spark-connector support a similar way for parsing the arguments in an upload and if so how would the construct look like? When I tested the above methodology it did not work.

答:
The Spark Cassandra Connector is primarily made for the manipulation of Cassandra data using Spark. This means if you aren't using the words Dataset, Dataframe, or RDD you probably don't need to be using the Spark Cassandra Connector.

The format you are using above is valid in the Java Driver which is included as part of the Spark Cassandra connector and can be accessed via the CassandraConnector wrapper. As is explained in the Documentation

```<code>import com.datastax.spark.connector.cql.CassandraConnector

CassandraConnector(conf).withSessionDo { session =>
  session.execute("CREATE KEYSPACE test2 WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1 }")
  session.execute("CREATE TABLE test2.words (word text PRIMARY KEY, count int)")
}
</code>```

Body:
I am using the spark-cassandra-connector in scala and I want to upload some entries into a table. I have seen the following uploading method using the session construct for the python driver:

session.execute(
    """
    INSERT INTO users (name, credits, user_id)
    VALUES (%s, %s, %s)
    """,
    ("John O'Reilly", 42, uuid.uuid1())
)

Does the spark-connector support a similar way for parsing the arguments in an upload and if so how would the construct look like? When I tested the above methodology it did not work.

Body:
The Spark Cassandra Connector is primarily made for the manipulation of Cassandra data using Spark. This means if you aren't using the words Dataset, Dataframe, or RDD you probably don't need to be using the Spark Cassandra Connector.

The format you are using above is valid in the Java Driver which is included as part of the Spark Cassandra connector and can be accessed via the CassandraConnector wrapper. As is explained in the Documentation

import com.datastax.spark.connector.cql.CassandraConnector

CassandraConnector(conf).withSessionDo { session =>
  session.execute("CREATE KEYSPACE test2 WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1 }")
  session.execute("CREATE TABLE test2.words (word text PRIMARY KEY, count int)")
}


问:
Are there any drawbacks to using head.js?
Things I am aware of:

Screen flicker if scripts alter styles / content (not an issue for me as I currently load scripts at the end of the page and so have workarounds already)

Inability to detect script load failure (not too concerned about this either as everything I develop is required to work with or without javascript. Might affect my workarounds for item 1 but happy with this risk)

It looks to be a very good option to me but I am hoping for some references (feel free to say only positive things!) before I invest time in incorporating it into my next project.

Currently we develop mid-to-large sized sites with, generally, a moderate amount of Javascript (although this is growing rapidly). We also use the jQuery library for the bulk of our Javascript.

Anyone have any experience? Good or bad! :)

P.S. for those interested this is head.js

答: Nope. As long as you put any code that is dependent on the loading files inside head.ready {} then you will not face any problems with your code.</p>


问:
Run debugger on javaFX project in android
I am trying to rebuild an old javafx project on android. Currently I am using javafxports to do so. The problem is I can't debug it, this is how the project hierarchy looks:

The application is started from DisplayClient. So far I am able to log messages using the device monitor. Can you please tell me if it is possible to attach a debugger and if it is how? If any further information is needed I would be happy to give it.

答:
You can easily attach a debugger to your IntelliJ IDE while running your app on an Android device.

To debug a JavaFXPorts/Gluon Mobile that you have created using the Gluon plugin for your IDE (NetBeans, IntelliJ or Eclipse), and that you have deployed to the Android device, follow these steps:

1. Create the JavaFX mobile app from your IDE

For that you can use the Gluon plugin for your IDE. Use one of the built-in templates to create your project or go and use one of the many samples available here.

Let's say you use the Single View project. Provide a name and run the app

2. Create the apk

Run the task from the Gradle View Tasks->other->AndroidInstall to create the apk (or on command line run ./gradlew android).

3. Open the app on your device

Make sure the app works on your device, and don't close it.

4. Open Android Device Monitor

Go to <android sdk>/tools and run monitor. On the left, on top you should see the device, and a list of processes. Find your app package name there, select it and see the port it is using for the app (8600).

5. Attach the debugger on your IDE

Finally, go back to your IDE, and attach the remote debugger, with localhost and 8600 port. For the IntelliJ IDE, go to Run->Edit Configurations..., on the upper left click +, select the Remote option, and provide a name (remote debugger), and the port:

6. Run the debugger on your IDE

Click ok to save, add some breakpoint to your code, and now run the debugger.

In this case, I have a breakpoint in the button event handler, so when I click on it, the app halts at the breakpoint:


问:
AWS EC2 instance seemed to self-destruct after moving NLTK data location
So I built a data and NLP app with a flask front end which functions perfectly locally but a flood of issues began as I tried to set this up on AWS (Ubuntu linux) behind an Apache server as we are advised to do (flask not being designed for deployment). The importing of python modules suddenly becomes quite a challenge with this setup, there are a number of questions about it on Stackoverflow. Had worked through about 5 of these issues, was using lots of Python logging statements each time throughout the code to see at what point exactly the various scripts were crashing or hanging (without error messages) and then it got further than ever before and this issue about the location of the NLTK corpus came up. Not the NLTK module, that imported fine, just the corpus folder.

So to do this usually just takes the following code:

```<code>import nltk
nltk.download()
</code>```

which opens up a kind of a user interface where you can select which corpus or NLP item to download and whether to change the directory to store it somewhere else. By default it makes the directory nltk_data/ in your home directory and puts it in there.

So I thought at first the issue was that the folder needed permissions for the Apache user www-data but that didn't work. Then noticed in the Apache error log that it had looked in 4 folders and not found anything - one of them being /var/www/nltk_data and none of them being the home directory where it actually was. Can't remember the other 3..

I looked through a couple of similar questions on Stackoverflow (1,2,3,4) but decided to go with something simpler. So did the following:

```<code>sudo mkdir /var/www/nltk_data
sudo cp -r nltk_data/   /var/www/
</code>```

Then I flushed the Apache log again, restarted the server and started checking the log. It was running at the usual rate, taking a few minutes to get through the scripts, was rechecking the log, and new logging messages kept appearing, then some message about memory kept repeating on the ssh screen and the logs were no longer visible. I couldn't type anything. It logged me out, wouldn't let me log back in. Went into the AWS console, rebooted it twice. Stopped it, started it again, still couldn't log in. So in anger, terminated it. Regretted doing that but didn't feel there was any point keeping it there if you couldn't log into it.

Questions:

Was that okay to copy the nltk_data directory to /var/www where Apache was looking, should I do that again?

If an EC2 instance runs out of memory, does it typically kill it so badly that even after stopping and starting it, you can no longer log in?

If this happens again, from my local terminal, is there a way to reboot the thing in 'safe' mode, so I can get in there and try to undo whatever I did that killed it? (rather than just effectively deleting the whole thing)

Will likely have another go now, recreate the instance, perhaps the 4MB ram was not enough for my app and Apache together, would like to know the answers to these things or any other relevant tips for when I next have to do this nltk step..

答:
So I solved it thankfully after setting up a new instance and here is how:

```<code>sudo ln -sT /home/ubuntu/nltk_data  /usr/share/nltk_data
</code>```

Am happy everything is now working. Have been watching the output of the top system monitor on the new instance which is slightly larger than the one which self-destructed, and notice that it never uses more than about 40% of the memory but the CPU is maxing out for long periods while the main scripts run. Maybe that is what killed the smaller instance..

When I initially went to install the stopwords it looked here:
LookupError:

```<code>**********************************************************************
  Resource 'corpora/stopwords' not found.  Please use the NLTK
  Downloader to obtain the resource:  >>> nltk.download()
  Searched in:
    - '/home/ubuntu/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
**********************************************************************
</code>```

the apache log however showed that it looked mainly in the same places except..

```<code>] [pid 19:tid 13] [client 77..]   Resource 'corpora/stopwords' not found.  Please use the NLTK
[Sat Jul 08 16:35:19.694759 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]   Downloader to obtain the resource:  >>> nltk.download()
[Sat Jul 08 16:35:19.694762 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]   Searched in:
[Sat Jul 08 16:35:19.694764 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/var/www/nltk_data'
[Sat Jul 08 16:35:19.694766 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/share/nltk_data'
[Sat Jul 08 16:35:19.694768 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/local/share/nltk_data'
[Sat Jul 08 16:35:19.694770 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/lib/nltk_data'
[Sat Jul 08 16:35:19.694772 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/local/lib/nltk_data'
</code>```

So I thought it would be safer to link rather than copy and also, to use that /usr/share/ directory where Apache was looking anyway rather than mess with its own directory.

Body:
So I built a data and NLP app with a flask front end which functions perfectly locally but a flood of issues began as I tried to set this up on AWS (Ubuntu linux) behind an Apache server as we are advised to do (flask not being designed for deployment). The importing of python modules suddenly becomes quite a challenge with this setup, there are a number of questions about it on Stackoverflow. Had worked through about 5 of these issues, was using lots of Python logging statements each time throughout the code to see at what point exactly the various scripts were crashing or hanging (without error messages) and then it got further than ever before and this issue about the location of the NLTK corpus came up. Not the NLTK module, that imported fine, just the corpus folder.

So to do this usually just takes the following code:

import nltk
nltk.download()

which opens up a kind of a user interface where you can select which corpus or NLP item to download and whether to change the directory to store it somewhere else. By default it makes the directory nltk_data/ in your home directory and puts it in there.

So I thought at first the issue was that the folder needed permissions for the Apache user www-data but that didn't work. Then noticed in the Apache error log that it had looked in 4 folders and not found anything - one of them being /var/www/nltk_data and none of them being the home directory where it actually was. Can't remember the other 3..

I looked through a couple of similar questions on Stackoverflow (1,2,3,4) but decided to go with something simpler. So did the following:

sudo mkdir /var/www/nltk_data
sudo cp -r nltk_data/   /var/www/

Then I flushed the Apache log again, restarted the server and started checking the log. It was running at the usual rate, taking a few minutes to get through the scripts, was rechecking the log, and new logging messages kept appearing, then some message about memory kept repeating on the ssh screen and the logs were no longer visible. I couldn't type anything. It logged me out, wouldn't let me log back in. Went into the AWS console, rebooted it twice. Stopped it, started it again, still couldn't log in. So in anger, terminated it. Regretted doing that but didn't feel there was any point keeping it there if you couldn't log into it.

Questions:

Was that okay to copy the nltk_data directory to /var/www where Apache was looking, should I do that again?

If an EC2 instance runs out of memory, does it typically kill it so badly that even after stopping and starting it, you can no longer log in?

If this happens again, from my local terminal, is there a way to reboot the thing in 'safe' mode, so I can get in there and try to undo whatever I did that killed it? (rather than just effectively deleting the whole thing)

Will likely have another go now, recreate the instance, perhaps the 4MB ram was not enough for my app and Apache together, would like to know the answers to these things or any other relevant tips for when I next have to do this nltk step..

Body:
So I solved it thankfully after setting up a new instance and here is how:

sudo ln -sT /home/ubuntu/nltk_data  /usr/share/nltk_data

Am happy everything is now working. Have been watching the output of the top system monitor on the new instance which is slightly larger than the one which self-destructed, and notice that it never uses more than about 40% of the memory but the CPU is maxing out for long periods while the main scripts run. Maybe that is what killed the smaller instance..

When I initially went to install the stopwords it looked here:
LookupError:

**********************************************************************
  Resource 'corpora/stopwords' not found.  Please use the NLTK
  Downloader to obtain the resource:  >>> nltk.download()
  Searched in:
    - '/home/ubuntu/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
**********************************************************************

the apache log however showed that it looked mainly in the same places except..

] [pid 19:tid 13] [client 77..]   Resource 'corpora/stopwords' not found.  Please use the NLTK
[Sat Jul 08 16:35:19.694759 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]   Downloader to obtain the resource:  >>> nltk.download()
[Sat Jul 08 16:35:19.694762 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]   Searched in:
[Sat Jul 08 16:35:19.694764 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/var/www/nltk_data'
[Sat Jul 08 16:35:19.694766 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/share/nltk_data'
[Sat Jul 08 16:35:19.694768 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/local/share/nltk_data'
[Sat Jul 08 16:35:19.694770 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/lib/nltk_data'
[Sat Jul 08 16:35:19.694772 2017] [wsgi:error] [pid 19437:tid 1..] [client 77..]     - '/usr/local/lib/nltk_data'

So I thought it would be safer to link rather than copy and also, to use that /usr/share/ directory where Apache was looking anyway rather than mess with its own directory.


问:
Send a direct message on private message to welcome new users who join the server
I want to get the bot to send a direct/private message to new users that join the server. It is able to post a welcome message on a channel but it keeps throwing errors for direct messages.</p>
```<code>const Discord = require('discord.js');
const bot = new Discord.Client ();

bot.on('ready', () => {
  console.log('I am ready!');
});

bot.on('guildMemberAdd', member => {
       member.guild.defaultChannel.send(`Welcome to the server, ${member}!`);
       console.log(`${member.user.username} has joined`);
});

bot.login('TOKEN_HERE');
</code>```

答:
Member object has a send method just like channels.

Note sendMessage is deprecated

```<code>const Discord = require('discord.js');
const bot = new Discord.Client ();

bot.on('guildMemberAdd', member => {
   member.send("Welcome to the server!");
});

bot.login('TOKEN_HERE');
</code>```

Body:
I want to get the bot to send a direct/private message to new users that join the server. It is able to post a welcome message on a channel but it keeps throwing errors for direct messages.

const Discord = require('discord.js');
const bot = new Discord.Client ();

bot.on('ready', () => {
  console.log('I am ready!');
});

bot.on('guildMemberAdd', member => {
       member.guild.defaultChannel.send(`Welcome to the server, ${member}!`);
       console.log(`${member.user.username} has joined`);
});

bot.login('TOKEN_HERE');

Body:
Member object has a send method just like channels.

Note sendMessage is deprecated

const Discord = require('discord.js');
const bot = new Discord.Client ();

bot.on('guildMemberAdd', member => {
   member.send("Welcome to the server!");
});

bot.login('TOKEN_HERE');


问:
using std::conditional to choose member type based on template parameter
Here is my program that attempts to use std::conditional to set the type of a member variable based on the value of an integer template parameter.

```<code>#include <stdio.h>
#include <type_traits>
using namespace std;

class cool{
public:
  cool(){ printf("Cool!\n");  }
};

class notcool{
public:
  notcool(){ printf("Not cool!\n");  }
};

template<int N>
class myclass{
public:
  typedef std::conditional<N==5,cool,notcool> thetype;
  thetype theinst;
};

int main(){
  printf("Testing\n");
  myclass<5> myc5;
  myclass<6> myc6;
  printf("Done testing\n");
  return 0;
}
</code>```

I would expect my program to give the following output:

Testing

Cool!

Not cool!

Done testing

Instead, the output is

Testing

Done testing

My compiler is GCC 4.9, and the way I compiled this program was using the command g++ test -std=c++11 -o test

Can anyone tell me why the program does not give the output I expect?

答:
thetype is actually not cool, and also not notcool. But std::conditional.

Yes. std::conditional is a type, that's how most type traits are implemented. If you want to get the underlying type from the conditional, you need to access the underlying type member from std::conditional. That's also how most type traits are implemented: They all have a type member which can be used to access the actual type you want, and not the type trait type.

In C++14, you would use std::conditional_t, which is just a alias for the type member of std::conditional, but because you are using C++11, you need to access it explicitly:

```<code>typedef typename std::conditional<N == 5, cool, notcool>::type thetype;
</code>```

Body:
Here is my program that attempts to use std::conditional to set the type of a member variable based on the value of an integer template parameter.

#include <stdio.h>
#include <type_traits>
using namespace std;

class cool{
public:
  cool(){ printf("Cool!\n");  }
};

class notcool{
public:
  notcool(){ printf("Not cool!\n");  }
};

template<int N>
class myclass{
public:
  typedef std::conditional<N==5,cool,notcool> thetype;
  thetype theinst;
};

int main(){
  printf("Testing\n");
  myclass<5> myc5;
  myclass<6> myc6;
  printf("Done testing\n");
  return 0;
}

I would expect my program to give the following output:

Testing

Cool!

Not cool!

Done testing

Instead, the output is

Testing

Done testing

My compiler is GCC 4.9, and the way I compiled this program was using the command g++ test -std=c++11 -o test

Can anyone tell me why the program does not give the output I expect?

Body:
thetype is actually not cool, and also not notcool. But std::conditional.

Yes. std::conditional is a type, that's how most type traits are implemented. If you want to get the underlying type from the conditional, you need to access the underlying type member from std::conditional. That's also how most type traits are implemented: They all have a type member which can be used to access the actual type you want, and not the type trait type.

In C++14, you would use std::conditional_t, which is just a alias for the type member of std::conditional, but because you are using C++11, you need to access it explicitly:

typedef typename std::conditional<N == 5, cool, notcool>::type thetype;