问:
when app is in background and if internet connection lost, app is getting crashed
We are working on react native and we implemented NetInfo event listener to check internet connectivity.

We are also calling fetch() on events to get data from google api. When app is in background and if internet connection lost then app is getting crashed with following error:

```<code>ReactNativeJS: Network request failed
E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
E AndroidRuntime: Process: com.example, PID: 30344
E AndroidRuntime: com.facebook.react.common.JavascriptException: Network request failed, stack:
E AndroidRuntime: onerror@25623:21
E AndroidRuntime: dispatchEvent@10670:19
E AndroidRuntime: setReadyState@27824:19
E AndroidRuntime: __didCompleteResponse@27660:19
E AndroidRuntime: <unknown>@27764:57
E AndroidRuntime: emit@9771:28
E AndroidRuntime: __callFunction@7571:39
E AndroidRuntime: <unknown>@7443:21
E AndroidRuntime: guard@7381:3
E AndroidRuntime: callFunctionReturnFlushedQueue@7442:6
E AndroidRuntime:
E AndroidRuntime: at com.facebook.react.modules.core.ExceptionsManagerModule.showOrThrowError(ExceptionsManagerModule.java:97)
E AndroidRuntime: at com.facebook.react.modules.core.ExceptionsManagerModule.reportFatalException(ExceptionsManagerModule.java:81)
E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
E AndroidRuntime:        at com.facebook.react.bridge.BaseJavaModule$JavaMethod.invoke(BaseJavaModule.java:318)
E AndroidRuntime:        at com.facebook.react.cxxbridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
E AndroidRuntime:        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
E AndroidRuntime:        at android.os.Handler.handleCallback(Handler.java:739)
E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:95)
E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
E AndroidRuntime:        at java.lang.Thread.run(Thread.java:818)
I ReactNativeJS: auth/network-request-failed
I ReactNativeJS: A network error (such as timeout, interrupted connection or unreachable host) has occurred.
W ActivityManager:   Force finishing activity com.example/.MainActivity
</code>```

I have created android react native module to get GPS current location using NETWORK_PROVIDER.

```<code>public class GpsLocationCheckModule extends ReactContextBaseJavaModule implements LocationListener{
private Promise promiseCallback;
public boolean gps_enabled = false;
private ReactApplicationContext mReactContext;
private Activity currentActivity;
private static final String SETTINGS_FAILURE = "SETTINGS_FAILURE";
private LocationManager locationManager;
public static final String TAG = GpsLocationCheckModule.class.getSimpleName();
private String messageText;
private Location location;
private boolean isPopUpDisplayed = false;

public GpsLocationCheckModule(ReactApplicationContext reactContext) {
    super(reactContext);
    //reactContext.addActivityEventListener(mActivityEventListener);
    mReactContext = reactContext;
   reactContext.addActivityEventListener(mActivityEventListener);
}

@Override
public String getName() {
    return "GpsServiceLocation"; //this will be use at JS side.
}

@ReactMethod
public void checkLocation(String message, Promise promise) {
    currentActivity = getCurrentActivity();
    promiseCallback=promise;
    messageText= message;
    Log.i(TAG,"check location");
    locationManager = (LocationManager)mReactContext.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0, this);
    boolean gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if(!gps_enabled){
        if(!isPopUpDisplayed){
            isPopUpDisplayed = true;
            Log.i(TAG,"checklocatoin disabled" + Boolean.toString(isPopUpDisplayed));
            displayPromptForEnablingGPS(currentActivity,messageText,promiseCallback);
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i(TAG,"location changed");
    String msg = "New Latitude: " + location.getLatitude()
            + "New Longitude: " + location.getLongitude();
    Log.i(TAG,msg);
    WritableMap params = Arguments.createMap();
    params.putDouble("Longitude", location.getLongitude());
    params.putDouble("Latitude", location.getLatitude());
    //locationManager.removeUpdates(this);
     Log.i(TAG,"removed");
   sendEvent(mReactContext, "locationChanged", params);
}

@Override
public void onProviderDisabled(String provider) {
    Log.i(TAG,"disabled");
    Log.i(TAG,"ispopup disabled" + Boolean.toString(isPopUpDisplayed));
    if(!isPopUpDisplayed){
        isPopUpDisplayed = true;
        Log.i(TAG,"ispopup inside disabled" + Boolean.toString(isPopUpDisplayed));
        displayPromptForEnablingGPS(currentActivity,messageText,promiseCallback);
    }
}

@Override
public void onProviderEnabled(String provider) {
    Log.i(TAG,"enabled");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.i(TAG,"status changed");
    // TODO Auto-generated method stub

}

private void displayPromptForEnablingGPS(final Activity activity, final String message, final Promise promise) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final String action = android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS;

    builder.setMessage(Html.fromHtml(message))
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int id) {
                            activity.startActivityForResult(new Intent(action), 1);
                            dialogInterface.dismiss();
                        }
                    })
            .setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int id) {
                            popupRejected();
                            dialogInterface.cancel();
                        }
                    });
    builder.create().show();
}

private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        currentActivity = activity;
        checkLocationService(true);
    }
};

public void checkLocationService(Boolean status){
    WritableMap map = Arguments.createMap();
    map.putString("status", "success");
    isPopUpDisplayed=false;
    Log.i(TAG,"ispopup checklocation" + Boolean.toString(isPopUpDisplayed));
    if(promiseCallback != null){
        promiseCallback.resolve(map);
        promiseCallback = null;
    }
}
public void popupRejected(){
    isPopUpDisplayed = false;
    Log.i(TAG,"ispopup rejected" + Boolean.toString(isPopUpDisplayed));
    if(promiseCallback != null){
        promiseCallback.reject(SETTINGS_FAILURE,"Gps enabling failed");
    }
}

 /*
 * Internal function for communicating with JS
 */
private void sendEvent(ReactContext reactContext,
    String eventName, @Nullable WritableMap params) {
    if (reactContext.hasActiveCatalystInstance()) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    } else {
        Log.i(TAG, "Waiting for CatalystInstance...");
    }
}
}
</code>```

I am calling this module in componentDidMount() in following way:

```<code>componentDidMount() {
     NetInfo.addEventListener(
        'change',
        this._handleConnectionInfoChange
    );
    NetInfo.fetch().done(
       (connectionInfo) => { this.setState({connectionInfo}); }
    );
    GpsServiceLocation.checkLocation(this.state.message).catch((error)=>{});
    }
</code>```

Event listener for location updates

```<code>constructor(props) {
      if (!this.evEmitter) {
      // Register Listener Callback - has to be removed later
       this.evEmitter = DeviceEventEmitter.addListener('locationChanged', this.onLocationChange.bind(this));
    }
   }
</code>```

Listener function

```<code>onLocationChange (e: Event) {
         NetInfo.fetch().done(
       (connectionInfo) => {

  if(connectionInfo != 'NONE'){
    if(e.Latitude != 0 && e.Longitude != 0){
             fetch('https://maps.googleapis.com/maps/api/distancematrix/json?origins='+e.Latitude+','+e.Longitude+'&destinations='+destLatlng+'&mode=walking&key=<key>')
                .then((responseData) => responseData.json())
                .done((responseData)=>{
                     ...
                });
         }
      }
   }
   }
</code>```

Any suggestion appreciated.

答:
I found the cause of issue. It was happening due to fetch(). If you are using fetch() and internet connection lost while app in background then fetch() method fails due to Network error.

I added catch() in fetch() to handle network related errors. Below is syntax.

```<code>     fetch('https://maps.googleapis.com/maps/api/distancematrix/json?origins='+e.Latitude+','+e.Longitude+'&destinations='+destLatlng+'&mode=walking&key=<key>')
            .then((responseData) => responseData.json())
            .done((responseData)=>{
                 ...
     }).catch((error)=>{
         //handle your error here
     });
</code>```

Body:
We are working on react native and we implemented NetInfo event listener to check internet connectivity.

We are also calling fetch() on events to get data from google api. When app is in background and if internet connection lost then app is getting crashed with following error:

ReactNativeJS: Network request failed
E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
E AndroidRuntime: Process: com.example, PID: 30344
E AndroidRuntime: com.facebook.react.common.JavascriptException: Network request failed, stack:
E AndroidRuntime: onerror@25623:21
E AndroidRuntime: dispatchEvent@10670:19
E AndroidRuntime: setReadyState@27824:19
E AndroidRuntime: __didCompleteResponse@27660:19
E AndroidRuntime: <unknown>@27764:57
E AndroidRuntime: emit@9771:28
E AndroidRuntime: __callFunction@7571:39
E AndroidRuntime: <unknown>@7443:21
E AndroidRuntime: guard@7381:3
E AndroidRuntime: callFunctionReturnFlushedQueue@7442:6
E AndroidRuntime:
E AndroidRuntime: at com.facebook.react.modules.core.ExceptionsManagerModule.showOrThrowError(ExceptionsManagerModule.java:97)
E AndroidRuntime: at com.facebook.react.modules.core.ExceptionsManagerModule.reportFatalException(ExceptionsManagerModule.java:81)
E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
E AndroidRuntime:        at com.facebook.react.bridge.BaseJavaModule$JavaMethod.invoke(BaseJavaModule.java:318)
E AndroidRuntime:        at com.facebook.react.cxxbridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
E AndroidRuntime:        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
E AndroidRuntime:        at android.os.Handler.handleCallback(Handler.java:739)
E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:95)
E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
E AndroidRuntime:        at java.lang.Thread.run(Thread.java:818)
I ReactNativeJS: auth/network-request-failed
I ReactNativeJS: A network error (such as timeout, interrupted connection or unreachable host) has occurred.
W ActivityManager:   Force finishing activity com.example/.MainActivity

I have created android react native module to get GPS current location using NETWORK_PROVIDER.

public class GpsLocationCheckModule extends ReactContextBaseJavaModule implements LocationListener{
private Promise promiseCallback;
public boolean gps_enabled = false;
private ReactApplicationContext mReactContext;
private Activity currentActivity;
private static final String SETTINGS_FAILURE = "SETTINGS_FAILURE";
private LocationManager locationManager;
public static final String TAG = GpsLocationCheckModule.class.getSimpleName();
private String messageText;
private Location location;
private boolean isPopUpDisplayed = false;

public GpsLocationCheckModule(ReactApplicationContext reactContext) {
    super(reactContext);
    //reactContext.addActivityEventListener(mActivityEventListener);
    mReactContext = reactContext;
   reactContext.addActivityEventListener(mActivityEventListener);
}

@Override
public String getName() {
    return "GpsServiceLocation"; //this will be use at JS side.
}

@ReactMethod
public void checkLocation(String message, Promise promise) {
    currentActivity = getCurrentActivity();
    promiseCallback=promise;
    messageText= message;
    Log.i(TAG,"check location");
    locationManager = (LocationManager)mReactContext.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0, this);
    boolean gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if(!gps_enabled){
        if(!isPopUpDisplayed){
            isPopUpDisplayed = true;
            Log.i(TAG,"checklocatoin disabled" + Boolean.toString(isPopUpDisplayed));
            displayPromptForEnablingGPS(currentActivity,messageText,promiseCallback);
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i(TAG,"location changed");
    String msg = "New Latitude: " + location.getLatitude()
            + "New Longitude: " + location.getLongitude();
    Log.i(TAG,msg);
    WritableMap params = Arguments.createMap();
    params.putDouble("Longitude", location.getLongitude());
    params.putDouble("Latitude", location.getLatitude());
    //locationManager.removeUpdates(this);
     Log.i(TAG,"removed");
   sendEvent(mReactContext, "locationChanged", params);
}

@Override
public void onProviderDisabled(String provider) {
    Log.i(TAG,"disabled");
    Log.i(TAG,"ispopup disabled" + Boolean.toString(isPopUpDisplayed));
    if(!isPopUpDisplayed){
        isPopUpDisplayed = true;
        Log.i(TAG,"ispopup inside disabled" + Boolean.toString(isPopUpDisplayed));
        displayPromptForEnablingGPS(currentActivity,messageText,promiseCallback);
    }
}

@Override
public void onProviderEnabled(String provider) {
    Log.i(TAG,"enabled");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.i(TAG,"status changed");
    // TODO Auto-generated method stub

}

private void displayPromptForEnablingGPS(final Activity activity, final String message, final Promise promise) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final String action = android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS;

    builder.setMessage(Html.fromHtml(message))
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int id) {
                            activity.startActivityForResult(new Intent(action), 1);
                            dialogInterface.dismiss();
                        }
                    })
            .setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int id) {
                            popupRejected();
                            dialogInterface.cancel();
                        }
                    });
    builder.create().show();
}

private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        currentActivity = activity;
        checkLocationService(true);
    }
};

public void checkLocationService(Boolean status){
    WritableMap map = Arguments.createMap();
    map.putString("status", "success");
    isPopUpDisplayed=false;
    Log.i(TAG,"ispopup checklocation" + Boolean.toString(isPopUpDisplayed));
    if(promiseCallback != null){
        promiseCallback.resolve(map);
        promiseCallback = null;
    }
}
public void popupRejected(){
    isPopUpDisplayed = false;
    Log.i(TAG,"ispopup rejected" + Boolean.toString(isPopUpDisplayed));
    if(promiseCallback != null){
        promiseCallback.reject(SETTINGS_FAILURE,"Gps enabling failed");
    }
}

 /*
 * Internal function for communicating with JS
 */
private void sendEvent(ReactContext reactContext,
    String eventName, @Nullable WritableMap params) {
    if (reactContext.hasActiveCatalystInstance()) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    } else {
        Log.i(TAG, "Waiting for CatalystInstance...");
    }
}
}

I am calling this module in componentDidMount() in following way:

componentDidMount() {
     NetInfo.addEventListener(
        'change',
        this._handleConnectionInfoChange
    );
    NetInfo.fetch().done(
       (connectionInfo) => { this.setState({connectionInfo}); }
    );
    GpsServiceLocation.checkLocation(this.state.message).catch((error)=>{});
    }

Event listener for location updates

constructor(props) {
      if (!this.evEmitter) {
      // Register Listener Callback - has to be removed later
       this.evEmitter = DeviceEventEmitter.addListener('locationChanged', this.onLocationChange.bind(this));
    }
   }

Listener function

onLocationChange (e: Event) {
         NetInfo.fetch().done(
       (connectionInfo) => {

  if(connectionInfo != 'NONE'){
    if(e.Latitude != 0 && e.Longitude != 0){
             fetch('https://maps.googleapis.com/maps/api/distancematrix/json?origins='+e.Latitude+','+e.Longitude+'&destinations='+destLatlng+'&mode=walking&key=<key>')
                .then((responseData) => responseData.json())
                .done((responseData)=>{
                     ...
                });
         }
      }
   }
   }

Any suggestion appreciated.

Body:
I found the cause of issue. It was happening due to fetch(). If you are using fetch() and internet connection lost while app in background then fetch() method fails due to Network error.

I added catch() in fetch() to handle network related errors. Below is syntax.

     fetch('https://maps.googleapis.com/maps/api/distancematrix/json?origins='+e.Latitude+','+e.Longitude+'&destinations='+destLatlng+'&mode=walking&key=<key>')
            .then((responseData) => responseData.json())
            .done((responseData)=>{
                 ...
     }).catch((error)=>{
         //handle your error here
     });


来源: stackexchange

问:
Swift: how to hide back button on the first view controllers of tab bar controller?
My Tab Bar Controller controls 5 view controllers and I want that in those 5 main pages all the back buttons are disabled and not visible. How can I do that correctly? I have tried all Swift commands seen here in SO but none has worked up to now.

I have tried with

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true
}

override func viewWillAppear(animated: Bool) {
    self.navigationItem.hidesBackButton = true
}
</code>```

but they don't work. I have also tried with

self.tabBarController?.navigationItem.hidesBackButton = true

but this is the strange result

答:
To remove the "back" button from the navigation bar, you can create a UITabBarController class for your UITabBarController in the storyboard, and in that class, inside the ViewDidLoad() method, you can call

```<code>self.navigationItem.hidesBackButton = true
</code>```

This will remove the back button.

ContentLicense: CC BY-SA 3.0

Body:
My Tab Bar Controller controls 5 view controllers and I want that in those 5 main pages all the back buttons are disabled and not visible. How can I do that correctly? I have tried all Swift commands seen here in SO but none has worked up to now.

I have tried with

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true
}

override func viewWillAppear(animated: Bool) {
    self.navigationItem.hidesBackButton = true
}

but they don't work. I have also tried with

self.tabBarController?.navigationItem.hidesBackButton = true

but this is the strange result

Body:
To remove the "back" button from the navigation bar, you can create a UITabBarController class for your UITabBarController in the storyboard, and in that class, inside the ViewDidLoad() method, you can call

self.navigationItem.hidesBackButton = true

This will remove the back button.


问:
How to disable focus for an option in `dijit/form/Select`?
I need to change behavior for a widget dijit/form/Select.

Widget should not allow focus (from mouse or using the keyboard) for options which have property disabled: true.

I would like to know if you can point me out how to achieve this result.

require([
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(Select, win) {
  var select = new Select({
    name: 'select2',
    options: [{
        label: 'Swedish Cars',
        value: '',
        disabled: true
      },
      {
        label: 'Volvo',
        value: 'volvo'
      },
      {
        label: 'Saab',
        value: 'saab',
        selected: true
      },
      {
        label: 'German Cars',
        value: '',
        disabled: true
      },
      {
        label: 'Mercedes',
        value: 'mercedes'
      },
      {
        label: 'Audi',
        value: 'audi'
      }
    ]
  }, 'select');

  select.on('change', function(evt) {
    console.log('myselect_event');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body></code>```

答:
I was able to solve this issue using a monkey patch.

The solution consist into:

Adding markup in label so we can customize the look.

Adding property disabled:true in item options, so item won't fire onChange.

Disabling focus on group item when mouse and keyboard are used.

I still very interesting to know if another better/cleaner solutions exists.

  require([
    'dijit/form/Select',
    'dojo/_base/window',
    'dojo/domReady!'
  ], function(Select, win) {
    var select = new Select({
      name: 'select2',
      options: [{
        label: 'Swedish Cars',
        value: '',
        group: true,
        disabled: true
      }, {
        label: 'Volvo',
        value: 'volvo'
      }, {
        label: 'Saab',
        value: 'saab',
        selected: true
      }, {
        label: 'German Cars',
        value: '',
        group: true,
        disabled: true
      }, {
        label: 'Mercedes',
        value: 'mercedes'
      }, {
        label: 'Audi',
        value: 'audi'
      }]
    }, 'select');

    select.on('change', function(value) {
      alert(value);
    });

    select.dropDown._onUpArrow = function() {
      this.dropDown.focusPrev()
    }.bind(select);

    select.dropDown._onDownArrow = function() {
      this.dropDown.focusNext()
    }.bind(select);

    select.dropDown.focusNext = function() {
      var next = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, 1);
      var nextSuccessive;
      var nextFinal;
      if (next.option.group) {
        var next = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, 1);
        this.dropDown.focusChild(next);
        nextSuccessive = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, 1);
        nextFinal = nextSuccessive;
      } else {
        nextFinal = next;
      }
      this.dropDown.focusChild(nextFinal);
    }.bind(select);

    select.dropDown.focusPrev = function() {
      var prev = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, -1);
      var prevSuccessive;
      var prevFinal;
      if (prev.option.group) {
        var prev = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, -1);
        this.dropDown.focusChild(prev);
        prevSuccessive = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, -1);
        prevFinal = prevSuccessive;
      } else {
        prevFinal = prev;
      }
      this.dropDown.focusChild(prevFinal, true);
    }.bind(select);

    select.dropDown.onItemHover = function( /*MenuItem*/ item) {
      if (item.option.group) {
        item._set("hovering", false);
        console.log('skip hover');
        return;
      }

      if (this.activated) {
        this.set("selected", item);
        if (item.popup && !item.disabled && !this.hover_timer) {
          this.hover_timer = this.defer(function() {
            this._openItemPopup(item);
          }, this.popupDelay);
        }
      } else if (this.passivePopupDelay < Infinity) {
        if (this.passive_hover_timer) {
          this.passive_hover_timer.remove();
        }
        this.passive_hover_timer = this.defer(function() {
          this.onItemClick(item, {
            type: "click"
          });
        }, this.passivePopupDelay);
      }

      this._hoveredChild = item;

      item._set("hovering", true);
    }.bind(select.dropDown);

    select.dropDown._onItemFocus = function( /*MenuItem*/ item) {
      if (item.option.group) {
        return;
      }
      if (this._hoveredChild && this._hoveredChild != item) {
        this.onItemUnhover(this._hoveredChild);
      }
      this.set("selected", item);
    }.bind(select.dropDown);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body></code>```

Body:
I need to change behavior for a widget dijit/form/Select.

Widget should not allow focus (from mouse or using the keyboard) for options which have property disabled: true.

I would like to know if you can point me out how to achieve this result.

require([
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(Select, win) {
  var select = new Select({
    name: 'select2',
    options: [{
        label: 'Swedish Cars',
        value: '',
        disabled: true
      },
      {
        label: 'Volvo',
        value: 'volvo'
      },
      {
        label: 'Saab',
        value: 'saab',
        selected: true
      },
      {
        label: 'German Cars',
        value: '',
        disabled: true
      },
      {
        label: 'Mercedes',
        value: 'mercedes'
      },
      {
        label: 'Audi',
        value: 'audi'
      }
    ]
  }, 'select');

  select.on('change', function(evt) {
    console.log('myselect_event');
  });
});

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

Body:
I was able to solve this issue using a monkey patch.

The solution consist into:

Adding markup in label so we can customize the look.

Adding property disabled:true in item options, so item won't fire onChange.

Disabling focus on group item when mouse and keyboard are used.

I still very interesting to know if another better/cleaner solutions exists.

  require([
    'dijit/form/Select',
    'dojo/_base/window',
    'dojo/domReady!'
  ], function(Select, win) {
    var select = new Select({
      name: 'select2',
      options: [{
        label: '<i>Swedish Cars</i>',
        value: '',
        group: true,
        disabled: true
      }, {
        label: 'Volvo',
        value: 'volvo'
      }, {
        label: 'Saab',
        value: 'saab',
        selected: true
      }, {
        label: '<i>German Cars</i>',
        value: '',
        group: true,
        disabled: true
      }, {
        label: 'Mercedes',
        value: 'mercedes'
      }, {
        label: 'Audi',
        value: 'audi'
      }]
    }, 'select');

    select.on('change', function(value) {
      alert(value);
    });

    select.dropDown._onUpArrow = function() {
      this.dropDown.focusPrev()
    }.bind(select);

    select.dropDown._onDownArrow = function() {
      this.dropDown.focusNext()
    }.bind(select);

    select.dropDown.focusNext = function() {
      var next = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, 1);
      var nextSuccessive;
      var nextFinal;
      if (next.option.group) {
        var next = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, 1);
        this.dropDown.focusChild(next);
        nextSuccessive = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, 1);
        nextFinal = nextSuccessive;
      } else {
        nextFinal = next;
      }
      this.dropDown.focusChild(nextFinal);
    }.bind(select);

    select.dropDown.focusPrev = function() {
      var prev = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, -1);
      var prevSuccessive;
      var prevFinal;
      if (prev.option.group) {
        var prev = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, -1);
        this.dropDown.focusChild(prev);
        prevSuccessive = this.dropDown._getNextFocusableChild(this.dropDown.focusedChild, -1);
        prevFinal = prevSuccessive;
      } else {
        prevFinal = prev;
      }
      this.dropDown.focusChild(prevFinal, true);
    }.bind(select);

    select.dropDown.onItemHover = function( /*MenuItem*/ item) {
      if (item.option.group) {
        item._set("hovering", false);
        console.log('skip hover');
        return;
      }

      if (this.activated) {
        this.set("selected", item);
        if (item.popup && !item.disabled && !this.hover_timer) {
          this.hover_timer = this.defer(function() {
            this._openItemPopup(item);
          }, this.popupDelay);
        }
      } else if (this.passivePopupDelay < Infinity) {
        if (this.passive_hover_timer) {
          this.passive_hover_timer.remove();
        }
        this.passive_hover_timer = this.defer(function() {
          this.onItemClick(item, {
            type: "click"
          });
        }, this.passivePopupDelay);
      }

      this._hoveredChild = item;

      item._set("hovering", true);
    }.bind(select.dropDown);

    select.dropDown._onItemFocus = function( /*MenuItem*/ item) {
      if (item.option.group) {
        return;
      }
      if (this._hoveredChild && this._hoveredChild != item) {
        this.onItemUnhover(this._hoveredChild);
      }
      this.set("selected", item);
    }.bind(select.dropDown);
  });

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body>


问:
Can i use a simpleType multiple Times?
I use this simpleType multiple times in my xsd:

```<code><xs:simpleType>
    <xs:restriction base="xs:string">
        <xs:pattern value="[0-9a-zA-Z]{3}" />
    </xs:restriction>
</xs:simpleType>
</code>```

Is there a way to define it once and then use it multiple times?

答:
Yes there is. Just give it a name.</p>

```<code><xsd:simpleType name="myType">
...
</xsd:simpleType>

<xsd:element type="myType" .../>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Can i use a simpleType multiple Times?

Body:
I use this simpleType multiple times in my xsd:

<xs:simpleType>
    <xs:restriction base="xs:string">
        <xs:pattern value="[0-9a-zA-Z]{3}" />
    </xs:restriction>
</xs:simpleType>

Is there a way to define it once and then use it multiple times?

Body:
Yes there is. Just give it a name.

<xsd:simpleType name="myType">
...
</xsd:simpleType>

<xsd:element type="myType" .../>


问:
how to implement timer for quiz game in android
I am working on creating an android quiz game. I want to implement timer for each level to calculate how fast the user can answer all the questions. between each level there is an activity which i want to show the time taken to answer the quiz in the previous level before proceed into the next level. Can I get a guide on how to implement this? Thank you in advance</p>

答:
```<code>You can do something like this, when the user starts quiz and enters into your first level, then inside onCreate take start time like this:

        Calendar calendar;
        SimpleDateFormat df;
        String template = "yyyy-MM-dd HH:mm:ss";
        calendar = Calendar.getInstance();
        df = new SimpleDateFormat(template, Locale.getDefault());

        //this will give you the start time
        String startTime = df.format(calendar.getTime());

        //when user finishes up the level again record the finish time
        String finishTime = df.format(calendar.getTime());

       //then compare the two times
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = df.parse(startTime);
            d2 = df.parse(finishTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

       //in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
</code>```

Hope it helps!!

Body:
You can do something like this, when the user starts quiz and enters into your first level, then inside onCreate take start time like this:

        Calendar calendar;
        SimpleDateFormat df;
        String template = "yyyy-MM-dd HH:mm:ss";
        calendar = Calendar.getInstance();
        df = new SimpleDateFormat(template, Locale.getDefault());

        //this will give you the start time
        String startTime = df.format(calendar.getTime());

        //when user finishes up the level again record the finish time
        String finishTime = df.format(calendar.getTime());

       //then compare the two times
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = df.parse(startTime);
            d2 = df.parse(finishTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

       //in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);

Hope it helps!!


问:
How do I detect an internet connection and then add an anchor (link) to an element, such as a div, or not add it if there is no connection
I am developing a basic HTML app for ipad. It will be used offline, but when it is online, I want an element on the page to have a link attached to it. I am a complete newb to javascript, so any help will be appreciated.

I have managed to add the link to the element when online, but when offline, it is still there. What do I have wrong here?

var isOnline = window.navigator.onLine;
var a = document.getElementById('webviewBtn');
if (isOnline) {

 a.setAttribute("href", "http://pixelwizard.com.au");
} else {

 a.setAttribute("href", "#");
}```

答: If you don't want an  element to be a link, don't give it an href. You're setting its href to "#" if the device is offline, which makes it appear as a clickable link.

Body: If you don't want an <a> element to be a link, don't give it an href. You're setting its href to "#" if the device is offline, which makes it appear as a clickable link.


问:
Image from URL to PHP upload Function
I've looked all over and can't seem to find the solution to my problem. Any help/pointers will be much appreciated.

I'm attempting to pull an image from a URL source (i.e. https://scontent.xx.fbcdn.net/v/t1.0-9/17990738_10154386783672539_8144154100714177483_n.jpg?oh=8c1c2fb46e8626f58fd76662f3fe6673&oe=59AAE570)

the URL is coming from a larger CURL and I'm parsing out the JSON results into a PHP object array

I can pull the url but when I try and pass the image information to my upload function, it fails both of my checks (image size & image type) and therefore fails to upload

the function below works when manually uploading a file via the HTML file uploader. below is what is typically passd

```<code>$file = $_FILES['file'];
</code>```

Here's the uploader function

```<code>function upload($file)
{
  $target_dir= "../admin/media/";
  $target_file = $target_dir . basename($file['name']);
  $random_number = rand(1000,100000);
  $uploadOk = 1;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

  //Check that file is not empty
  $check = getimagesize($file['tmp_name']);
  if($check !== false) {
    $uploadOk = 1;
  } else {
    $uploadOk = 0; echo "no image size";
  }

  //Check that file is an image
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
      $uploadOk = 0; echo "not an image file";
  }

  $img_info = getimagesize($file['tmp_name']);
  $width = $img_info[0];
  $height = $img_info[1];
  $ratio = $width / $height;

  switch ($img_info[2]) {
    case IMAGETYPE_GIF  : $src = imagecreatefromgif($file['tmp_name']);  break;
    case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($file['tmp_name']); break;
    case IMAGETYPE_PNG  : $src = imagecreatefrompng($file['tmp_name']);  break;
  }

  if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
  // if everything is ok, try to upload file
  } else {
    //UPLOAD ORIGINAL VERSION
    $file_name = $random_number."-".$file['name']."-original";
    $file_name = slugify($file_name);

    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $width, $height, $width, $height);
    //string the target folder and file name together
    $target_file = $target_dir . $file_name;

    //upload image to server
    imagejpeg($tmp, $target_file . ".jpg");
    $file_name_original = $file_name . ".jpg";

    //UPLOAD THUMBNAIL VERSION
    $file_name = $random_number."-".$file['name']."-thumbnail";
    $file_name = slugify($file_name);

    $min_dim_thumbnail = 300;
    if( $ratio > 1) {
            $new_width = $min_dim_thumbnail*$ratio;
            $new_height = $min_dim_thumbnail;
            $x_center = ($new_width/2) - 150;
            $y_center = 0;
        } else {
            $new_width = $min_dim_thumbnail;
            $new_height = $min_dim_thumbnail/$ratio;
            $x_center = 0;
            $y_center = ($new_height/2) - 150;
        }

    $tmp = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    $crop = imagecrop($tmp, ['x' => $x_center, 'y' => $y_center, 'width' => '300', 'height' => '300']);

    $target_file = $target_dir . $file_name;

    imagejpeg($crop, $target_file . ".jpg");
    $file_name_thumbnail = $file_name . ".jpg";

    //UPLOAD BANNER VERSION
    $file_name = $random_number."-".$file['name']."-banner";
    $file_name = slugify($file_name);

    $min_dim_height = 450;
    $min_dim_width = 800;
    if( $ratio > 1.78) {
            $new_width = $min_dim_height*$ratio;
            $new_height = $min_dim_height;
            $x_center = ($new_width/2) - 400;
            $y_center = 0;
        } else {
            $new_width = $min_dim_width;
            $new_height = $min_dim_width/$ratio;
            $x_center = 0;
            $y_center = ($new_height/2) - 225;
        }

    $tmp = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    $crop = imagecrop($tmp, ['x' => $x_center, 'y' => $y_center, 'width' => '800', 'height' => '450']);

    $target_file = $target_dir . $file_name;

    imagejpeg($crop, $target_file . ".jpg");
    $file_name_banner = $file_name . ".jpg";

  }
  //return the slugified file name to the calling function
  return array($file_name_original, $file_name_banner, $file_name_thumbnail);
}?>
</code>```

Here's the slugify Function

```<code><?php
//FUNCTION FOR RETURNING SLUG VALUE FROM A STRING
function slugify($text)
{
    // replace non letter or digits by -
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    // transliterate
       //$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    // remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);
    // trim
    $text = trim($text, '-');
    // remove duplicate -
    $text = preg_replace('~-+~', '-', $text);
    // lowercase
    $text = strtolower($text);

    if (empty($text)) {
        return 'n-a';
    }
    return $text;
}?>
</code>```

And here's the code I'm working with in a separate php file that's attempting to process the upload

```<code>    $image_url = $value->{'cover'}->{'source'}; //define image source
    $file = file_get_contents($image_url);
    $file['tmp_name'] = $image_url;
    $file['name'] = basename($files['tmp_name']);
    list($image_original, $image_banner, $image_thumbnail) = upload($file); //pass PHP image to our upload function
</code>```

Thank you in advance.

答:
Likely you just have to assign the same keys instead of the default $_FILES array:

```<code># Create the two elements that are required for the function
$files['tmp_name'] = 'https://s-media-cache-ak0.pinimg.com/736x/c6/4c/e0/c64ce05bf01ccb3ea8af44de5980cbe4.jpg';
$files['name'] = basename($files['tmp_name']);
# Do the regular upload
upload($files);
</code>```

I haven't tried it, but in theory it should work.

Title: Image from URL to PHP upload Function

Body:
I've looked all over and can't seem to find the solution to my problem. Any help/pointers will be much appreciated.

I'm attempting to pull an image from a URL source (i.e. https://scontent.xx.fbcdn.net/v/t1.0-9/17990738_10154386783672539_8144154100714177483_n.jpg?oh=8c1c2fb46e8626f58fd76662f3fe6673&oe=59AAE570)

the URL is coming from a larger CURL and I'm parsing out the JSON results into a PHP object array

I can pull the url but when I try and pass the image information to my upload function, it fails both of my checks (image size & image type) and therefore fails to upload

the function below works when manually uploading a file via the HTML file uploader. below is what is typically passd

$file = $_FILES['file'];

Here's the uploader function

function upload($file)
{
  $target_dir= "../admin/media/";
  $target_file = $target_dir . basename($file['name']);
  $random_number = rand(1000,100000);
  $uploadOk = 1;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

  //Check that file is not empty
  $check = getimagesize($file['tmp_name']);
  if($check !== false) {
    $uploadOk = 1;
  } else {
    $uploadOk = 0; echo "no image size";
  }

  //Check that file is an image
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
      $uploadOk = 0; echo "not an image file";
  }

  $img_info = getimagesize($file['tmp_name']);
  $width = $img_info[0];
  $height = $img_info[1];
  $ratio = $width / $height;

  switch ($img_info[2]) {
    case IMAGETYPE_GIF  : $src = imagecreatefromgif($file['tmp_name']);  break;
    case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($file['tmp_name']); break;
    case IMAGETYPE_PNG  : $src = imagecreatefrompng($file['tmp_name']);  break;
  }

  if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
  // if everything is ok, try to upload file
  } else {
    //UPLOAD ORIGINAL VERSION
    $file_name = $random_number."-".$file['name']."-original";
    $file_name = slugify($file_name);

    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $width, $height, $width, $height);
    //string the target folder and file name together
    $target_file = $target_dir . $file_name;

    //upload image to server
    imagejpeg($tmp, $target_file . ".jpg");
    $file_name_original = $file_name . ".jpg";

    //UPLOAD THUMBNAIL VERSION
    $file_name = $random_number."-".$file['name']."-thumbnail";
    $file_name = slugify($file_name);

    $min_dim_thumbnail = 300;
    if( $ratio > 1) {
            $new_width = $min_dim_thumbnail*$ratio;
            $new_height = $min_dim_thumbnail;
            $x_center = ($new_width/2) - 150;
            $y_center = 0;
        } else {
            $new_width = $min_dim_thumbnail;
            $new_height = $min_dim_thumbnail/$ratio;
            $x_center = 0;
            $y_center = ($new_height/2) - 150;
        }

    $tmp = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    $crop = imagecrop($tmp, ['x' => $x_center, 'y' => $y_center, 'width' => '300', 'height' => '300']);

    $target_file = $target_dir . $file_name;

    imagejpeg($crop, $target_file . ".jpg");
    $file_name_thumbnail = $file_name . ".jpg";

    //UPLOAD BANNER VERSION
    $file_name = $random_number."-".$file['name']."-banner";
    $file_name = slugify($file_name);

    $min_dim_height = 450;
    $min_dim_width = 800;
    if( $ratio > 1.78) {
            $new_width = $min_dim_height*$ratio;
            $new_height = $min_dim_height;
            $x_center = ($new_width/2) - 400;
            $y_center = 0;
        } else {
            $new_width = $min_dim_width;
            $new_height = $min_dim_width/$ratio;
            $x_center = 0;
            $y_center = ($new_height/2) - 225;
        }

    $tmp = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    $crop = imagecrop($tmp, ['x' => $x_center, 'y' => $y_center, 'width' => '800', 'height' => '450']);

    $target_file = $target_dir . $file_name;

    imagejpeg($crop, $target_file . ".jpg");
    $file_name_banner = $file_name . ".jpg";

  }
  //return the slugified file name to the calling function
  return array($file_name_original, $file_name_banner, $file_name_thumbnail);
}?>

Here's the slugify Function

<?php
//FUNCTION FOR RETURNING SLUG VALUE FROM A STRING
function slugify($text)
{
    // replace non letter or digits by -
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    // transliterate
       //$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    // remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);
    // trim
    $text = trim($text, '-');
    // remove duplicate -
    $text = preg_replace('~-+~', '-', $text);
    // lowercase
    $text = strtolower($text);

    if (empty($text)) {
        return 'n-a';
    }
    return $text;
}?>

And here's the code I'm working with in a separate php file that's attempting to process the upload

    $image_url = $value->{'cover'}->{'source'}; //define image source
    $file = file_get_contents($image_url);
    $file['tmp_name'] = $image_url;
    $file['name'] = basename($files['tmp_name']);
    list($image_original, $image_banner, $image_thumbnail) = upload($file); //pass PHP image to our upload function

Thank you in advance.

Body:
Likely you just have to assign the same keys instead of the default $_FILES array:

# Create the two elements that are required for the function
$files['tmp_name'] = 'https://s-media-cache-ak0.pinimg.com/736x/c6/4c/e0/c64ce05bf01ccb3ea8af44de5980cbe4.jpg';
$files['name'] = basename($files['tmp_name']);
# Do the regular upload
upload($files);

I haven't tried it, but in theory it should work.


问:
Seed with paperclip using image url
I'm using Paperclip and I want to upload the image on S3 for the User's avatar.

My CSV

```<code>username    avatar_url
foo         https://s3.amazonaws.com/foo/seed/10215716104_e09765dabd_z.jpg
</code>```

I was going to follow this tutorial to create a CSV, along with this SO question (for Paperclip seeding), so something like this:

```<code>require 'csv'

csv_text = File.read(Rails.root.join('lib', 'seeds', 'user.csv'))
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
csv.each do |row|
  u = User.new
  u.username = row['username']
  u.avatar = File.open(row['avatar_url'])
  u.save
end
</code>```

However, when I try this in the console, like this:

```<code>User.create(username: 'foo', avatar: File.new("https://s3.amazonaws.com/foo/seed/10215716104_e09765dab"))
</code>```

I get an error:

```<code>Errno::ENOENT: No such file or directory @ rb_sysopen - https://s3.amazonaws.com/foo/seed/10215716104_e09765dabd_z.jpg
</code>```

Is it possible to seed with images on S3?

答:
Here is how I'm using it:

```<code>class User < ActiveRecord::Base
  has_attached_file :avatar, ...
end

user = User.new
user.avatar = URI.parse(url_goes_here)
user.save
</code>```

Attachment downloaded from a URL

Title: Seed with paperclip using image url

Body:
I'm using Paperclip and I want to upload the image on S3 for the User's avatar.

My CSV

username    avatar_url
foo         https://s3.amazonaws.com/foo/seed/10215716104_e09765dabd_z.jpg

I was going to follow this tutorial to create a CSV, along with this SO question (for Paperclip seeding), so something like this:

require 'csv'

csv_text = File.read(Rails.root.join('lib', 'seeds', 'user.csv'))
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
csv.each do |row|
  u = User.new
  u.username = row['username']
  u.avatar = File.open(row['avatar_url'])
  u.save
end

However, when I try this in the console, like this:

User.create(username: 'foo', avatar: File.new("https://s3.amazonaws.com/foo/seed/10215716104_e09765dab"))

I get an error:

Errno::ENOENT: No such file or directory @ rb_sysopen - https://s3.amazonaws.com/foo/seed/10215716104_e09765dabd_z.jpg

Is it possible to seed with images on S3?

Body:
Here is how I'm using it:

class User < ActiveRecord::Base
  has_attached_file :avatar, ...
end

user = User.new
user.avatar = URI.parse(url_goes_here)
user.save

Attachment downloaded from a URL


问:
Unable to run Hybrid application on remote server MFP 7.1
After migrate the remote server from MFP 6.3.0 to MFP 7.1. I am unable to run the application

MFP 7.1.0.00-20170330-0917

Eclipse Kepler SR 2

Log

```<code>06-06 12:53:56.233: D/NONE(6221): connectOnStartup
06-06 12:53:56.237: D/NONE(6221): establishSSLClientAuth
06-06 12:53:56.239: D/NONE(6221): establishSSLClientAuth isCertificateExists:  false
06-06 12:53:56.242: D/NONE(6221): Request [/apps/services/api/ITS/android/init]
06-06 12:53:56.243: W/NONE(6221): Note that if your application targets Android 3.0 (API level 11) or higher, WL.OptionsMenu might have no effect, depending on the device.
06-06 12:53:56.967: D/com.worklight.nativeandroid.common.WLUtils(6221): WLUtils.convertStringToJSON in WLUtils.java:495 :: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:56.971: D/wl.failResponse(6221): WLFailResponse.parseErrorFromResponse in WLFailResponse.java:103 :: Additional error information is not available for the current response and response text is: Error 500: java.lang.NullPointerException
06-06 12:53:56.971: D/wl.failResponse(6221): org.json.JSONException: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.nativeandroid.common.WLUtils.convertStringToJSON(WLUtils.java:496)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.parseErrorFromResponse(WLFailResponse.java:91)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.<init>(WLFailResponse.java:49)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.processFailureResponse(WLRequest.java:745)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.requestFinished(WLRequest.java:327)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequestSender.run(WLRequestSender.java:52)
06-06 12:53:56.971: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-06 12:53:56.971: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-06 12:53:56.971: D/wl.failResponse(6221):    at java.lang.Thread.run(Thread.java:818)
06-06 12:53:56.971: D/wl.certManager(6221): WLCertManager.clearKeystore in WLCertManager.java:258 :: Key store cleared.
06-06 12:53:56.976: D/wl.certManager(6221): WLCertManager.clearKeystore in WLCertManager.java:258 :: Key store cleared.
06-06 12:53:56.986: D/wl.request(6221): WLRequestSender.run in WLRequestSender.java:40 :: Sending request https://server-address/ITS/authorization/v1/clients/instance
06-06 12:53:57.637: D/com.worklight.nativeandroid.common.WLUtils(6221): WLUtils.convertStringToJSON in WLUtils.java:495 :: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:57.638: D/wl.failResponse(6221): WLFailResponse.parseErrorFromResponse in WLFailResponse.java:103 :: Additional error information is not available for the current response and response text is: Error 500: java.lang.NullPointerException
06-06 12:53:57.638: D/wl.failResponse(6221): org.json.JSONException: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.nativeandroid.common.WLUtils.convertStringToJSON(WLUtils.java:496)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.parseErrorFromResponse(WLFailResponse.java:91)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.<init>(WLFailResponse.java:49)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.processFailureResponse(WLRequest.java:745)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.requestFinished(WLRequest.java:327)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequestSender.run(WLRequestSender.java:52)
06-06 12:53:57.638: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-06 12:53:57.638: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-06 12:53:57.638: D/wl.failResponse(6221):    at java.lang.Thread.run(Thread.java:818)
06-06 12:53:57.640: D/wl.certManager(6221): WLCertManager.clearKeystore in WLCertManager.java:258 :: Key store cleared.
06-06 12:53:57.641: D/NONE(6221): Client registration failed with error: {"responseHeaders":{},"status":500,"responseText":"Error 500: java.lang.NullPointerException\n","errorCode":"UNRESPONSIVE_HOST","errorMsg":"The service is currently not available.","invocationContext":null}
06-06 12:53:57.642: I/chromium(6221): [INFO:CONSOLE(27)] "*******isCustomResponse []", source: file:///android_asset/www/default/js/PushAppRealmChallengeHandler.js (27)
06-06 12:53:57.645: E/NONE(6221): [/apps/services/api/ITS/android/init] failure. state: 500, response: undefined
06-06 12:53:57.654: E/NONE(6221): Client init failed. The service is currently not available.
</code>```

Any idea how to fix it..???

答:
The log says ""errorCode":"UNRESPONSIVE_HOST","errorMsg":"The service is currently not available."}

Verify your wlclient.properties to see if the hostname, context etc are proper. If so, verify your application logic to see if the relative URI for resources are proper.

Body:
After migrate the remote server from MFP 6.3.0 to MFP 7.1. I am unable to run the application

MFP 7.1.0.00-20170330-0917

Eclipse Kepler SR 2

Log

06-06 12:53:56.233: D/NONE(6221): connectOnStartup
06-06 12:53:56.237: D/NONE(6221): establishSSLClientAuth
06-06 12:53:56.239: D/NONE(6221): establishSSLClientAuth isCertificateExists:  false
06-06 12:53:56.242: D/NONE(6221): Request [/apps/services/api/ITS/android/init]
06-06 12:53:56.243: W/NONE(6221): Note that if your application targets Android 3.0 (API level 11) or higher, WL.OptionsMenu might have no effect, depending on the device.
06-06 12:53:56.967: D/com.worklight.nativeandroid.common.WLUtils(6221): WLUtils.convertStringToJSON in WLUtils.java:495 :: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:56.971: D/wl.failResponse(6221): WLFailResponse.parseErrorFromResponse in WLFailResponse.java:103 :: Additional error information is not available for the current response and response text is: Error 500: java.lang.NullPointerException
06-06 12:53:56.971: D/wl.failResponse(6221): org.json.JSONException: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.nativeandroid.common.WLUtils.convertStringToJSON(WLUtils.java:496)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.parseErrorFromResponse(WLFailResponse.java:91)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.<init>(WLFailResponse.java:49)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.processFailureResponse(WLRequest.java:745)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.requestFinished(WLRequest.java:327)
06-06 12:53:56.971: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequestSender.run(WLRequestSender.java:52)
06-06 12:53:56.971: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-06 12:53:56.971: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-06 12:53:56.971: D/wl.failResponse(6221):    at java.lang.Thread.run(Thread.java:818)
06-06 12:53:56.971: D/wl.certManager(6221): WLCertManager.clearKeystore in WLCertManager.java:258 :: Key store cleared.
06-06 12:53:56.976: D/wl.certManager(6221): WLCertManager.clearKeystore in WLCertManager.java:258 :: Key store cleared.
06-06 12:53:56.986: D/wl.request(6221): WLRequestSender.run in WLRequestSender.java:40 :: Sending request https://server-address/ITS/authorization/v1/clients/instance
06-06 12:53:57.637: D/com.worklight.nativeandroid.common.WLUtils(6221): WLUtils.convertStringToJSON in WLUtils.java:495 :: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:57.638: D/wl.failResponse(6221): WLFailResponse.parseErrorFromResponse in WLFailResponse.java:103 :: Additional error information is not available for the current response and response text is: Error 500: java.lang.NullPointerException
06-06 12:53:57.638: D/wl.failResponse(6221): org.json.JSONException: Input string does not contain brackets, or input string is invalid. The string is: Error 500: java.lang.NullPointerException
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.nativeandroid.common.WLUtils.convertStringToJSON(WLUtils.java:496)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.parseErrorFromResponse(WLFailResponse.java:91)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.api.WLFailResponse.<init>(WLFailResponse.java:49)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.processFailureResponse(WLRequest.java:745)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequest.requestFinished(WLRequest.java:327)
06-06 12:53:57.638: D/wl.failResponse(6221):    at com.worklight.wlclient.WLRequestSender.run(WLRequestSender.java:52)
06-06 12:53:57.638: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-06 12:53:57.638: D/wl.failResponse(6221):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-06 12:53:57.638: D/wl.failResponse(6221):    at java.lang.Thread.run(Thread.java:818)
06-06 12:53:57.640: D/wl.certManager(6221): WLCertManager.clearKeystore in WLCertManager.java:258 :: Key store cleared.
06-06 12:53:57.641: D/NONE(6221): Client registration failed with error: {"responseHeaders":{},"status":500,"responseText":"Error 500: java.lang.NullPointerException\n","errorCode":"UNRESPONSIVE_HOST","errorMsg":"The service is currently not available.","invocationContext":null}
06-06 12:53:57.642: I/chromium(6221): [INFO:CONSOLE(27)] "*******isCustomResponse []", source: file:///android_asset/www/default/js/PushAppRealmChallengeHandler.js (27)
06-06 12:53:57.645: E/NONE(6221): [/apps/services/api/ITS/android/init] failure. state: 500, response: undefined
06-06 12:53:57.654: E/NONE(6221): Client init failed. The service is currently not available.

Any idea how to fix it..???


问:
How to change background color of UITableViewCell using my own color combination
actually i have found some thread that asking question like mine.
but every solution that given in those thread can not be use in my code..
the last link i was read is
How to customize the background color of a UITableViewCell?

my problem is i just want to change my tableviewcell background color with my own color.
can somebody help me??

答: finnaly i found out how to solve this problem. but i was choose to use an image. I was declare my way to solve it in my another question in : is there somebody who made an application using background for tableview and tableviewcell?</p>


问:
What does this line mean in Brin/Page's 1998 paper?
I'm not sure if this belongs in SO, but I don't know what other SE site would be more appropriate.

In Brin and Page's paper "The Anatomy of a Large-Scale Hypertextual Web Search Engine", they describe the variable d in the PageRank algorithm as the probability that a random surfer requests a new random page. On the next line, they state:

One important variation is to only add the damping factor d to a
  single page, or a group of pages. This allows for personalization and
  can make it nearly impossible to deliberately mislead the system in
  order to get a higher ranking.

What does this mean? Why would they add the damping factor to only a single page?

Does it mean that the random surfer will keep following links until they arrive at a specific page? I don't think this makes sense because the random surfer can get stuck in a loop and never reach that specific page.

答:
The Wikipedia article on PageRank kind of explains the overall concept of the damping factor, but this forum post explains it better.

Eventually any web surfer is eventually going to get to a point where he/she gets bored and does something else.  The theory (assuming I understood the Wikipedia article correctly) is that while looking at a given page, there's an 85% chance that a user will click on one of the links to another page.  Therefore, the odds of viewing two pages in a row is 85%, the odds of viewing three pages is 72.25%, the odds of viewing four pages is 61.4%, etc.

Thus, if you have page A linking to page B and page B linking to page C:

A -> B -> C

then the popularity of page A has an 85% chance of causing page B to become popular, but only a 72.25% chance of making page C popular, because there's a 15% chance of the user randomly going to some other website instead at each of those decision points.

Without that fall-off, I think that every website in the world would eventually end up with an infinite page rank, because the page rank would propagate through every page to every other page like a tidal wave.  By damping the progression of page rank strength at each step, you ensure that sites linked from high-ranking sites get a rank boost, but not sites that happen to be reachable via a hundred hops.

The bit you're quoting is explained a bit more in their follow-on paper, in which they explain that they normally use a constant damping factor when calculating page rank, and assume that there is a 15% (1 - .85) probability of jumping to any arbitrary page in the world, with all possible pages getting those jumps equally, but that you can instead use a fixed set of target pages (or even a single web page) to receive all of those random jumps.  When you do that, you end up computing a very different page rank based on proximity to that particular page or group of pages.

For example, if the user has a particular page set as his/her browser's start page, you might assume that the user will click the home button and go back to that page when he or she gets bored.  Thus, pages linked closely from that page would have a higher personal page rank for that user.  You can create an even better personalized ranking by adding in things like the user's bookmarks, pages they visit frequently, etc.  And because rankings based on those limited sets of "restart pages" are personalized in this way, they cannot be easily manipulated by commercial interests, because nobody is likely to buy links from one of the five particular pages that happen to be in your bookmarks (or home page or whatever).


问:
$(document).ready() works but $.ready() does not
```<code>$(document).ready( function(){
    $(document).on('click', 'a[data-iframe-menu-entry="data-iframe-menu-entry"]', function(event) {
        alert('hola');
....
</code>```

vs

```<code>$.ready(function() {
    $(document).on('click', 'a[data-iframe-menu-entry="data-iframe-menu-entry"]', function(event) {
        alert('hola');
....
</code>```

$.ready() is supposed to be an alias, but it does not work for me. What is wrong?

答:
Correct form of alias is:</p>

```<code>$(function() {
   // Your code
});
</code>```

Body:
$(document).ready( function(){
    $(document).on('click', 'a[data-iframe-menu-entry="data-iframe-menu-entry"]', function(event) {
        alert('hola');
....

vs

$.ready(function() {
    $(document).on('click', 'a[data-iframe-menu-entry="data-iframe-menu-entry"]', function(event) {
        alert('hola');
....

$.ready() is supposed to be an alias, but it does not work for me. What is wrong?

Body:
Correct form of alias is:

$(function() {
   // Your code
});


问:
Rename property of an object inside array
This is my input JSON

```<code>{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}
</code>```

Expected output:

```<code>{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}
</code>```

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

答:
I just learned about += from an answer to another question. It works here too.

```<code>jq '.description[] |= (select(has("car_name")) += {"name":.car_name} | del(.car_name))'
</code>```

The select function selects the objects that meet the condition. Then we add to, and delete from, those objects.

Body:
This is my input JSON

{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Expected output:

{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

Body:
I just learned about += from an answer to another question. It works here too.

jq '.description[] |= (select(has("car_name")) += {"name":.car_name} | del(.car_name))'

The select function selects the objects that meet the condition. Then we add to, and delete from, those objects.


问:
How can I dynamically add a button to the last item in a list?
In Angular, I'm using the ng-repeat directive to print a list of items in an array. What I'd like to do is add a button to the right of the last item in the list. I'm not aware of a non jquery way of adding this dynamically.

Here is an image of what I currently have. My button gets pushed down the list when new things get added. I'd like to see that button on the right side of the last item in the list (here it is 'acculist').

Any ideas help! Thanks everyone.

Edit
The button must be present at all times. Initially there will be no items in the Shopping List, so the user must always have the ability to click the button to add items to a shopping list.

答:
```<code><div ng-app="my_app" ng-controller="my_Ctrl">
   <ul>
      <li ng-repeat="a in items">
         <span>{{a}}</span>
         <button ng-if="$last" value="Add" ng-click="additems()">Add</button>
       </li>
       <li ng-if="items.length===0">
          <button value="Add" ng-click="additems()">Add</button>
       </li>
    </ul>
</div>
</code>```

<p>angular </p>

```<code>  var app=angular.module("my_app",[]);
  app.controller("my_Ctrl",function($scope){
     $scope.items=["one","two","three"];
     $scope.additems=function(){
      $scope.items.push("New Items"+($scope.items.length+1));
     }
 })
</code>```

Body:
<div ng-app="my_app" ng-controller="my_Ctrl">
   <ul>
      <li ng-repeat="a in items">
         <span>{{a}}</span>
         <button ng-if="$last" value="Add" ng-click="additems()">Add</button>
       </li>
       <li ng-if="items.length===0">
          <button value="Add" ng-click="additems()">Add</button>
       </li>
    </ul>
</div>

angular

  var app=angular.module("my_app",[]);
  app.controller("my_Ctrl",function($scope){
     $scope.items=["one","two","three"];
     $scope.additems=function(){
      $scope.items.push("New Items"+($scope.items.length+1));
     }
 })


问:
not getting proper base_url in codeigniter app
i am getting this type of url when trying to access pages other than index page

```<code>http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home
</code>```

but url to access page must be

```<code>http://localhost:8012/health-care/index.php/home
</code>```

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

答:
Y0u have to change  this line

```<code>http://localhost:8012/health-care/index.php/home
</code>```

to this

```<code>$config['base_url'] = 'http//localhost:8012/health-care/';
</code>```

Please have a try.

Body:
i am getting this type of url when trying to access pages other than index page

http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home

but url to access page must be

http://localhost:8012/health-care/index.php/home

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

Body:
Y0u have to change  this line

http://localhost:8012/health-care/index.php/home

to this

$config['base_url'] = 'http//localhost:8012/health-care/';

Please have a try.


问:
Incorrect port number returned by $_SERVER['server_port']
Scenario: I'm working on a Apache web server with some PHP.  I point my browser at https://my.example.com/test.php that has the following lines of code in it:

```<code>```
<?php
print_r($_SERVER);
?>
```
</code>```

The value printed out for SERVER_PORT is 80, not 443.  But if I go to https://my.example.com:80/test.php the web server (Apache) barfs (An error occurred during a connection to my.example.com:80. SSL received a record that exceeded the maximum permissible length. Error code: ssl_error_rx_record_too_long).  If I go to https://my.example.com:443/test.php then the URL redirects to https://my.example.com/test.php with no errors or problems except that my PHP prints out that the server port is 80 instead of 443.

Here's the relevant section from the conf.d/ssl.conf file (I removed what I believe are extraneous directives out and replaced the actual IP address with the word IP_ADDRESS):

```<code>Listen IP_ADDRESS:443
<VirtualHost *:443>
        ServerName my.example.com
        ServerAlias my
        DocumentRoot "/path/to/document_root/htdocs"
        Options +Indexes
</VirtualHost>
</code>```

Here is the full print out of $_SERVER variable (with my server details redacted/changed to anonymous examples):

```<code>Array
(
    [HTTP_HOST] => my.example.com
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5
    [HTTP_ACCEPT_ENCODING] => gzip,deflate
    [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
    [HTTP_KEEP_ALIVE] => 115
    [HTTP_CONNECTION] => keep-alive
    [HTTP_COOKIE] => PHPSESSID=randomstring_yes_I'm_that_paranoid
    [PATH] => /sbin:/usr/sbin:/bin:/usr/bin
    [SERVER_SIGNATURE] =>
Apache/2.2.3 (Red Hat) Server at my.example.com Port 80

    [SERVER_SOFTWARE] => Apache/2.2.3 (Red Hat)
    [SERVER_NAME] => my.example.com
    [SERVER_ADDR] => IP_ADDRESS_1
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => IP_ADDRESS_2
    [DOCUMENT_ROOT] => /path/to/document_root/htdocs
    [SERVER_ADMIN] => admin@example.com
    [SCRIPT_FILENAME] => /path/to/document_root/htdocs/test.php
    [REMOTE_PORT] => 49178
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] =>
    [REQUEST_URI] => /test.php
    [SCRIPT_NAME] => /test.php
    [PHP_SELF] => /test.php
    [REQUEST_TIME] => 1292273758
)
</code>```

As you can see, the SERVER_PORT is 80 and $_SERVER['HTTPS'] isn't set.  According to the PHP docs, I thought it was supposed to be set to a non-empty value if the PHP script is accessed via HTTPS (which is what I'm doing).

Any idea what's going on?  I'm just the web developer - I don't manage this server but my server admin tells me everything is working but I would like to know why $_SERVER['SERVER_PORT'] is returning 80 instead of 443 when viewing an HTTPS URL.

EDIT: I've edited the above example to illustrate my results in printing out the entire $_SERVER variable.

EDIT 2: Trying https://my.example.com:443/test.php as suggested in the comments below does the same thing - SERVER_PORT is 80 and HTTPS isn't set (specifically trying this URL redirects to https://my.example.com/test.php).

EDIT 3: OK, I've posted what I believe is the answer to this below (TL;DR: moving the SSL directives inside the VirtualHost directive and changing that directive to reference my site using it's IP address rather than a wildcard appears to have resolved the problem).

答:
I seem to remember having this happen to me when I upgraded my apache a couple years ago.  It ended up being a bad SSLCipherSuite, IIRC.  Basically make sure you have a complete SSL configuration:

Do you have your ciphers, cert and key defined?  And SSLEngine On?  Something like this is required in your configuration minimally...

SSLEngine on

SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile /path/to/apache/conf/server.crt
SSLCertificateKeyFile /path/to/apache/conf/server.key

... and if you want to verify the client certificates, you also need something like:

SSLVerifyClient require
SSLVerifyDepth  10
SSLCACertificateFile /path/to/apache/conf/trustedpubkeys.crt

Good luck!

if you want to verify this is actually happening, fire up a sniffer like tcpdump or wireshark.  For tcpdump I'd use a commandline like ...

tcpdump -i eth0 -nn -s 1600 ip proto 17 and host IP_ADDRESS

(where IP_ADDRESS is the fqdn or dotted quad of your server)

Then get your $_SERVER var dump page, or a phpinfo() page, etc.

Your $_SERVER var dump shows your remote port, so you should be able to see which of your connections used that port, and whether it was connected to port 80 or 443.

Wireshark would let you do the same thing, if you're more of a GUI person.

Body:
Scenario: I'm working on a Apache web server with some PHP.  I point my browser at https://my.example.com/test.php that has the following lines of code in it:

<?php
print_r($_SERVER);
?>

The value printed out for SERVER_PORT is 80, not 443.  But if I go to https://my.example.com:80/test.php the web server (Apache) barfs (An error occurred during a connection to my.example.com:80. SSL received a record that exceeded the maximum permissible length. Error code: ssl_error_rx_record_too_long).  If I go to https://my.example.com:443/test.php then the URL redirects to https://my.example.com/test.php with no errors or problems except that my PHP prints out that the server port is 80 instead of 443.

Here's the relevant section from the conf.d/ssl.conf file (I removed what I believe are extraneous directives out and replaced the actual IP address with the word IP_ADDRESS):

Listen IP_ADDRESS:443
<VirtualHost *:443>
        ServerName my.example.com
        ServerAlias my
        DocumentRoot "/path/to/document_root/htdocs"
        Options +Indexes
</VirtualHost>

Here is the full print out of $_SERVER variable (with my server details redacted/changed to anonymous examples):

Array
(
    [HTTP_HOST] => my.example.com
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5
    [HTTP_ACCEPT_ENCODING] => gzip,deflate
    [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
    [HTTP_KEEP_ALIVE] => 115
    [HTTP_CONNECTION] => keep-alive
    [HTTP_COOKIE] => PHPSESSID=randomstring_yes_I'm_that_paranoid
    [PATH] => /sbin:/usr/sbin:/bin:/usr/bin
    [SERVER_SIGNATURE] =>
Apache/2.2.3 (Red Hat) Server at my.example.com Port 80

    [SERVER_SOFTWARE] => Apache/2.2.3 (Red Hat)
    [SERVER_NAME] => my.example.com
    [SERVER_ADDR] => IP_ADDRESS_1
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => IP_ADDRESS_2
    [DOCUMENT_ROOT] => /path/to/document_root/htdocs
    [SERVER_ADMIN] => admin@example.com
    [SCRIPT_FILENAME] => /path/to/document_root/htdocs/test.php
    [REMOTE_PORT] => 49178
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] =>
    [REQUEST_URI] => /test.php
    [SCRIPT_NAME] => /test.php
    [PHP_SELF] => /test.php
    [REQUEST_TIME] => 1292273758
)

As you can see, the SERVER_PORT is 80 and $_SERVER['HTTPS'] isn't set.  According to the PHP docs, I thought it was supposed to be set to a non-empty value if the PHP script is accessed via HTTPS (which is what I'm doing).

Any idea what's going on?  I'm just the web developer - I don't manage this server but my server admin tells me everything is working but I would like to know why $_SERVER['SERVER_PORT'] is returning 80 instead of 443 when viewing an HTTPS URL.

EDIT: I've edited the above example to illustrate my results in printing out the entire $_SERVER variable.

EDIT 2: Trying https://my.example.com:443/test.php as suggested in the comments below does the same thing - SERVER_PORT is 80 and HTTPS isn't set (specifically trying this URL redirects to https://my.example.com/test.php).

EDIT 3: OK, I've posted what I believe is the answer to this below (TL;DR: moving the SSL directives inside the VirtualHost directive and changing that directive to reference my site using it's IP address rather than a wildcard appears to have resolved the problem).


问:
How to install browser extensions on saucelabs?
I want to install an browser extension before my tests starts. I read on the documentation here that I should create a prerun executable to do this for me. However I am not sure how to this. I have no experience with creating executables </p>

答:
Using the pre-run will only upload the extension onto the SauceLabs Virtual Machine, it won't install it onto the respective browser.

If you want the extension to be installed on the browsers, you may want to consider setting a custom Firefox profile or Chrome options.

Here is a simple Java Example for setting a firefox profile (make sure to use the full path otherwise you will likely get an error):

```<code>FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(<PATH TO EXTENSION>));
caps.setCapability(FirefoxDriver.PROFILE, profile);
</code>```

Body:
Using the pre-run will only upload the extension onto the SauceLabs Virtual Machine, it won't install it onto the respective browser.

If you want the extension to be installed on the browsers, you may want to consider setting a custom Firefox profile or Chrome options.

Here is a simple Java Example for setting a firefox profile (make sure to use the full path otherwise you will likely get an error):

FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(<PATH TO EXTENSION>));
caps.setCapability(FirefoxDriver.PROFILE, profile);

ContentLicense: CC BY-SA 4.0


问:
Data Annotation table columns
```<code>public partial class Employee
{
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}
</code>```

This is generated class for table Employee using EF. I want Emp_Name change to EmpName in application without changing table structure. But using below changes using data annotation dbEntity.Set<Employee>().ToList();  getting exception

"The entity type Employee is not part of the model for the current
  context."

System.InvalidOperationException.

How can solve this

```<code>public partial class Employee
{
    public int Emp_Id { get; set; }
    [Column("Emp_Name")]
    public string EmpName { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}
</code>```

答:
The meaning of:

The entity type Employee is not part of the model for the current
  context.

Exception is that dbcontext is not aware of Employee type you need to register it with dbContext

```<code>public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees {get; set;}
}
</code>```

MyDbContext is your dbContext class and you need to define dbset of type employee in that override the OnModelCreating method of DbContext in your context like below:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>().ToTable("Employee");
}
</code>```

If you are changing the name for display purpose then you can use Display Or DisplayName as S.Akbari mentioned in his answer.

Title: Data Annotation table columns

Body:
public partial class Employee
{
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}

This is generated class for table Employee using EF. I want Emp_Name change to EmpName in application without changing table structure. But using below changes using data annotation dbEntity.Set<Employee>().ToList();  getting exception

"The entity type Employee is not part of the model for the current
  context."

System.InvalidOperationException.

How can solve this

public partial class Employee
{
    public int Emp_Id { get; set; }
    [Column("Emp_Name")]
    public string EmpName { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}

Body:
The meaning of:

The entity type Employee is not part of the model for the current
  context.

Exception is that dbcontext is not aware of Employee type you need to register it with dbContext

public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees {get; set;}
}

MyDbContext is your dbContext class and you need to define dbset of type employee in that override the OnModelCreating method of DbContext in your context like below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>().ToTable("Employee");
}

If you are changing the name for display purpose then you can use Display Or DisplayName as S.Akbari mentioned in his answer.


问:
Pass value from DataGridView to Textbox with searching in C#
I have a DataGridView which displays rows of table containing information in 4 columns. There are 4 textboxes used to input data to the datagridview. I have implemented a search feature (code below) to search for data in table. The thing I want is if I have searched an ID (for example, 123855) and the datagridview displays only one row with ID 123855, the value of 3 other columns is passed to the 3 other textboxes.

```<code>void SearchBoxTextChanged(object sender, EventArgs e)
{
    koneksi.Open();
    DataTable dt = new DataTable();
    MySqlDataAdapter da = new MySqlDataAdapter("Select * from mahasiswa where nim like '"+searchBox.Text+"%' or nim like'%"+searchBox.Text+"' or nim like '%"+searchBox.Text+"%' ", koneksi);
    da.Fill(dt);
    Tabel.DataSource = dt.DefaultView;
    koneksi.Close();
}
</code>```

How should I do that?

Thank you.

答:
use dataGridView1_CurrentCellChanged event :

```<code> private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
 {
     if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.Index > -1)
     {
         string value1 = dataGridView1.CurrentRow.Cells[0].Value != null ? dataGridView1.CurrentRow.Cells[0].Value.ToString() : "";
         textBox1.Text = value1;

         string value2 = dataGridView1.CurrentRow.Cells[1].Value != null ?  dataGridView1.CurrentRow.Cells[1].Value.ToString() : "";
         textBox2.Text = value2;
         .
         .
         .
     }
 }
</code>```

Body:
I have a DataGridView which displays rows of table containing information in 4 columns. There are 4 textboxes used to input data to the datagridview. I have implemented a search feature (code below) to search for data in table. The thing I want is if I have searched an ID (for example, 123855) and the datagridview displays only one row with ID 123855, the value of 3 other columns is passed to the 3 other textboxes.

void SearchBoxTextChanged(object sender, EventArgs e)
{
    koneksi.Open();
    DataTable dt = new DataTable();
    MySqlDataAdapter da = new MySqlDataAdapter("Select * from mahasiswa where nim like '"+searchBox.Text+"%' or nim like'%"+searchBox.Text+"' or nim like '%"+searchBox.Text+"%' ", koneksi);
    da.Fill(dt);
    Tabel.DataSource = dt.DefaultView;
    koneksi.Close();
}

How should I do that?

Thank you.

Body:
use dataGridView1_CurrentCellChanged event :

 private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
 {
     if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.Index > -1)
     {
         string value1 = dataGridView1.CurrentRow.Cells[0].Value != null ? dataGridView1.CurrentRow.Cells[0].Value.ToString() : "";
         textBox1.Text = value1;

         string value2 = dataGridView1.CurrentRow.Cells[1].Value != null ?  dataGridView1.CurrentRow.Cells[1].Value.ToString() : "";
         textBox2.Text = value2;
         .
         .
         .
     }
 }


问:
How to change the case of all characters in a text file to lowercase in java?
So if the contents of a text file is FCCCC, the output of the same text file should be fcccc.

I have written the following code

```<code>  import java.lang.*;
  import java.io.*;
  import java.io.FileWriter;
  import java.io.IOException;
  class A
  {
   public static void main(String args[]) throws IOException
   {
      try
      {
            FileReader reader = new FileReader("doc1.txt");
            FileWriter writer = new FileWriter("doc1.txt", true);
            int character=' ';
            char m;
            while ((character = reader.read()) != -1)
            {
                m=Character.toLowerCase((char)character);
                System.out.println(m);
                writer.write(m);
            }
            reader.close();
            writer.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
 }
</code>```

In the code above if the contents of the text file are FCCCC then the output is FCCCCfcccc.

What is the mistake in the code?

答:
You can use java.io.RandomAccessFile. It allows you to read and write to file and get file pointer and set file pointer. The program:

```<code>public static void main(String args[]) throws IOException {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("C:\\Untitled.txt", "rw");

            long length = raf.length();
            byte[] buffer = new byte[(int) length];
            long pointer = 0;
            while (raf.read(buffer) != -1) {
                String upperCase = new String(buffer).toUpperCase();
                raf.seek(pointer);
                raf.writeBytes(upperCase);
                pointer = raf.getFilePointer();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null)
                raf.close();
        }
    }
</code>```

raf.length() returns number of bytes in file

raf.read(buffer) reads buffer.length amount of bytes into buffer array

raf.seek(pointer); set file pointer to position before current read

raf.getFilePointer(); get file pointer position before next read to be able to write starting from this position.

Body:
So if the contents of a text file is FCCCC, the output of the same text file should be fcccc.

I have written the following code

  import java.lang.*;
  import java.io.*;
  import java.io.FileWriter;
  import java.io.IOException;
  class A
  {
   public static void main(String args[]) throws IOException
   {
      try
      {
            FileReader reader = new FileReader("doc1.txt");
            FileWriter writer = new FileWriter("doc1.txt", true);
            int character=' ';
            char m;
            while ((character = reader.read()) != -1)
            {
                m=Character.toLowerCase((char)character);
                System.out.println(m);
                writer.write(m);
            }
            reader.close();
            writer.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
 }

In the code above if the contents of the text file are FCCCC then the output is FCCCCfcccc.

What is the mistake in the code?

Body:
You can use java.io.RandomAccessFile. It allows you to read and write to file and get file pointer and set file pointer. The program:

public static void main(String args[]) throws IOException {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("C:\\Untitled.txt", "rw");

            long length = raf.length();
            byte[] buffer = new byte[(int) length];
            long pointer = 0;
            while (raf.read(buffer) != -1) {
                String upperCase = new String(buffer).toUpperCase();
                raf.seek(pointer);
                raf.writeBytes(upperCase);
                pointer = raf.getFilePointer();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null)
                raf.close();
        }
    }

raf.length() returns number of bytes in file

raf.read(buffer) reads buffer.length amount of bytes into buffer array

raf.seek(pointer); set file pointer to position before current read

raf.getFilePointer(); get file pointer position before next read to be able to write starting from this position.


问:
Ionic 2 - range slider
I have a ionic 2 range slider component, what I would like to do is set an gradient color on the slider. So basically from 0 to 10 where 0 is grey and 10 is red. How do I style my range slider with an color gradient?

This is my range slider:

```<code>  <ion-item text-wrap>
    <ion-label stacked>Beperking: </ion-label><ion-badge item-right color="secondary">{{ Beperking }}</ion-badge>
    <ion-range min="0" max="10" [(ngModel)]="Beperking" color="secondary" pin="true">
      <ion-label range-left>0</ion-label>
      <ion-label range-right>10</ion-label>
    </ion-range>
  </ion-item>
</code>```

How do I change the color when it is above an certain value?

答: for this you need to map the change in slider to a valve and on change event fire a function which would change the style of the target component or you could nest it in [] property tag to make the effect using data binding.</p>

Title: Ionic 2 - range slider

Body:
I have a ionic 2 range slider component, what I would like to do is set an gradient color on the slider. So basically from 0 to 10 where 0 is grey and 10 is red. How do I style my range slider with an color gradient?

This is my range slider:

  <ion-item text-wrap>
    <ion-label stacked>Beperking: </ion-label><ion-badge item-right color="secondary">{{ Beperking }}</ion-badge>
    <ion-range min="0" max="10" [(ngModel)]="Beperking" color="secondary" pin="true">
      <ion-label range-left>0</ion-label>
      <ion-label range-right>10</ion-label>
    </ion-range>
  </ion-item>

How do I change the color when it is above an certain value?