问:
Request to enable GPS occuring twice if activity stopped and started again
I have an activity which requests the user to enable the GPS in the onStart() by showing a dialog with OK and CANCEL buttons. But if the user presses home button before interacting with the dialog, and starts the app again, a new dialog box appears on top of the old one and hence the user sees two dialog boxes one after the another. How can I dismiss the old dialog box in the onStop method of the activity?

Here is the relevant part of my code:

```<code>protected void onStart() {
    super.onStart();
    enableGPS();
}

private void enableGPS() {                                      //GPS ENABLE RELATED METHOD
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result
                    .getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:                           //GPS ALREDY TURNED ON
                    if (locationServiceConnected) {
                        if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                        }
                    }
                    else {
                        redirectStatus.setText("ERROR: Not able to connect to Location Service");
                        btnRetry.setVisibility(View.VISIBLE);
                    }
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:               //GPS NOT ALREDY TURNED ON, SHOW TURN ON DIALOG
                    try {
                        status.startResolutionForResult(enableGPSActivity.this, REQUEST_CHECK_SETTINGS); //CREATING DIALOG FOR GPS TURN ON
                    } catch (IntentSender.SendIntentException e) {
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:       //GPS CANNOT BE TURNED ON
                    redirectStatus.setText("Permission Available, not able to enable GPS");
                    btnRetry.setVisibility(View.VISIBLE);
                    break;
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {             //GPS ENABLE RELATED METHOD, DIALOG FOR GPS TURN ON
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        if (resultCode == Activity.RESULT_OK) {                 // GPS TURN ON ACCEPTED
            if (locationServiceConnected) {
                if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                    redirectStatus.setText("Please Wait. Fetching Your Current Location");
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                }
            }
        }
        if (resultCode == Activity.RESULT_CANCELED) {               //GPS TURN ON REJECTED
            redirectStatus.setText("Permission Available, GPS Off");
            btnRetry.setVisibility(View.VISIBLE);
        }
    }
}
</code>```

}

答:
Call enableGPS(); into onCreate() instead of onStart().

because,

According to the life-cycle of an Activity - When user pressed home button, the current activity will goes in background by calling - onPause() and onStop() method. When you resume the activity from Stack - Activity will be resumed by calling onRestart(), onStart() and onResume().

Body:
I have an activity which requests the user to enable the GPS in the onStart() by showing a dialog with OK and CANCEL buttons. But if the user presses home button before interacting with the dialog, and starts the app again, a new dialog box appears on top of the old one and hence the user sees two dialog boxes one after the another. How can I dismiss the old dialog box in the onStop method of the activity?

Here is the relevant part of my code:

protected void onStart() {
    super.onStart();
    enableGPS();
}

private void enableGPS() {                                      //GPS ENABLE RELATED METHOD
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result
                    .getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:                           //GPS ALREDY TURNED ON
                    if (locationServiceConnected) {
                        if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                        }
                    }
                    else {
                        redirectStatus.setText("ERROR: Not able to connect to Location Service");
                        btnRetry.setVisibility(View.VISIBLE);
                    }
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:               //GPS NOT ALREDY TURNED ON, SHOW TURN ON DIALOG
                    try {
                        status.startResolutionForResult(enableGPSActivity.this, REQUEST_CHECK_SETTINGS); //CREATING DIALOG FOR GPS TURN ON
                    } catch (IntentSender.SendIntentException e) {
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:       //GPS CANNOT BE TURNED ON
                    redirectStatus.setText("Permission Available, not able to enable GPS");
                    btnRetry.setVisibility(View.VISIBLE);
                    break;
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {             //GPS ENABLE RELATED METHOD, DIALOG FOR GPS TURN ON
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        if (resultCode == Activity.RESULT_OK) {                 // GPS TURN ON ACCEPTED
            if (locationServiceConnected) {
                if (ActivityCompat.checkSelfPermission(enableGPSActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                    redirectStatus.setText("Please Wait. Fetching Your Current Location");
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, enableGPSActivity.this);
                }
            }
        }
        if (resultCode == Activity.RESULT_CANCELED) {               //GPS TURN ON REJECTED
            redirectStatus.setText("Permission Available, GPS Off");
            btnRetry.setVisibility(View.VISIBLE);
        }
    }
}

}


来源: stackexchange

问:
Oculus entitlement gear vr
I am developing a game for Gear VR in Unity 5.6.1p1 with Oculus Utils 1.9.0. It is on technical review now on developer console. However I keep getting entitlement error even after adding it to the project.

Here is their explanation:

It appears that your app does not support entitlement checks to prevent unauthorized use of your content. Documentation on how to add entitlement checks can be found here: https://developer.oculus.com/documentation/platform/latest/concepts/pgsg-get-started-with-sdk/

And here is my entitlement code:

```<code>public class PlatformManager : MonoBehaviour
{
    public static bool entitled = false;
    private static PlatformManager s_instance;
    private ulong m_myID;

    private string m_myOculusID;

    void Awake()
    {
        if(s_instance != null)
        {
            Destroy(gameObject);
            return;
        }
        s_instance = this;
        DontDestroyOnLoad(gameObject);
        Core.Initialize();
    }

    private void Start()
    {
        entitled = false;
        Entitlements.IsUserEntitledToApplication().OnComplete(IsEntitledCallback);
    }

    void IsEntitledCallback(Message msg)
    {
        if(msg.IsError)
        {
            entitled = false;
            TerminateWithError(msg);
            return;
        }
        entitled = true;
        Users.GetLoggedInUser().OnComplete(GetLoggedInUserCallback);
    }

    public static void TerminateWithError(Message msg)
    {
        Debug.Log("Error: " + msg.GetError().Message);
        UnityEngine.Application.Quit();
    }

    void GetLoggedInUserCallback(Message<User> msg)
    {
        if(msg.IsError)
        {
            TerminateWithError(msg);
            return;
        }

        m_myID = msg.Data.ID;
        m_myOculusID = msg.Data.OculusID;
    }
}
</code>```

I am not doing anything with ID after entitling. Should I do something? Is there a mistake in my code? I do get true value after entitling.

答: My app has passed entitlement check and techical review. The code was good, but I had to add a message to let the user know that he is not entitled, and then exit the app.</p>

ContentLicense: CC BY-SA 3.0

Title: Oculus entitlement gear vr

Body:
I am developing a game for Gear VR in Unity 5.6.1p1 with Oculus Utils 1.9.0. It is on technical review now on developer console. However I keep getting entitlement error even after adding it to the project.

Here is their explanation:

It appears that your app does not support entitlement checks to prevent unauthorized use of your content. Documentation on how to add entitlement checks can be found here: https://developer.oculus.com/documentation/platform/latest/concepts/pgsg-get-started-with-sdk/

And here is my entitlement code:

public class PlatformManager : MonoBehaviour
{
    public static bool entitled = false;
    private static PlatformManager s_instance;
    private ulong m_myID;

    private string m_myOculusID;

    void Awake()
    {
        if(s_instance != null)
        {
            Destroy(gameObject);
            return;
        }
        s_instance = this;
        DontDestroyOnLoad(gameObject);
        Core.Initialize();
    }

    private void Start()
    {
        entitled = false;
        Entitlements.IsUserEntitledToApplication().OnComplete(IsEntitledCallback);
    }

    void IsEntitledCallback(Message msg)
    {
        if(msg.IsError)
        {
            entitled = false;
            TerminateWithError(msg);
            return;
        }
        entitled = true;
        Users.GetLoggedInUser().OnComplete(GetLoggedInUserCallback);
    }

    public static void TerminateWithError(Message msg)
    {
        Debug.Log("Error: " + msg.GetError().Message);
        UnityEngine.Application.Quit();
    }

    void GetLoggedInUserCallback(Message<User> msg)
    {
        if(msg.IsError)
        {
            TerminateWithError(msg);
            return;
        }

        m_myID = msg.Data.ID;
        m_myOculusID = msg.Data.OculusID;
    }
}

I am not doing anything with ID after entitling. Should I do something? Is there a mistake in my code? I do get true value after entitling.


问:
How to save the screenshot in particular folder using python
I have written the below script for taking a screenshot. Currently, it saves the file in the same directory as the python file is located. I want to save the screenshot in a particular folder.</p>

```<code>from selenium import webdriver
import option
import time

#PhantomJS
driver = webdriver.PhantomJS(executable_path=r'D:\PhantomJS\phantomjs-2.1.1-
windows\bin\phantomjs.exe')

#Selenium
#driver = webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe")

#Maximizes window to full screen
driver.maximize_window()

#Gets the URL for OMS
driver.get(option.OMS_QUERY)

#Gets the username & Password
driver.find_element_by_xpath(option.LOG_IN).click()
driver.find_element_by_id("username").send_keys(option.USERNAME)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(3)
driver.find_element_by_id("password").send_keys(option.PASSWORD)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(15)

#Saves the screenshot for OMS_SWR
driver.save_screenshot('oms_swr.png')

#Gets the URL for DMS
driver.get(option.DMS_QUERY)
time.sleep(15)

#Saves the screenshot for DMS_SWR
driver.save_screenshot('dms_swr.png')
driver.quit()
</code>```

答:
You have to set path where you want to store it, Store in system drive like this</p>

```<code>driver.save_screenshot('D:/Folder_name/dms_swr.png')
</code>```

Body:
I have written the below script for taking a screenshot. Currently, it saves the file in the same directory as the python file is located. I want to save the screenshot in a particular folder.

from selenium import webdriver
import option
import time

#PhantomJS
driver = webdriver.PhantomJS(executable_path=r'D:\PhantomJS\phantomjs-2.1.1-
windows\bin\phantomjs.exe')

#Selenium
#driver = webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe")

#Maximizes window to full screen
driver.maximize_window()

#Gets the URL for OMS
driver.get(option.OMS_QUERY)

#Gets the username & Password
driver.find_element_by_xpath(option.LOG_IN).click()
driver.find_element_by_id("username").send_keys(option.USERNAME)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(3)
driver.find_element_by_id("password").send_keys(option.PASSWORD)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(15)

#Saves the screenshot for OMS_SWR
driver.save_screenshot('oms_swr.png')

#Gets the URL for DMS
driver.get(option.DMS_QUERY)
time.sleep(15)

#Saves the screenshot for DMS_SWR
driver.save_screenshot('dms_swr.png')
driver.quit()

Body:
You have to set path where you want to store it, Store in system drive like this

driver.save_screenshot('D:/Folder_name/dms_swr.png')


问:
How can I create a data structure starting at a specified memory address (without using new)?
I asked a similar question before, but I only realized now that the answer I received isn't totally what I wanted.

If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned an address to) without using "new".

答:
I can think of two solutions

Use placement new instead of new.

For a C style structure simply copy the structure to the memory address and typecast it - bitwise copy

i.e.

```<code>CreateStructAtAddr(void* pOutput, mystruct* pInput)
{
    *(mystruct*)pOutput = *pInput;
}
</code>```

I am ignoring check for valid memory for brevity

ContentLicense: CC BY-SA 2.5

Body:
I can think of two solutions

Use placement new instead of new.

For a C style structure simply copy the structure to the memory address and typecast it - bitwise copy

i.e.

CreateStructAtAddr(void* pOutput, mystruct* pInput)
{
    *(mystruct*)pOutput = *pInput;
}

I am ignoring check for valid memory for brevity


问:
Pattern Matching for CSV processing
I have a csv file with three columns and I want to get the third column into an Iterator. I want to filter out the headers by using the trytoDouble method in combination of the Pattern Matching.

```<code>def trytoDouble(s: String): Option[Double] = {
  try {
    Some(s.toDouble)
  } catch {
    case e: Exception => None
  }
}

val asdf = Source.fromFile("my.csv").getLines().map(_.split(",").map(_.trim).map(utils.trytoDouble(_))).map{
  _ match {
    case Array(a, b, Some(c: Double)) => c
  }
}
</code>```

results in

An exception or error caused a run to abort: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)
  scala.MatchError: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)

what did I do wrong?

答:
The other answers are great, but I just noticed that an alternative of minimal code change is to simply write

```<code>val asdf = Source.fromFile(fileName).getLines().map(_.split(",").map(_.trim).map( utils.trytoDouble(_))).flatMap{
  _ match {
    case Array(a, b, c) => c
  }
}
</code>```

or slightly more efficient (since we are only interested in the last column anyway):

```<code>val asdf = Source.fromFile(fileName).getLines().map(_.split(",")).flatMap{
  _ match {
    case Array(a, b, c) => trytoDouble(c.trim)
  }
}
</code>```

Important to notice is here that flatMap will remove None objects.

Title: Pattern Matching for CSV processing

Body:
I have a csv file with three columns and I want to get the third column into an Iterator. I want to filter out the headers by using the trytoDouble method in combination of the Pattern Matching.

def trytoDouble(s: String): Option[Double] = {
  try {
    Some(s.toDouble)
  } catch {
    case e: Exception => None
  }
}

val asdf = Source.fromFile("my.csv").getLines().map(_.split(",").map(_.trim).map(utils.trytoDouble(_))).map{
  _ match {
    case Array(a, b, Some(c: Double)) => c
  }
}

results in

An exception or error caused a run to abort: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)
  scala.MatchError: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)

what did I do wrong?

Body:
The other answers are great, but I just noticed that an alternative of minimal code change is to simply write

val asdf = Source.fromFile(fileName).getLines().map(_.split(",").map(_.trim).map( utils.trytoDouble(_))).flatMap{
  _ match {
    case Array(a, b, c) => c
  }
}

or slightly more efficient (since we are only interested in the last column anyway):

val asdf = Source.fromFile(fileName).getLines().map(_.split(",")).flatMap{
  _ match {
    case Array(a, b, c) => trytoDouble(c.trim)
  }
}

Important to notice is here that flatMap will remove None objects.


问:
two or more range inputs sharing one (the same) Max value in HTML
To give you an image of what I am trying to do, know that browser strategy real time games page when you can recruit units using an range input (or ui slider)? Something like this...
 I am trying to make some range inputs that should share the same max value (which is given dynamically by an ajax call). For example if I have value 10, when I change first range at value 3, rests of ranges will have max value 7 now. If I change value to second range at 2, rests will have now max 5...
I should simplify this for the moment with only 3 ranges (but will be more, like 14).

```<code><input type="range" id="wpike" min="0" max="" value="0"><button>V</button>
<input type="range" id="waxe" min="0" max="" value="0"><button>V</button>
<input type="range" id="wsword" min="0" max="" value="0"><button>V</button>
</code>```

Variable $rangemax will be given in ajax call and put in every range input max value... I tried to make an onchange event using ranges class, but that will trigger it over the actual range changed (minimizing its max value irremediable).

```<code>$('.ceva').on('change input', function () {
    var $rangemax = // $rangemax - wpike val - waxe val - wsword val(orientative)
        $('ceva').attr('max', $rangemax);
});
</code>```

I can do an onchange function for each id separately like: when I change its value, change atrr max for every id (excluding changed id)... But this will result huge code, considering i should have like 14 ranges...
Or I can have an invisible input... When page is loaded, I fill its value with $rangemax. Ranges will have max Then $(ceva).on(change - insert in the input value ($rangemax-waxe.val()-wpike.val()-so on... Then set max attr of $(ceva) as insert element value?  Would be more elegant...but..not enought?:D

答:
after a marathon effort, I have what u want;

Change first scroll ("wpike"); based on that other two will be set such that waxe+wsword  = 10 -wpike;

Note: this works only for 3; scaling upto 14 is something that needs more thought;

window.onload = changeEvent()

function changeEvent() {
  let allInputs = document.querySelectorAll('input[type="range"]');
  let allIds = [];
  for(i=0;i<allInputs.length;i++) {
   allIds.push(allInputs[i].getAttribute('id'));
     allInputs[i].onchange = function(e) {
       let idOfScrolledSlider = (e.path[0].getAttribute('id'));
       changeSliders(allIds,idOfScrolledSlider)
     }
  }
}

function changeSliders(allIds,idOfScrolledSlider) {
 let cleanedIdArray = popId(allIds,idOfScrolledSlider)
  let firstScrollValue = document.getElementById(idOfScrolledSlider).value;
  document.getElementById('waxe').value = Math.floor(Math.random() * (10 -firstScrollValue));
  let secondScrollValue = Math.floor(Math.random() * (firstScrollValue))
  document.getElementById('wsword').value =10 - (parseInt(firstScrollValue) + parseInt(secondScrollValue));
  console.log('firstScrollValue',firstScrollValue);
  console.log('secondScrollValue',secondScrollValue);
  console.log('3rd scoll', 10 - (parseInt(firstScrollValue) + parseInt(secondScrollValue)));
}

function popId(allIds,idOfScrolledSlider) {
  let newArray = [];
  allIds.map((id) => {
     if(id != idOfScrolledSlider) newArray.push(id);
  });
   return newArray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="range" id="wpike" min="0" max="10" value="10"><button>V</button>
<input type="range" id="waxe" min="0" max="" value="0"><button>V</button>
<input type="range" id="wsword" min="0" max="" value="0"><button>V</button> </code>```

Body:
To give you an image of what I am trying to do, know that browser strategy real time games page when you can recruit units using an range input (or ui slider)? Something like this...
 I am trying to make some range inputs that should share the same max value (which is given dynamically by an ajax call). For example if I have value 10, when I change first range at value 3, rests of ranges will have max value 7 now. If I change value to second range at 2, rests will have now max 5...
I should simplify this for the moment with only 3 ranges (but will be more, like 14).

<input type="range" id="wpike" min="0" max="" value="0"><button>V</button>
<input type="range" id="waxe" min="0" max="" value="0"><button>V</button>
<input type="range" id="wsword" min="0" max="" value="0"><button>V</button>

Variable $rangemax will be given in ajax call and put in every range input max value... I tried to make an onchange event using ranges class, but that will trigger it over the actual range changed (minimizing its max value irremediable).

$('.ceva').on('change input', function () {
    var $rangemax = // $rangemax - wpike val - waxe val - wsword val(orientative)
        $('ceva').attr('max', $rangemax);
});

I can do an onchange function for each id separately like: when I change its value, change atrr max for every id (excluding changed id)... But this will result huge code, considering i should have like 14 ranges...
Or I can have an invisible input... When page is loaded, I fill its value with $rangemax. Ranges will have max Then $(ceva).on(change - insert in the input value ($rangemax-waxe.val()-wpike.val()-so on... Then set max attr of $(ceva) as insert element value?  Would be more elegant...but..not enought?:D

Body:
after a marathon effort, I have what u want;

Change first scroll ("wpike"); based on that other two will be set such that waxe+wsword  = 10 -wpike;

Note: this works only for 3; scaling upto 14 is something that needs more thought;

window.onload = changeEvent()

function changeEvent() {
  let allInputs = document.querySelectorAll('input[type="range"]');
  let allIds = [];
  for(i=0;i<allInputs.length;i++) {
   allIds.push(allInputs[i].getAttribute('id'));
     allInputs[i].onchange = function(e) {
       let idOfScrolledSlider = (e.path[0].getAttribute('id'));
       changeSliders(allIds,idOfScrolledSlider)
     }
  }
}

function changeSliders(allIds,idOfScrolledSlider) {
 let cleanedIdArray = popId(allIds,idOfScrolledSlider)
  let firstScrollValue = document.getElementById(idOfScrolledSlider).value;
  document.getElementById('waxe').value = Math.floor(Math.random() * (10 -firstScrollValue));
  let secondScrollValue = Math.floor(Math.random() * (firstScrollValue))
  document.getElementById('wsword').value =10 - (parseInt(firstScrollValue) + parseInt(secondScrollValue));
  console.log('firstScrollValue',firstScrollValue);
  console.log('secondScrollValue',secondScrollValue);
  console.log('3rd scoll', 10 - (parseInt(firstScrollValue) + parseInt(secondScrollValue)));
}

function popId(allIds,idOfScrolledSlider) {
  let newArray = [];
  allIds.map((id) => {
     if(id != idOfScrolledSlider) newArray.push(id);
  });
   return newArray;
}

<input type="range" id="wpike" min="0" max="10" value="10"><button>V</button>
<input type="range" id="waxe" min="0" max="" value="0"><button>V</button>
<input type="range" id="wsword" min="0" max="" value="0"><button>V</button>


问:
Sails does not clear cache without hard refresh
My Sails application does not update javascript files in production.
I am starting sails on production:

NODE_ENV=production forever start app.js

But when i open the website, i dont see any changes. Even if i restart the website. Changes applies only after hard-refresh with ctrl+F5, or manually clearing the cache.

But locally it works.

This is probably something with cache, that browser is not forced to update/clear the cache. How to solve that?

My tasks/config/sails-linker.js:

```<code>  grunt.config.set('sails-linker', {
    devJs: {
      options: {
        startTag: '<!--SCRIPTS-->',
        endTag: '<!--SCRIPTS END-->',
        fileTmpl: '<script src="%s?v='+ new Date().getTime() +'"></script>',
        appRoot: '.tmp/public'
      },
      files: {
        '.tmp/public/**/*.html': require('../pipeline').jsFilesToInject,
        'views/**/*.html': require('../pipeline').jsFilesToInject,
        'views/**/*.ejs': require('../pipeline').jsFilesToInject
      }
    },
</code>```

because i am not using sails lift on production, i changed the grunt default  to this:

```<code>/tasks/register/default.js

module.exports = function (grunt) {

grunt.registerTask('default', [
    'compileAssets',
    'linkAssetsBuildProd',
    'watch',
    'concat',
    'uglify',
    'cssmin',
    'sails-linker:prodJs',
    'sails-linker:prodJsJade',
  ]);
};
</code>```

I have no idea where to look next.

答:
I have fixed it now like this:

on tasks/config/sails-linker.js added this:

```<code>module.exports = function(grunt) {

  var time = new Date().getTime();

  grunt.config.set('sails-linker', {
</code>```

and then changed there every line from

```<code>fileTmpl: '<script src="%s"></script>'
</code>```

to

```<code>fileTmpl: '<script src="%s?v='+ time +'"></script>'
</code>```

And on production server on every update with assets i run

```<code>sails www --prod
</code>```

And then

```<code>NODE_ENV=production pm2 start app.js
</code>```

This works. At least. This generates everytime new minified javascript file with new version, and browser reloads then.

Body:
My Sails application does not update javascript files in production.
I am starting sails on production:

NODE_ENV=production forever start app.js

But when i open the website, i dont see any changes. Even if i restart the website. Changes applies only after hard-refresh with ctrl+F5, or manually clearing the cache.

But locally it works.

This is probably something with cache, that browser is not forced to update/clear the cache. How to solve that?

My tasks/config/sails-linker.js:

  grunt.config.set('sails-linker', {
    devJs: {
      options: {
        startTag: '',
        endTag: '',
        fileTmpl: '',
        appRoot: '.tmp/public'
      },
      files: {
        '.tmp/public/**/*.html': require('../pipeline').jsFilesToInject,
        'views/**/*.html': require('../pipeline').jsFilesToInject,
        'views/**/*.ejs': require('../pipeline').jsFilesToInject
      }
    },

because i am not using sails lift on production, i changed the grunt default  to this:

/tasks/register/default.js

module.exports = function (grunt) {

grunt.registerTask('default', [
    'compileAssets',
    'linkAssetsBuildProd',
    'watch',
    'concat',
    'uglify',
    'cssmin',
    'sails-linker:prodJs',
    'sails-linker:prodJsJade',
  ]);
};

I have no idea where to look next.

Body:
I have fixed it now like this:

on tasks/config/sails-linker.js added this:

module.exports = function(grunt) {

  var time = new Date().getTime();

  grunt.config.set('sails-linker', {

and then changed there every line from

fileTmpl: '<script src="%s"></script>'

to

fileTmpl: '<script src="%s?v='+ time +'"></script>'

And on production server on every update with assets i run

sails www --prod

And then

NODE_ENV=production pm2 start app.js

This works. At least. This generates everytime new minified javascript file with new version, and browser reloads then.


问:
Promise.all: What are arguments of promise.all.catch(e)
What are arguments of promise.all.catch(e)

Is e an array of errors or object?

```<code>Promise.all([promise1, promise2, ..])
.then((result1, result2,..)=>{})
.catch((error1,error2..???)=>{

})
</code>```

How can we get array of errors? if not Promise.all then how?

答:
As per spec

The all function returns a new promise which is fulfilled with an
array of fulfillment values for the passed promises, or rejects with
the reason of the first passed promise that rejects. It resolves all
elements of the passed iterable to promises as it runs this algorithm.

Hence promise.catch

When the catch method is called with argument onRejected the following
steps are taken:

Let promise be the this value.

Return Invoke(promise, "then", «undefined, onRejected»).

Hence reason of the first passed promise that rejects is the argument of promise.all.catch.

Body:
What are arguments of promise.all.catch(e)

Is e an array of errors or object?

Promise.all([promise1, promise2, ..])
.then((result1, result2,..)=>{})
.catch((error1,error2..???)=>{

})

How can we get array of errors? if not Promise.all then how?


问:
Limit the string length of TextBox when it is updated with Binding
I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update:
Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

```<code>    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }
</code>```

答:
I hope to understand you right. You could create a new Property in the ViewModel that returns only the first 5 chars of the text and set your binding to that property.
You might need to call PropertyChanged for the new Property when the text changes.</p>

Body:
I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update:
Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }


问:
Delete folder from internal storage in android?
How to delete folder(contain some folder and file) from internal storage? Folder have some below tree.

```<code>folder
|_________  C2 (folder)
             |________1 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________2 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________3 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________4 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________5 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif

|_________  C2.xml (file)
</code>```

I want to delete folder and containing all files

```<code>fil.delete();

System.out.println("boolean =>" + fil.delete());
</code>```

but above code shows false. Please help.

答:
Using Apache commons-io, which is just one line of code. </p>

```<code>FileUtils.deleteDirectory(getAlbumStorageDir(directoryName));
</code>```

Body:
How to delete folder(contain some folder and file) from internal storage? Folder have some below tree.

folder
|_________  C2 (folder)
             |________1 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________2 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________3 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________4 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif
             |________5 (folder)
                      |________1.gif
                      |________2.gif
                      |________3.gif
                      |________4.gif

|_________  C2.xml (file)

I want to delete folder and containing all files

fil.delete();

System.out.println("boolean =>" + fil.delete());

but above code shows false. Please help.

Body:
Using Apache commons-io, which is just one line of code.

FileUtils.deleteDirectory(getAlbumStorageDir(directoryName));


问:
how to read json keys with different number of objects in java
I  have a Json file that is as below:

```<code>{
"fileExtension":["xls","xlsx"],
"fileType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"fileName": "Dummy123",
"worksheetCount":"3",
"worksheetList":["ws1","ws2","ws3"],
"worksheet":
{
    "ws1":
    {
        "worksheetName":"Employee Info",
        "sectionCount":"1",
        "sectionList":["Employee"],
        "sectionName":"Employee",
        "sectionType":"table",
        "Employee":
        {
            "columnCount": "3",
            "beginningRowNumber": "2",
            "endingRowNumber": "7",
            "columnList":[
            "columns":
              {
                "c1":
                {
                    "c1_header": "EMP ID",
                    "c1_datatype" :"Numeric"
                },
                "c2":
                {
                    "c2_header": "EMP NAME",
                    "c2_datatype" : "String"
                },
                "c3":
                {
                    "c3_header": "DESIGNATION",
                    "c3_datatype":"String"
                }
            }

        }
    }
}
}
</code>```

here the worksheet count and section count and column count varies for each object like "ws1". I have many objects in my json like ws1. but in each of this the section count and column count varies and there are json objects for each section and each column, I want to get the value for each section and column and worksheet without repeating my code. Could someone please help me out.

答:
```<code>JSJSONObject worksheets=rootobject.getJSONObject("worksheet");
JSONArray worksheetName=rootobject.getJSONArray("worksheetList");
int lenght=worksheetName.lenght();

for(int i=0;i<lenght;i++)
{
    JSJSONObject ws=worksheets.getJSONObject(worksheetName.getString(i));
    JSONArray sectionList=rootobject.getJSONArray("sectionList");
    for(int j=0;j<sectionList.lenght();j++)
    {
        JSJSONObject section=ws.getJSONObject(sectionList.getString(j));
        JSONArray columnList=section.getJSONArray("columnList");
        for(int k=0;k<columnList.lenght();k++)
        {
            JSJSONObject column=ws.getJSONObject(columnList.getString(k));
            JSONArray keys = column.names ();
            for (int l = 0; l < keys.length (); l++) {
                String key = keys.getString (l); // Here's your key
                JSJSONObject c1_c2_c3=column.getJSONObject(key);//c1_c2_c3 indicate c1 or c2 or c3
                JSONArray c1_c2_c3Keys = c1_c2_c3.names ();
                for (int m = 0; m < c1_c2_c3Keys.length (); m++) {
                    String c1_c2_c3key = c1_c2_c3Keys.getString (m); // Here's your key i.e. c1_header,c1_datatype,c2_header
                    String header_datatype=c1_c2_c3.getString(c1_c2_c3key);//header_datatype indicate header or datatype i.e. EMP ID ,Numeric
                }
            }
         }
    }
}
</code>```

hope this will help you .

Body:
I  have a Json file that is as below:

{
"fileExtension":["xls","xlsx"],
"fileType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"fileName": "Dummy123",
"worksheetCount":"3",
"worksheetList":["ws1","ws2","ws3"],
"worksheet":
{
    "ws1":
    {
        "worksheetName":"Employee Info",
        "sectionCount":"1",
        "sectionList":["Employee"],
        "sectionName":"Employee",
        "sectionType":"table",
        "Employee":
        {
            "columnCount": "3",
            "beginningRowNumber": "2",
            "endingRowNumber": "7",
            "columnList":[
            "columns":
              {
                "c1":
                {
                    "c1_header": "EMP ID",
                    "c1_datatype" :"Numeric"
                },
                "c2":
                {
                    "c2_header": "EMP NAME",
                    "c2_datatype" : "String"
                },
                "c3":
                {
                    "c3_header": "DESIGNATION",
                    "c3_datatype":"String"
                }
            }

        }
    }
}
}

here the worksheet count and section count and column count varies for each object like "ws1". I have many objects in my json like ws1. but in each of this the section count and column count varies and there are json objects for each section and each column, I want to get the value for each section and column and worksheet without repeating my code. Could someone please help me out.

Body:
JSJSONObject worksheets=rootobject.getJSONObject("worksheet");
JSONArray worksheetName=rootobject.getJSONArray("worksheetList");
int lenght=worksheetName.lenght();

for(int i=0;i<lenght;i++)
{
    JSJSONObject ws=worksheets.getJSONObject(worksheetName.getString(i));
    JSONArray sectionList=rootobject.getJSONArray("sectionList");
    for(int j=0;j<sectionList.lenght();j++)
    {
        JSJSONObject section=ws.getJSONObject(sectionList.getString(j));
        JSONArray columnList=section.getJSONArray("columnList");
        for(int k=0;k<columnList.lenght();k++)
        {
            JSJSONObject column=ws.getJSONObject(columnList.getString(k));
            JSONArray keys = column.names ();
            for (int l = 0; l < keys.length (); l++) {
                String key = keys.getString (l); // Here's your key
                JSJSONObject c1_c2_c3=column.getJSONObject(key);//c1_c2_c3 indicate c1 or c2 or c3
                JSONArray c1_c2_c3Keys = c1_c2_c3.names ();
                for (int m = 0; m < c1_c2_c3Keys.length (); m++) {
                    String c1_c2_c3key = c1_c2_c3Keys.getString (m); // Here's your key i.e. c1_header,c1_datatype,c2_header
                    String header_datatype=c1_c2_c3.getString(c1_c2_c3key);//header_datatype indicate header or datatype i.e. EMP ID ,Numeric
                }
            }
         }
    }
}

hope this will help you .


问:
Do struct tags, union tags and enum tags have separate namespaces?
schot's answer is a good one. He claimed that

Tags (names of structures, unions and enumerations).

I think that the tags for structures, unions and enumerations have different namespaces, so that this code is completely fine:

```<code>// In the same scope
struct T {};
union T {};
enum T {};
</code>```

But inferring from the quotation above, it looks like all tags share the same namespace. Is the answer not clear enough or am I wrong?

答:
No, they do not have separate namespaces. There is only one namespace for tags. This means

```<code>struct TS{};
union TU{};
int TS, TU;
</code>```

is valid while

```<code>struct T{};
union T{};
</code>```

is not. Two declarations of T are in the same namespace.

Body:
schot's answer is a good one. He claimed that

Tags (names of structures, unions and enumerations).

I think that the tags for structures, unions and enumerations have different namespaces, so that this code is completely fine:

// In the same scope
struct T {};
union T {};
enum T {};

But inferring from the quotation above, it looks like all tags share the same namespace. Is the answer not clear enough or am I wrong?

Body:
No, they do not have separate namespaces. There is only one namespace for tags. This means

struct TS{};
union TU{};
int TS, TU;

is valid while

struct T{};
union T{};

is not. Two declarations of T are in the same namespace.


问:
Executing a script in a different directory without having to use the full path
I generate a bash script named "script1" and place it in the directory /home/Me/bin. I want to execute it (just by calling it's name ./script1) without the complete path from any directory. How can I do it? Is there any specific command? </p>

答:
The directory the script is in needs to be included in your PATH environment variable. $HOME/bin usually is included already. Otherwise, you can add it in your ~/.bashrc:

```<code>PATH=$PATH:/home/Me/bin
</code>```

Body:
The directory the script is in needs to be included in your PATH environment variable. $HOME/bin usually is included already. Otherwise, you can add it in your ~/.bashrc:

PATH=$PATH:/home/Me/bin


问:
multiple <select> change event not firing when last item is deselected
I am registering a change event on a multiselect with jQuery to display the selected values in a span element below the multiselect. The change event fires fine when selecting and deselecting elements in the list, except if I deselect the last selected element.

Here is an example (see it in jsfiddle):

```<code><select id="multiselect" multiple>
    <optgroup label="Italian">
        <option value="CEI2008">CEI2008 — Conferenza Episcopale Italiana (2008)</option>
        <option value="LUZZI">LUZZI — Riveduta - Luzzi (1924)</option>
    </optgroup>
    <optgroup label="Latin">
        <option value="NVBSE">NVBSE — Nova Vulgata - Bibliorum Sacrorum Edition (1979)</option>
    </optgroup>
</select>
<div>Selected versions: <span id="selectedversions">none</span></div>
</code>```

and the accompanying jquery code:

```<code>$('#multiselect').change(function(){
    var selecteditems = $(this).val();
    if(selecteditems.length===0){ $('#selectedversions').text('none'); }
    else{ $('#selectedversions').text(selecteditems.join(',')); }
});
</code>```

When the last item is deselected with a CTRL-click, I would expect the change event to fire and jquery val() to return an empty array. Instead it seems that the change event is not firing at all in the case of deselecting the last selected item.

答:
For me jQuery is not loaded properly because of poor internet connection. If you have same problem use DOM level.

```<code>$(document).on('change','#multiselect',function() {
    var value = $('#multiselect').val();
    alert(value);
});
</code>```

Body:
I am registering a change event on a multiselect with jQuery to display the selected values in a span element below the multiselect. The change event fires fine when selecting and deselecting elements in the list, except if I deselect the last selected element.

Here is an example (see it in jsfiddle):

<select id="multiselect" multiple>
    <optgroup label="Italian">
        <option value="CEI2008">CEI2008 — Conferenza Episcopale Italiana (2008)</option>
        <option value="LUZZI">LUZZI — Riveduta - Luzzi (1924)</option>
    </optgroup>
    <optgroup label="Latin">
        <option value="NVBSE">NVBSE — Nova Vulgata - Bibliorum Sacrorum Edition (1979)</option>
    </optgroup>
</select>

Selected versions: none

and the accompanying jquery code:

$('#multiselect').change(function(){
    var selecteditems = $(this).val();
    if(selecteditems.length===0){ $('#selectedversions').text('none'); }
    else{ $('#selectedversions').text(selecteditems.join(',')); }
});

When the last item is deselected with a CTRL-click, I would expect the change event to fire and jquery val() to return an empty array. Instead it seems that the change event is not firing at all in the case of deselecting the last selected item.

Body:
For me jQuery is not loaded properly because of poor internet connection. If you have same problem use DOM level.

$(document).on('change','#multiselect',function() {
    var value = $('#multiselect').val();
    alert(value);
});


答:
Add "/home/Me/bin" to your PATH.

Then, you can just call "script1".

Title: Executing a script in a different directory without having to use the full path

Body: I generate a bash script named "script1" and place it in the directory /home/Me/bin. I want to execute it (just by calling it's name ./script1) without the complete path from any directory. How can I do it? Is there any specific command?


问:
How do I move service references to their own assembly?
A little background:

I'm creating a set of adapters to allow communication with mobile devices over different cellular networks.  This will be achieved using a class factory pattern.  At least one of the networks requires a service reference to communicate with their devices through a web service.

So far I've got 3 assemblies so far which represent:

An assembly which contains the main adapter library: this contains

The interface definition for each of the adapters

Base classes

The class factory to instantiate the specified adapter at runtime.

An assembly for each network adapter implementation.

An assembly that contains my main application.

Given that I don't want to be adding service references and their configuration to the main application assembly [as that's not relevant to the main application], how do I force each assembly's service reference to get its configuration from its own app.config?

If I have the service reference configuration in the main app.config, everything works just fine, but if I move the configuration to the adapter's app.config everything stops working throwing the following exception at the point where I new up the Soap1Client.

"Could not find default endpoint element that references contract 'MobileService.Service1Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element."

答: You can set all the options programatically. </p>

OwnerDisplayName: balabaster

LastEditorDisplayName: balabaster

OwnerDisplayName: leppie


问:
Can we create implicit Intent to call our own Activities
Is it possible to create implicit intent to call our own activity? If possible is it useful or better option is Explicit Intent?</p>

答:
please explain your situation more...
If a single Activity is there and you want to call the same activity again from this to have any refresh sort of thing...
Then its not a good idea...

All the views can be updated without calling the same activity again.
And if new view is to be generated then use another activity


问:
Custom design listview position error
custom design Listview Blog image

i want to create something like shown in the above image, where latest blog show up and other follow the alternate layout.

i have created the odd even follow loop, but its not working, when scrolling the listview it loads from first position,

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int layoutResource = 0; // determined by view type
    int viewType = getItemViewType(position);
    switch (viewType) {
        case 0:
            layoutResource = R.layout.news_row;
            break;

        case 0:
            layoutResource = R.layout.news_row_even;
            break;

        case 1:
            layoutResource = R.layout.news_row_odd;
    }
    if (convertView == null)
        convertView = inflater.inflate(layoutResource, null);

    TextView txtNewsTitle = (TextView) convertView.findViewById(R.id.news_title);
    txtNewsTitle.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));
    txtNewsTitle.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));

    TextView txtMessage = (TextView) convertView.findViewById(R.id.message);
    txtMessage.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtMessage.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    TextView txtAgo = (TextView) convertView.findViewById(R.id.ago);
    txtAgo.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtAgo.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    int MAX_WIDTH = Utils.getScreenWidth() / 2;
    int MAX_HEIGHT = MAX_WIDTH;

    final PNewsData news = (PNewsData) getItem(position);
    int n = 0;

    Log.e("position", String.valueOf(position));

    txtNewsTitle.setText(news.title);
    txtMessage.setText(news.description.substring(0, Math.min(news.description.length(), 120)) + "...");
    txtAgo.setText(news.added);

    if (news.images.get(0).path != null) {
        p.load(Config.APP_IMAGES_URL + news.images.get(0).path)
                .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                .into(imgNewsPhoto);
    }

    return convertView;
}
</code>```

答:
First of all, there is an error in switch statement. duplicated case 0.
And, add it</p>

```<code>@Override
public int getViewTypeCount() {
    return 3;
}
</code>```

Title: Custom design listview position error

Body:
custom design Listview Blog image

i want to create something like shown in the above image, where latest blog show up and other follow the alternate layout.

i have created the odd even follow loop, but its not working, when scrolling the listview it loads from first position,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int layoutResource = 0; // determined by view type
    int viewType = getItemViewType(position);
    switch (viewType) {
        case 0:
            layoutResource = R.layout.news_row;
            break;

        case 0:
            layoutResource = R.layout.news_row_even;
            break;

        case 1:
            layoutResource = R.layout.news_row_odd;
    }
    if (convertView == null)
        convertView = inflater.inflate(layoutResource, null);

    TextView txtNewsTitle = (TextView) convertView.findViewById(R.id.news_title);
    txtNewsTitle.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));
    txtNewsTitle.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));

    TextView txtMessage = (TextView) convertView.findViewById(R.id.message);
    txtMessage.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtMessage.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    TextView txtAgo = (TextView) convertView.findViewById(R.id.ago);
    txtAgo.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtAgo.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    int MAX_WIDTH = Utils.getScreenWidth() / 2;
    int MAX_HEIGHT = MAX_WIDTH;

    final PNewsData news = (PNewsData) getItem(position);
    int n = 0;

    Log.e("position", String.valueOf(position));

    txtNewsTitle.setText(news.title);
    txtMessage.setText(news.description.substring(0, Math.min(news.description.length(), 120)) + "...");
    txtAgo.setText(news.added);

    if (news.images.get(0).path != null) {
        p.load(Config.APP_IMAGES_URL + news.images.get(0).path)
                .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                .into(imgNewsPhoto);
    }

    return convertView;
}

Body:
First of all, there is an error in switch statement. duplicated case 0.
And, add it

@Override
public int getViewTypeCount() {
    return 3;
}


答:
No.

All the tags share the same namespace. So you are not allowed to have:

```<code>struct T {...};
union T {...};
enum T {...};
</code>```

C11 draft N1570, 6.2.3 Name spaces of identifiers explicitly add s footnote.

32) There is only one name space for tags even though three are possible.

Title: Do struct tags, union tags and enum tags have separate namespaces?

Body:
No.

All the tags share the same namespace. So you are not allowed to have:

struct T {...};
union T {...};
enum T {...};

C11 draft N1570, 6.2.3 Name spaces of identifiers explicitly add s footnote.

32) There is only one name space for tags even though three are possible.


问:
How to force GCC to warn about usage of a class function?
Using GCC 4.8.*, when the warning -Wfloat-equal is activated, the compiler warns about strict comparisons between floting point number, like in the following example:

```<code>double x = 3.14159;
double y = 1.11111;
if(x == y) // <-- this induces a warning
{ /* ... */ }
</code>```

Now, imagine I want a class containing double variables and defining the equality operator:

```<code>class Complex // (it's only an example)
{
  private:
    double re;
    double im;
  public:
    bool operator == (Complex const& z) const;
};
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}
</code>```

This does exactly what I expect. Of course, it induces a warning when I compile the class. In order to avoid it (because I understand the warning, thanks to the compiler, but I want to do that, and I don't want to continue to see the warning), I inform the compiler by this way:

```<code>#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}
#pragma GCC diagnostic pop
</code>```

Okay, I don't have the warning when I compile my Complex.cpp file. But it's still dangerous to use the operator == on complex numbers, exaclty like it's dangerous to use operator == on double numbers (it's the reason for the existence of the option -Wfloat-equal). Then, my question:

Is it possible to have a GCC warning (activated by -Wfloat-equal) where the operator == on complex numbers is used ? It's not the existence of the operator I want to warn, but the usage.

Note: I defined the symmetric operator as a class member, but I'm open to have a class function bool equals(...) const called by a bool operator == (Complex const&,Complex const&) if it can simplify my expected behavior.

Note: I don't use C++11 for compatibility reasons.

答:
This seems to work (live on gcc4.8.5):

```<code>__attribute__((warning ("your message")))
bool operator == (Complex const& z) const;
</code>```

of course, you'll need to make sure the offending statement doesn't get optimized out ..

As it is, you'll need to dis/enable it manually (via some define) ... I don't know if gcc allows inspecting if a warning has been enabled or not.

Body:
Using GCC 4.8.*, when the warning -Wfloat-equal is activated, the compiler warns about strict comparisons between floting point number, like in the following example:

double x = 3.14159;
double y = 1.11111;
if(x == y) // <-- this induces a warning
{ /* ... */ }

Now, imagine I want a class containing double variables and defining the equality operator:

class Complex // (it's only an example)
{
  private:
    double re;
    double im;
  public:
    bool operator == (Complex const& z) const;
};
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}

This does exactly what I expect. Of course, it induces a warning when I compile the class. In order to avoid it (because I understand the warning, thanks to the compiler, but I want to do that, and I don't want to continue to see the warning), I inform the compiler by this way:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool Complex::operator == (Complex const& z) const
{
  return (this->re == z.re) && (this->im == z.im);
}
#pragma GCC diagnostic pop

Okay, I don't have the warning when I compile my Complex.cpp file. But it's still dangerous to use the operator == on complex numbers, exaclty like it's dangerous to use operator == on double numbers (it's the reason for the existence of the option -Wfloat-equal). Then, my question:

Is it possible to have a GCC warning (activated by -Wfloat-equal) where the operator == on complex numbers is used ? It's not the existence of the operator I want to warn, but the usage.

Note: I defined the symmetric operator as a class member, but I'm open to have a class function bool equals(...) const called by a bool operator == (Complex const&,Complex const&) if it can simplify my expected behavior.

Note: I don't use C++11 for compatibility reasons.

Body:
This seems to work (live on gcc4.8.5):

__attribute__((warning ("your message")))
bool operator == (Complex const& z) const;

of course, you'll need to make sure the offending statement doesn't get optimized out ..

As it is, you'll need to dis/enable it manually (via some define) ... I don't know if gcc allows inspecting if a warning has been enabled or not.


问:
RVM PATH is not properly set up
I've recently run into the following error from rvm when trying to upgrade my ruby version.

```<code>Warning! PATH is not properly set up, '/home/sam/.rvm/gems/ruby-2.2.1/bin' is not at first place,
</code>```

My echo $PATH is as follows:

```<code>/usr/local/heroku/bin:/home/sam/.rvm/gems/ruby-2.2.1/bin:/home/sam/.rvm/gems/ruby-2.2.1@global/bin:/home/sam/.rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin
</code>```

My .bashrc has the following lines in it

```<code>export PATH="$PATH:$HOME/.rvm/bin" # Add RVM to PATH for scripting

### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"
</code>```

And .bash_profile has:

```<code>[[ -s "$HOME/.profile" ]] && source "$HOME/.profile" # Load the default .profile

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
</code>```

And my rvm info is as follows

```<code>Warning! PATH is not properly set up, '/home/sam/.rvm/gems/ruby-2.2.1/bin' is not at first place,
         usually this is caused by shell initialization files - check them for 'PATH=...' entries,
         it might also help to re-add RVM to your dotfiles: 'rvm get stable --auto-dotfiles',
         to fix temporarily in this shell session run: 'rvm use ruby-2.2.1'.

ruby-2.2.1:

  system:
    uname:       "Linux bitey0asus 3.13.0-77-generic #121-Ubuntu SMP Wed Jan 20 10:50:42 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux"
    system:      "ubuntu/14.04/x86_64"
    bash:        "/bin/bash => GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)"
    zsh:         " => not installed"

  rvm:
    version:      "rvm 1.26.11 (latest) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]"
    updated:      "10 minutes 55 seconds ago"
    path:         "/home/sam/.rvm"

  ruby:
    interpreter:  "ruby"
    version:      "2.2.1p85"
    date:         "2015-02-26"
    platform:     "x86_64-linux"
    patchlevel:   "2015-02-26 revision 49769"
    full_version: "ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]"

  homes:
    gem:          "/home/sam/.rvm/gems/ruby-2.2.1"
    ruby:         "/home/sam/.rvm/rubies/ruby-2.2.1"

  binaries:
    ruby:         "/home/sam/.rvm/rubies/ruby-2.2.1/bin/ruby"
    irb:          "/home/sam/.rvm/rubies/ruby-2.2.1/bin/irb"
    gem:          "/home/sam/.rvm/rubies/ruby-2.2.1/bin/gem"
    rake:         "/home/sam/.rvm/rubies/ruby-2.2.1/bin/rake"

  environment:
    PATH:         "/usr/local/heroku/bin:/home/sam/.rvm/gems/ruby-2.2.1/bin:/home/sam/.rvm/gems/ruby-2.2.1@global/bin:/home/sam/.rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin"
    GEM_HOME:     "/home/sam/.rvm/gems/ruby-2.2.1"
    GEM_PATH:     "/home/sam/.rvm/gems/ruby-2.2.1:/home/sam/.rvm/gems/ruby-2.2.1@global"
    MY_RUBY_HOME: "/home/sam/.rvm/rubies/ruby-2.2.1"
    IRBRC:        "/home/sam/.rvm/rubies/ruby-2.2.1/.irbrc"
    RUBYOPT:      ""
    gemset:       ""
</code>```

I found a solution to a similar problem here.  But apparently not close enough (the proposed solution had no effect).

Anyway if anyone has any ideas, I'd appreciate it.  I'm a little clueless on the ins and outs of rvm so I'm a bit in the dark here.  Thanks in advance

Edit:

I tried reversing the order of the two rvm lines in my .bashrc but this did not help the error, nor did it change the order shown by echo $PATH.

答:
To solve it I just changed in my .profile file:

```<code>PATH="$HOME/bin:$HOME/.local/bin:$PATH"
</code>```

to

```<code>PATH="$PATH:$HOME/bin:$HOME/.local/bin"
</code>```

Title: RVM PATH is not properly set up

Body:
I've recently run into the following error from rvm when trying to upgrade my ruby version.

Warning! PATH is not properly set up, '/home/sam/.rvm/gems/ruby-2.2.1/bin' is not at first place,

My echo $PATH is as follows:

/usr/local/heroku/bin:/home/sam/.rvm/gems/ruby-2.2.1/bin:/home/sam/.rvm/gems/ruby-2.2.1@global/bin:/home/sam/.rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin

My .bashrc has the following lines in it

export PATH="$PATH:$HOME/.rvm/bin" # Add RVM to PATH for scripting

### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"

And .bash_profile has:

[[ -s "$HOME/.profile" ]] && source "$HOME/.profile" # Load the default .profile

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

And my rvm info is as follows

Warning! PATH is not properly set up, '/home/sam/.rvm/gems/ruby-2.2.1/bin' is not at first place,
         usually this is caused by shell initialization files - check them for 'PATH=...' entries,
         it might also help to re-add RVM to your dotfiles: 'rvm get stable --auto-dotfiles',
         to fix temporarily in this shell session run: 'rvm use ruby-2.2.1'.

ruby-2.2.1:

  system:
    uname:       "Linux bitey0asus 3.13.0-77-generic #121-Ubuntu SMP Wed Jan 20 10:50:42 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux"
    system:      "ubuntu/14.04/x86_64"
    bash:        "/bin/bash => GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)"
    zsh:         " => not installed"

  rvm:
    version:      "rvm 1.26.11 (latest) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]"
    updated:      "10 minutes 55 seconds ago"
    path:         "/home/sam/.rvm"

  ruby:
    interpreter:  "ruby"
    version:      "2.2.1p85"
    date:         "2015-02-26"
    platform:     "x86_64-linux"
    patchlevel:   "2015-02-26 revision 49769"
    full_version: "ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]"

  homes:
    gem:          "/home/sam/.rvm/gems/ruby-2.2.1"
    ruby:         "/home/sam/.rvm/rubies/ruby-2.2.1"

  binaries:
    ruby:         "/home/sam/.rvm/rubies/ruby-2.2.1/bin/ruby"
    irb:          "/home/sam/.rvm/rubies/ruby-2.2.1/bin/irb"
    gem:          "/home/sam/.rvm/rubies/ruby-2.2.1/bin/gem"
    rake:         "/home/sam/.rvm/rubies/ruby-2.2.1/bin/rake"

  environment:
    PATH:         "/usr/local/heroku/bin:/home/sam/.rvm/gems/ruby-2.2.1/bin:/home/sam/.rvm/gems/ruby-2.2.1@global/bin:/home/sam/.rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin:/home/sam/.rvm/bin"
    GEM_HOME:     "/home/sam/.rvm/gems/ruby-2.2.1"
    GEM_PATH:     "/home/sam/.rvm/gems/ruby-2.2.1:/home/sam/.rvm/gems/ruby-2.2.1@global"
    MY_RUBY_HOME: "/home/sam/.rvm/rubies/ruby-2.2.1"
    IRBRC:        "/home/sam/.rvm/rubies/ruby-2.2.1/.irbrc"
    RUBYOPT:      ""
    gemset:       ""

I found a solution to a similar problem here.  But apparently not close enough (the proposed solution had no effect).

Anyway if anyone has any ideas, I'd appreciate it.  I'm a little clueless on the ins and outs of rvm so I'm a bit in the dark here.  Thanks in advance

Edit:

I tried reversing the order of the two rvm lines in my .bashrc but this did not help the error, nor did it change the order shown by echo $PATH.

Body:
To solve it I just changed in my .profile file:

PATH="$HOME/bin:$HOME/.local/bin:$PATH"

to

PATH="$PATH:$HOME/bin:$HOME/.local/bin"


问:
Fotify scan with visual studio 2005 fails
I am trying to scan the C/C++/COM code with fortify 360 (SCA) through visual studio 2005 interface.

The compilation goes through fine. But, fortify scan fails with warning " scan failed: value does not fall under within range".

Please let me know how can we resolve this issue.

Thanks in advance.

答:
In your solution's build configuration, you need to set the target architecture to "Any CPU".

If that doesn't solve the problem, you need to contact Fortify Technical Support.


问:
Wordpress og:image not working in whatsapp?
I had created a Wordpress news website. There are many sharing options implemented! I added WhatsApp and send the URL to WhatsApp and share to WhatsApp! The issue is, initially the post image is shown when I share the link in WhatsApp. But now the image is not showing while I share the link in WhatsApp! There are no issues while sharing on facebook! When I inspect the page source WordPress automatically gives og:image as the post feature image! But it does not show up in WhatsApp. But when I copy paste the same og:image to header.php I WordPress it works perfectly! Initially, I thought of the size problem while later I found out that size is as per the og:image meta tag standard.

Here i post the single.php code:

```<code><?php
/**
 * NewsGamer Theme
 *
 * Theme by: MipThemes
 * http://themes.mipdesign.com
 *
 * Our portfolio: http://themeforest.net/user/mip/portfolio
 * Thanks for using our theme!
 *
 */

// load header
get_header();

// Get Page properties
$mip_current_page   = new MipThemeFramework_Page();

// Update Post View
MipThemeFramework_Post_Views::update_post_views($post->ID);

// Load Custom post headers
get_template_part( 'elements/parts/post-header-'. $mip_current_page->page_template .'' );
?>

    <!-- start:post-info-bar -->
    <?php if ($mip_current_page->enable_post_info_bar) get_template_part( 'elements/post-info-bar' ); ?>
    <!-- end:post-info-bar -->

    <!-- start:page content -->
    <div id="page-content" class="<?php echo esc_attr($mip_current_page->page_template_class); ?> clearfix">

        <?php
            //get sidebar
            if ( ($mip_current_page->page_sidebar_template == 'left-sidebar')&&(!wp_is_mobile()) ) get_sidebar();
        ?>

        <!-- start:main -->
        <div id="main" class="main article">
            <!-- start:article post -->
            <article id="post-<?php echo esc_attr($post->ID); ?>" <?php post_class('article-post clearfix'); ?> <?php echo MipThemeFramework_Util::get_item_scope( $mip_current_page->review_post ); ?>>
            <?php
                if (have_posts()) :
                    // Get Template
                    get_template_part( 'elements/'. $mip_current_page->page_template .'' );
                else :
                    // No Posts
                    esc_html_e('No posts.', 'newsgamer');
                endif;
            ?>
            </article>
            <!-- end:article post -->
        </div>
        <!-- end:main -->

        <?php
            //get sidebar
            if ( ($mip_current_page->page_sidebar_template == 'right-sidebar')||( ($mip_current_page->page_sidebar_template == 'left-sidebar')&&(wp_is_mobile()) ) ) get_sidebar();
        ?>

    </div>
    <!-- end:page content -->

<?php
    // load footer
    get_footer();
?>
</code>```

答:
I have had the same problem, everything worked fine in any opengraph testing tool and in the social sites themself's: facebook, twitter, ok, vk but in whatsapp & telegram not.

So after a lot of research, the problem was in our virtual site firewall that protects from site crawling by many logics, a couple of them is IP and User-Agent. The whatsapp & telegram are pinging sites to fetch og data are not throw their servers like social sites, but through your mobile operator's dynamic IP, but the user-agent is of the messenger itself, and it was in our automatically generated blacklist.

Check if you don't ban access to your site by theirs user-agents string that contains: WhatsApp/2.17.395 A or TelegramBot (like TwitterBot)

Wish it helped.

Body:
I had created a Wordpress news website. There are many sharing options implemented! I added WhatsApp and send the URL to WhatsApp and share to WhatsApp! The issue is, initially the post image is shown when I share the link in WhatsApp. But now the image is not showing while I share the link in WhatsApp! There are no issues while sharing on facebook! When I inspect the page source WordPress automatically gives og:image as the post feature image! But it does not show up in WhatsApp. But when I copy paste the same og:image to header.php I WordPress it works perfectly! Initially, I thought of the size problem while later I found out that size is as per the og:image meta tag standard.

Here i post the single.php code:

<?php
/**
 * NewsGamer Theme
 *
 * Theme by: MipThemes
 * http://themes.mipdesign.com
 *
 * Our portfolio: http://themeforest.net/user/mip/portfolio
 * Thanks for using our theme!
 *
 */

// load header
get_header();

// Get Page properties
$mip_current_page   = new MipThemeFramework_Page();

// Update Post View
MipThemeFramework_Post_Views::update_post_views($post->ID);

// Load Custom post headers
get_template_part( 'elements/parts/post-header-'. $mip_current_page->page_template .'' );
?>

    <?php if ($mip_current_page->enable_post_info_bar) get_template_part( 'elements/post-info-bar' ); ?>

    <div id="page-content" class="<?php echo esc_attr($mip_current_page->page_template_class); ?> clearfix">

        <?php
            //get sidebar
            if ( ($mip_current_page->page_sidebar_template == 'left-sidebar')&&(!wp_is_mobile()) ) get_sidebar();
        ?>

            <article id="post-<?php echo esc_attr($post->ID); ?>" <?php post_class('article-post clearfix'); ?> <?php echo MipThemeFramework_Util::get_item_scope( $mip_current_page->review_post ); ?>>
            <?php
                if (have_posts()) :
                    // Get Template
                    get_template_part( 'elements/'. $mip_current_page->page_template .'' );
                else :
                    // No Posts
                    esc_html_e('No posts.', 'newsgamer');
                endif;
            ?>

        <?php
            //get sidebar
            if ( ($mip_current_page->page_sidebar_template == 'right-sidebar')||( ($mip_current_page->page_sidebar_template == 'left-sidebar')&&(wp_is_mobile()) ) ) get_sidebar();
        ?>

<?php
    // load footer
    get_footer();
?>


问:
Is there a way to monitor kube cron jobs using prometheus
Is there a way to monitor kube cronjob?

I have a kube cronjob which runs every 10mins on my cluster. Is there a way to collect metrics every time my cronjob fails due to some error  or notify when my cronjob has not been completed after a certain period of time?

答: The kube-state-metrics exporter also includes various CronJob related metrics: https://github.com/kubernetes/kube-state-metrics/blob/master/Documentation/cronjob-metrics.md, but unfortunately doesn't seem to include success CronJob success/failure.  </p>

ContentLicense: CC BY-SA 4.0


问:
Performing function on user permissions granting result?
I ask the user if they will allow notifications, I then want to animate a tick if they approve. Im unsure how to achieve this as permissions are async and i cant then detect a result instantly to perform a func?

Here is my current code:

user taps button and triggers a call to grant permissions with a closure to tick the button on completion

```<code>func userDidTapNotifications() {
    self.appDelegate.setupNotifications { (success) -> Void in
        if success {
            notificationsGranted()
        }
    }
}
</code>```

function presents the approval pop up and completes closure, issue is that it will complete before the user has picked a choice as its async, so im completing true before the user has granted access, causing issues.

```<code>func setupNotifications(completion: (_ success: Bool) -> Void) {
    center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }
    completion(true)
}
</code>```

after this I call my final func on completion of closure:

```<code>func notificationsGranted() {
    let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
    if isRegisteredForRemoteNotifications {
        self.permissionsView.notificationsSwitch.setSelected(true, animated: true)
        self.userDefaults.set(true, forKey: "notificationsApproved")
        arePermissionsGranted()
    }
}
</code>```

What would be the correct approach to present the permissions alert, then take action based on a response?

答:
Store you completion handler in a global object in your AppDelegate and when didRegisterRemoteNotification method is invoke then just invoke the completion handler that you have stored...
And in your ViewController you should call setUpNotification method.

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var notificationCompletion: ((Bool)->Void)?

    func setUpNotification(completion: @escaping (Bool)->Void) {
        self.notificationCompletion = completion //Store the completion in a global property to use later.

        //Invoke Your Notification Registration methods...
        //Do not invoke the completion handle here...
    }
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //Permission is granted. Now invoke the completion that you have store to use later.
        if let completion = self.notificationCompletion {
            completion(true)
        }
    }
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //Permission is not granted/failed. Now invoke the completion that you have store to use later.
        if let completion = self.notificationCompletion {
            completion(false)
        }
    }
}

ViewController.swift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.setUpNotification(completion: { isPermissionGranted in
                if isPermissionGranted {
                    DispatchQueue.main.async {
                        self.notificationPermissionIsGranted()
                    }
                }

            })
        }
    }
    func notificationPermissionIsGranted() {
        //Animate Your View..
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Body:
I ask the user if they will allow notifications, I then want to animate a tick if they approve. Im unsure how to achieve this as permissions are async and i cant then detect a result instantly to perform a func?

Here is my current code:

user taps button and triggers a call to grant permissions with a closure to tick the button on completion

func userDidTapNotifications() {
    self.appDelegate.setupNotifications { (success) -> Void in
        if success {
            notificationsGranted()
        }
    }
}

function presents the approval pop up and completes closure, issue is that it will complete before the user has picked a choice as its async, so im completing true before the user has granted access, causing issues.

func setupNotifications(completion: (_ success: Bool) -> Void) {
    center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }
    completion(true)
}

after this I call my final func on completion of closure:

func notificationsGranted() {
    let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
    if isRegisteredForRemoteNotifications {
        self.permissionsView.notificationsSwitch.setSelected(true, animated: true)
        self.userDefaults.set(true, forKey: "notificationsApproved")
        arePermissionsGranted()
    }
}

What would be the correct approach to present the permissions alert, then take action based on a response?

Body:
Store you completion handler in a global object in your AppDelegate and when didRegisterRemoteNotification method is invoke then just invoke the completion handler that you have stored...
And in your ViewController you should call setUpNotification method.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var notificationCompletion: ((Bool)->Void)?

    func setUpNotification(completion: @escaping (Bool)->Void) {
        self.notificationCompletion = completion //Store the completion in a global property to use later.

        //Invoke Your Notification Registration methods...
        //Do not invoke the completion handle here...
    }
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //Permission is granted. Now invoke the completion that you have store to use later.
        if let completion = self.notificationCompletion {
            completion(true)
        }
    }
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //Permission is not granted/failed. Now invoke the completion that you have store to use later.
        if let completion = self.notificationCompletion {
            completion(false)
        }
    }
}

ViewController.swift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.setUpNotification(completion: { isPermissionGranted in
                if isPermissionGranted {
                    DispatchQueue.main.async {
                        self.notificationPermissionIsGranted()
                    }
                }

            })
        }
    }
    func notificationPermissionIsGranted() {
        //Animate Your View..
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


答:
The answer to your question:

Tag names: all identifiers declared as names of structs, unions and enumerated types. Note that all three kinds of tags share one name space.

Just quoting this from reference guide.

At the point of lookup, the name space of an identifier is determined by the manner in which it is used:

identifier that follows the keyword struct, union, or enum is looked up in the tag name space.


问:
Vivado 2015.1 VHDL Input/ Output Violation
I am getting through the tutorial of Nexys 4 DDR and I am implementing a simple MUX

```<code>library IEEE;

use IEEE.STD_LOGIC_1164.ALL;

library UNISIM;
use UNISIM.VComponents.all;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity lab1_2_1 is
    Port ( SW0 : in STD_LOGIC;
           SW1 : in STD_LOGIC;
           SW2 : in STD_LOGIC;
           LED0 : out STD_LOGIC);
end lab1_2_1;

architecture Behavioral of lab1_2_1 is

            Signal SW2_bar : STD_LOGIC;
            Signal SW0_int : STD_LOGIC;
            Signal SW1_int : STD_LOGIC;

begin
            SW2_bar <= not SW2;
            SW0_int <= SW0 and SW2_bar;
            SW1_int <= SW1 and SW2;
            LED0 <= SW0_int or SW1_int;

end Behavioral;
</code>```

When I get to the part of generating a bitstream, I get this critical warning

NSTD #1 Critical Warning 1 out of 1 logical ports use I/O standard (IOSTANDARD) value 'DEFAULT', instead of a user assigned specific value. This may cause I/O contention or incompatibility with the board power or connectivity affecting performance, signal integrity or in extreme cases cause damage to the device or the components to which it is connected. To correct this violation, specify all I/O standards. This design will fail to generate a bitstream unless all logical ports have a user specified I/O standard value defined. To allow bitstream creation with unspecified I/O standard values (not recommended), use this command: set_property SEVERITY {Warning} [get_drc_checks NSTD-1].  NOTE: When using the Vivado Runs infrastructure (e.g. launch_runs Tcl command), add this command to a .tcl file and add that file as a pre-hook for write_bitstream step for the implementation run. Problem ports: LED0.

and

UCIO #1 Critical Warning 1 out of 1 logical ports have no user assigned specific location constraint (LOC). This may cause I/O contention or incompatibility with the board power or connectivity affecting performance, signal integrity or in extreme cases cause damage to the device or the components to which it is connected. To correct this violation, specify all pin locations. This design will fail to generate a bitstream unless all logical ports have a user specified site LOC constraint defined.  To allow bitstream creation with unspecified pin locations (not recommended), use this command: set_property SEVERITY {Warning} [get_drc_checks UCIO-1].  NOTE: When using the Vivado Runs infrastructure (e.g. launch_runs Tcl command), add this command to a .tcl file and add that file as a pre-hook for write_bitstream step for the implementation run.  Problem ports: LED0.

Any Ideas?

答:
Vivado expects you to define physical locations of the IOs and IO standards. IO standard depends on the voltage level and pull-up/pull-down resistors connected to pins of the FPGA.

You may add those into a constraint file (e.g. SDC or XDC). For example, I assigned output LED0 to pin A1 of the FPGA and defined the IO standard as 2.5V LVCMOS. The correct values can be found in the manual of your FPGA board.

```<code>set_property PACKAGE_PIN A1       [get_ports {LED0}];
set_property IOSTANDARD  LVCMOS25 [get_ports {LED0}];
</code>```

Body:
I am getting through the tutorial of Nexys 4 DDR and I am implementing a simple MUX

library IEEE;

use IEEE.STD_LOGIC_1164.ALL;

library UNISIM;
use UNISIM.VComponents.all;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity lab1_2_1 is
    Port ( SW0 : in STD_LOGIC;
           SW1 : in STD_LOGIC;
           SW2 : in STD_LOGIC;
           LED0 : out STD_LOGIC);
end lab1_2_1;

architecture Behavioral of lab1_2_1 is

            Signal SW2_bar : STD_LOGIC;
            Signal SW0_int : STD_LOGIC;
            Signal SW1_int : STD_LOGIC;

begin
            SW2_bar <= not SW2;
            SW0_int <= SW0 and SW2_bar;
            SW1_int <= SW1 and SW2;
            LED0 <= SW0_int or SW1_int;

end Behavioral;

When I get to the part of generating a bitstream, I get this critical warning

NSTD #1 Critical Warning 1 out of 1 logical ports use I/O standard (IOSTANDARD) value 'DEFAULT', instead of a user assigned specific value. This may cause I/O contention or incompatibility with the board power or connectivity affecting performance, signal integrity or in extreme cases cause damage to the device or the components to which it is connected. To correct this violation, specify all I/O standards. This design will fail to generate a bitstream unless all logical ports have a user specified I/O standard value defined. To allow bitstream creation with unspecified I/O standard values (not recommended), use this command: set_property SEVERITY {Warning} [get_drc_checks NSTD-1].  NOTE: When using the Vivado Runs infrastructure (e.g. launch_runs Tcl command), add this command to a .tcl file and add that file as a pre-hook for write_bitstream step for the implementation run. Problem ports: LED0.

and

UCIO #1 Critical Warning 1 out of 1 logical ports have no user assigned specific location constraint (LOC). This may cause I/O contention or incompatibility with the board power or connectivity affecting performance, signal integrity or in extreme cases cause damage to the device or the components to which it is connected. To correct this violation, specify all pin locations. This design will fail to generate a bitstream unless all logical ports have a user specified site LOC constraint defined.  To allow bitstream creation with unspecified pin locations (not recommended), use this command: set_property SEVERITY {Warning} [get_drc_checks UCIO-1].  NOTE: When using the Vivado Runs infrastructure (e.g. launch_runs Tcl command), add this command to a .tcl file and add that file as a pre-hook for write_bitstream step for the implementation run.  Problem ports: LED0.

Any Ideas?

Body:
Vivado expects you to define physical locations of the IOs and IO standards. IO standard depends on the voltage level and pull-up/pull-down resistors connected to pins of the FPGA.

You may add those into a constraint file (e.g. SDC or XDC). For example, I assigned output LED0 to pin A1 of the FPGA and defined the IO standard as 2.5V LVCMOS. The correct values can be found in the manual of your FPGA board.

set_property PACKAGE_PIN A1       [get_ports {LED0}];
set_property IOSTANDARD  LVCMOS25 [get_ports {LED0}];


问:
how to resize dynamically markers on a map
My exercise with Leaflet.js : resize the icon of a marker when zooming in or out by modifying the iconSize option (ie not by changing the icon source).

I tried this :

```<code>function resize(e) {

  for (const marker of markers) {

    const newY = marker.options.icon.options.iconSize.y * (mymap.getZoom() / parameterInitZoom);
    const newX = marker.options.icon.options.iconSize.x * (mymap.getZoom() / parameterInitZoom);

    marker.setIcon(marker.options.icon.options.iconsize = [newX, newY]);
  }
}

mymap.on('zoomend', resize)
</code>```

but I ended up with :
t.icon.createIcon is not a function

I saw also the method muliplyBy but couldn't find out the way to make it work.
How to do it ?

答:
What I did finally, and it's working well : </p>

```<code>let factor;
let markers = [];

//New class of icons
const MyIcon = L.Icon.extend({
  options: {
    iconSize: new L.Point(iconInitWidth, iconInitHeight) //Define your iconInitWidth and iconInitHeight before
  },
});

/*------------ Functions - Callbacks ----------------*/
//Small function to keep the factor up to date with the current zoom
function updateFactor() {
  let currentZoom = mymap.getZoom();
  factor = Math.pow(currentZoom / mymap.options.zoom, 5);
};
updateFactor();

//Create a new marker
function makeMarker(e) {
  const newX = Math.round(iconInitWidth * factor);
  const newY = newX * iconInitHeight / iconInitWidth;

  const newMarker = new L.Marker(new L.LatLng(e.latlng.lat, e.latlng.lng), {
    icon: new MyIcon({ iconSize: new L.Point(newX, newY) })
  }).addTo(mymap);

  markers[markers.length] = newMarker;
}

//Update the marker
function resize(e) {
  updateFactor();

  for (const marker of markers) {

    const newX = Math.round(iconInitWidth * factor);
    const newY = newX * iconInitHeight / iconInitWidth;

    marker.setIcon(new MyIcon({ iconSize: new L.Point(newX, newY) }));
  }
}

/*------------ Event listeners ----------------*/
mymap.addEventListener('click', makeMarker);
mymap.on('zoom', resize);
</code>```

Body:
My exercise with Leaflet.js : resize the icon of a marker when zooming in or out by modifying the iconSize option (ie not by changing the icon source).

I tried this :

function resize(e) {

  for (const marker of markers) {

    const newY = marker.options.icon.options.iconSize.y * (mymap.getZoom() / parameterInitZoom);
    const newX = marker.options.icon.options.iconSize.x * (mymap.getZoom() / parameterInitZoom);

    marker.setIcon(marker.options.icon.options.iconsize = [newX, newY]);
  }
}

mymap.on('zoomend', resize)

but I ended up with :
t.icon.createIcon is not a function

I saw also the method muliplyBy but couldn't find out the way to make it work.
How to do it ?

Body:
What I did finally, and it's working well :

let factor;
let markers = [];

//New class of icons
const MyIcon = L.Icon.extend({
  options: {
    iconSize: new L.Point(iconInitWidth, iconInitHeight) //Define your iconInitWidth and iconInitHeight before
  },
});

/*------------ Functions - Callbacks ----------------*/
//Small function to keep the factor up to date with the current zoom
function updateFactor() {
  let currentZoom = mymap.getZoom();
  factor = Math.pow(currentZoom / mymap.options.zoom, 5);
};
updateFactor();

//Create a new marker
function makeMarker(e) {
  const newX = Math.round(iconInitWidth * factor);
  const newY = newX * iconInitHeight / iconInitWidth;

  const newMarker = new L.Marker(new L.LatLng(e.latlng.lat, e.latlng.lng), {
    icon: new MyIcon({ iconSize: new L.Point(newX, newY) })
  }).addTo(mymap);

  markers[markers.length] = newMarker;
}

//Update the marker
function resize(e) {
  updateFactor();

  for (const marker of markers) {

    const newX = Math.round(iconInitWidth * factor);
    const newY = newX * iconInitHeight / iconInitWidth;

    marker.setIcon(new MyIcon({ iconSize: new L.Point(newX, newY) }));
  }
}

/*------------ Event listeners ----------------*/
mymap.addEventListener('click', makeMarker);
mymap.on('zoom', resize);


问:
Difference in raster values between R and QGIS
I want to ask what probably is a basic question about the way in which R and QGIS import raster files.

I have a single band-raster. When I import it into R, using the "raster" function of the raster package, I get this range of pixel values:

```<code>class       : RasterLayer
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /data/MTDA/CGS_S2_RADIOMETRY/2017/10/15/S2B_20171015T104525Z_31UFS_TOC_V100/S2B_20171015T104525Z_31UFS_TOC-B02_10M_V100.tif
names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -32768, 32767  (min, max)
</code>```

When I stack this layer in a raster brick, I get these min-max values:

```<code>class       : RasterLayer
band        : 2  (of  11  bands)
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /tmp/Rtmp882dZS/raster/r_tmp_2017-11-10_172819_11532_86514.grd

names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -1129, 9994  (min, max)
</code>```

However, if I load the same raster in QGIS, the min value is 228 and the max value is 907 (I calculated these values with the options "Extent: Full" and "Accuracy: Actual (slower)".

So, where do these differences come from? I do not understand exactly what R and QGIS are doing...

答:
In the end, I found what is the difference about!
When asking to R, I get the real min/max values. QGIS, instead, calculates the min/max values with a cumulative count. When I set the "Load min/max values" (in the Raster Properties window) to "Min/Max" I got the same values R showed.</p>

Body:
I want to ask what probably is a basic question about the way in which R and QGIS import raster files.

I have a single band-raster. When I import it into R, using the "raster" function of the raster package, I get this range of pixel values:

class       : RasterLayer
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /data/MTDA/CGS_S2_RADIOMETRY/2017/10/15/S2B_20171015T104525Z_31UFS_TOC_V100/S2B_20171015T104525Z_31UFS_TOC-B02_10M_V100.tif
names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -32768, 32767  (min, max)

When I stack this layer in a raster brick, I get these min-max values:

class       : RasterLayer
band        : 2  (of  11  bands)
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /tmp/Rtmp882dZS/raster/r_tmp_2017-11-10_172819_11532_86514.grd

names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -1129, 9994  (min, max)

However, if I load the same raster in QGIS, the min value is 228 and the max value is 907 (I calculated these values with the options "Extent: Full" and "Accuracy: Actual (slower)".

So, where do these differences come from? I do not understand exactly what R and QGIS are doing...


问:
Switch statement with boolean is not working?
Why is my compiler telling me:

Incompatible Types:

Required: Boolean

Found: Int

under case 0 & case 1

For instance:

```<code>    public void test(boolean isOn){
    switch (isOn){
        case 0:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 1:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }
</code>```

}

Driver Class:

```<code>Club me = new Club();
me.test(true);
</code>```

答:
In Java, Switch does NOT work with Boolean.

Accepted variable types are :
char,byte,short,int,String,Character,Byte,Short,Integer,enum

Body:
Why is my compiler telling me:

Incompatible Types:

Required: Boolean

Found: Int

under case 0 & case 1

For instance:

    public void test(boolean isOn){
    switch (isOn){
        case 0:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 1:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }

}

Driver Class:

Club me = new Club();
me.test(true);