问:
Failed to load resource: the server responded with a status of 404 - google sheets
I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

index.html

```<code><!DOCTYPE html>
    <html lang='en'>
        <head>
            <meta charset='utf-8'>
            <meta content='IE=edge' http-equiv='X-UA-Compatible'>
            <meta content='width=device-width, initial-scale=1' name='viewport'>
        </head>

        <body>

            <!-- Contact Form - sent to a Google Sheet -->

            <form id='foo'>

        <p>
            <label>Name</label>
            <input id='name' name='name' type='text'>
        </p>

        <p>
            <label>Email Address</label>
            <input id='email' name='email' type='email'>
        </p>

        <p>
            <label>Phone Number</label>
            <input id='phone' name='phone' type='tel'>
        </p>

        <p>
            <label>Message</label>
            <textarea id='message' name='message' rows='5'></textarea>
        </p>

            <div id='success'></div>
                <button type='submit'>Send</button>
            </form>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

            <!-- Custom Theme JavaScript -->
        <script src='google-sheet.js'></script>
    </html>
</code>```

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google-sheet.js

```<code>// Variable to hold request
var request;

// Bind to the submit event of our form
     $("#foo").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "https://script.google.com/macros/u/0/s/AKfycbzBcGD8jJ2fblphRDVkwtxjUm23TNawFXPHPqZ4wZAyP-EfWQ/exec",
        type: "post",
        data: serializedData

    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});
</code>```

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google script

```<code>//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "FormSheet";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

    var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function

    function doGet(e){
      return handleResponse(e);
    }

    function doPost(e){
    return handleResponse(e);
    }

    function handleResponse(e) {

  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations

      var lock = LockService.getPublicLock();
      lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

      try {
    // next set where we write the data - you could write to multiple/alternate destinations

        var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
        var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data

        var headRow = e.parameter.header_row || 1;
        var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
        var nextRow = sheet.getLastRow()+1; // get next row
        var row = [];

    // loop through the header columns

        for (i in headers){
          if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
            row.push(new Date());
          } else { // else use header name to get data
            row.push(e.parameter[headers[i]]);
          }
        }
    // more efficient to set values as [][] array than individually

        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results

        return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
      } catch(e){

    // if error return this

        return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
      } finally { //release lock
        lock.releaseLock();
      }
    }

    function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
    }
</code>```

The Form:

答:
Use google.script.run.  With it you can run any script that is inside of your project.  Reference

This is a simple example of a web app that puts an editable spreadsheet on an HTML Page.  Publish as a webapp.

Code.gs:

```<code>var SSID='SpreadsheetID';
var sheetName='Sheet Name';
function htmlSpreadsheet(mode)
{
  var mode=(typeof(mode)!='undefined')?mode:'dialog';
  var br='<br />';
  var s='';
  var hdrRows=1;
  var ss=SpreadsheetApp.openById(SSID);
  var sht=ss.getSheetByName(sheetName);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  s+='<table>';
  for(var i=0;i<rngA.length;i++)
  {
    s+='<tr>';
    for(var j=0;j<rngA[i].length;j++)
    {
      if(i<hdrRows)
      {
        s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
      }
      else
      {
        s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
      }
    }
    s+='</tr>';
  }
  s+='</table>';
  //s+='<div id="success"></div>';
  s+='</body></html>';
  switch (mode)
  {
    case 'dialog':
      var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
      userInterface.append(s);
      SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
      break;
    case 'web':
      var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
      return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
   }
}

function updateSpreadsheet(i,j,value)
{
  var ss=SpreadsheetApp.openById(SSID);
  var sht=ss.getSheetByName(sheetName);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  rngA[i][j]=value;
  rng.setValues(rngA);
  var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
  return data;
}

function doGet()
{
  var output=htmlSpreadsheet('web');
  return output;
}
</code>```

htmlss.html:

```<code><!DOCTYPE html>
<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    $(function() {

    });
    function updateSS(i,j)
    {
      var str='#txt' + String(i) + String(j);
      var value=$(str).val();
      $(str).css('background-color','#ffff00');
      google.script.run
         .withSuccessHandler(successHandler)
         .updateSpreadsheet(i,j,value)
    }
    function successHandler(data)
    {
      $('#success').text(data.message);
      $('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
    }
    console.log('My Code');
    </script>
    <style>
      th{text-align:left}
    </style>
  </head>
  <body>
  <div id="success"></div>
</code>```

Body:
I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

index.html

<!DOCTYPE html>

            <meta charset='utf-8'>
            <meta content='IE=edge' http-equiv='X-UA-Compatible'>
            <meta content='width=device-width, initial-scale=1' name='viewport'>

            <form id='foo'>

            Name
            <input id='name' name='name' type='text'>

            Email Address
            <input id='email' name='email' type='email'>

            Phone Number
            <input id='phone' name='phone' type='tel'>

            Message
            <textarea id='message' name='message' rows='5'></textarea>

                <button type='submit'>Send</button>
            </form>

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google-sheet.js

// Variable to hold request
var request;

// Bind to the submit event of our form
     $("#foo").submit(function(event){

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "https://script.google.com/macros/u/0/s/AKfycbzBcGD8jJ2fblphRDVkwtxjUm23TNawFXPHPqZ4wZAyP-EfWQ/exec",
        type: "post",
        data: serializedData

    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});

I am attempting to send data from a html form to google sheets document. I keep getting the "Failed to load resource: the server responded with a status of 404" error. Can someone please provide assistance?

google script

//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "FormSheet";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

    var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function

    function doGet(e){
      return handleResponse(e);
    }

    function doPost(e){
    return handleResponse(e);
    }

    function handleResponse(e) {

  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations

      var lock = LockService.getPublicLock();
      lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

      try {
    // next set where we write the data - you could write to multiple/alternate destinations

        var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
        var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data

        var headRow = e.parameter.header_row || 1;
        var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
        var nextRow = sheet.getLastRow()+1; // get next row
        var row = [];

    // loop through the header columns

        for (i in headers){
          if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
            row.push(new Date());
          } else { // else use header name to get data
            row.push(e.parameter[headers[i]]);
          }
        }
    // more efficient to set values as [][] array than individually

        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results

        return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
      } catch(e){

    // if error return this

        return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
      } finally { //release lock
        lock.releaseLock();
      }
    }

    function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
    }

The Form:

Body:
Use google.script.run.  With it you can run any script that is inside of your project.  Reference

This is a simple example of a web app that puts an editable spreadsheet on an HTML Page.  Publish as a webapp.

Code.gs:

var SSID='SpreadsheetID';
var sheetName='Sheet Name';
function htmlSpreadsheet(mode)
{
  var mode=(typeof(mode)!='undefined')?mode:'dialog';
  var br='<br />';
  var s='';
  var hdrRows=1;
  var ss=SpreadsheetApp.openById(SSID);
  var sht=ss.getSheetByName(sheetName);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  s+='<table>';
  for(var i=0;i<rngA.length;i++)
  {
    s+='<tr>';
    for(var j=0;j<rngA[i].length;j++)
    {
      if(i<hdrRows)
      {
        s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
      }
      else
      {
        s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
      }
    }
    s+='</tr>';
  }
  s+='</table>';
  //s+='<div id="success"></div>';
  s+='</body></html>';
  switch (mode)
  {
    case 'dialog':
      var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
      userInterface.append(s);
      SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
      break;
    case 'web':
      var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
      return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
   }
}

function updateSpreadsheet(i,j,value)
{
  var ss=SpreadsheetApp.openById(SSID);
  var sht=ss.getSheetByName(sheetName);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  rngA[i][j]=value;
  rng.setValues(rngA);
  var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
  return data;
}

function doGet()
{
  var output=htmlSpreadsheet('web');
  return output;
}

htmlss.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    $(function() {

    });
    function updateSS(i,j)
    {
      var str='#txt' + String(i) + String(j);
      var value=$(str).val();
      $(str).css('background-color','#ffff00');
      google.script.run
         .withSuccessHandler(successHandler)
         .updateSpreadsheet(i,j,value)
    }
    function successHandler(data)
    {
      $('#success').text(data.message);
      $('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
    }
    console.log('My Code');
    </script>
    <style>
      th{text-align:left}
    </style>
  </head>
  <body>
  <div id="success"></div>


来源: stackexchange

问:
Call a function in directive template
I have a directive like this

```<code>  app.directive('clipChat', ClipChat);

function ClipChat() {
    var strfin ='*';
    var chatTemplate = '<div ng-repeat="message in newarr">   <span ng-if="message.content.slice(-1)==message.star"  ng-click="makeitTodo(message)">i <i class="fa fa-mail-forward "></i></span> '+ '</div>' ;
    var directive = {
        restrict: 'EA',
        template: chatTemplate,
        replace: true,
        scope: {
            messages: "=",
            idSelf: "=",
            idOther: "=",

        },

        link:function ($scope) {
</code>```

//etc etc

I want to call the function makeitTodo when i click the span element inside my controller..

I have tested like the following.

```<code>app.controller('ChatCtrl',  ["$scope",function($scope){
 $scope.makeitTodo = function(a){
  alert(a);
}
}])
</code>```

But it is not working.. PLease help me.

答:
Isolated scope function binding is missing

Sample Fiddler: https://jsfiddle.net/paka2/9yda0cLk
`

```<code>angular.module('myApp', []).controller('myCtrl', function($scope) {
    $scope.makeitTodo = function(message) {
    console.log(message);
    }
}).directive('clipChat', function() {
    return {
    restrict: "E",
        scope: { done: '&' },
        template: '<input type="text" ng-model="message">'+
        '<button ng-click="done({message:message})"> click me </button>'
    }
});;
</code>```

`

ContentLicense: CC BY-SA 3.0

Title: Call a function in directive template

Body:
I have a directive like this

  app.directive('clipChat', ClipChat);

function ClipChat() {
    var strfin ='*';
    var chatTemplate = '
   i  '+ '
' ;
    var directive = {
        restrict: 'EA',
        template: chatTemplate,
        replace: true,
        scope: {
            messages: "=",
            idSelf: "=",
            idOther: "=",

        },

        link:function ($scope) {

//etc etc

I want to call the function makeitTodo when i click the span element inside my controller..

I have tested like the following.

app.controller('ChatCtrl',  ["$scope",function($scope){
 $scope.makeitTodo = function(a){
  alert(a);
}
}])

But it is not working.. PLease help me.

Body:
Isolated scope function binding is missing

Sample Fiddler: https://jsfiddle.net/paka2/9yda0cLk
`

angular.module('myApp', []).controller('myCtrl', function($scope) {
    $scope.makeitTodo = function(message) {
    console.log(message);
    }
}).directive('clipChat', function() {
    return {
    restrict: "E",
        scope: { done: '&' },
        template: '<input type="text" ng-model="message">'+
        '<button ng-click="done({message:message})"> click me </button>'
    }
});;

`


问:
Compile and link 32-bit program from Visual Studio 2008
I asked this same basic question yesterday, but had not got far enough to get a clear idea of the issue. Basically, this is the error I now get when building my app:

.\Debug\HotSync.obj : fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I assume this means that I'm compiling 64-bit object modules and then trying to link a 32-bit executable. So is this a matter of the compiler itself, or of an option given to the compiler? This project was previously a VC++ 2003 project, so has always been 32-bit.

I might mention that the only versions of cl.exe that I can find are in the amd64 and x86-amd64 subdirectories of VC\bin. I have to manually add one of these paths to the "VC++ Directories" list, but the results are the same for either.

My hosting PC is AMD running Windows 7 64-bit, but I would hope that I can still build programs that will run on XP. Anyone know how to do this?

答: Apparently the "problem" is that I only installed C++ since that's all that I plan on using. But for some reason the cl.exe that I need only gets installed as part of the C# installation. So go figger! Serves me right for trying to save clutter by not doing a full-full install.</p>

ContentLicense: CC BY-SA 2.5


问:
Using multiple AND in nested IF
I want a nested IF, and in seperate IF's I want to be able to use the AND function.

I have 7 different cells I need to check, so I'm getting pretty lost, what I have so far is:

```<code>=IF(G1="yes";"Result 1";(IF(AND(A1>=3;A1<=4),AND(B1>=800;B1<=1200),AND(C1>=1300;C1<=1400),AND(D1>=80;D1<=90),AND(E1>=100;E1<=120),AND(F1>=45;F1<=60);"Result 2"))
</code>```

However this function doesn't work, I'd like to know where I went wrong, and if there's a shorter solution, because this seems like a formula that's way too long.

答:
If I understand well, you want something like this ...

```<code>if
    G = yes
then
    Result 1
else
    if  A between 3 and 4
    and B between 800 and 1200
    and C between 1300 and 1400
    and D between 80 and 90
    and E between 100 and 120
    and F between 45 and 60
    then
        Result 2
    else ???
        ???
    endif
endif
</code>```

You don't need to nest and bracket the various AND's , as

```<code>And(A, And(B, C)) == And(A, B, C)
</code>```

therefore you could write

```<code>=IF(G1="yes";"Result 1";IF(AND(A1>=3;A1<=4;B1>=800;B1<=1200;C1>=1300;C1<=1400;D1>=80;D1<=90;E1>=100;E1<=120;F1>=45;F1<=60);"Result 2"))
</code>```

and you should think of a "Result 3" if any of the "between" parts don't draw ... otherwise you just get a "FALSE" ... this is not a "not working" ... just a "badly thought" ggg

PLUS

you have a wild mixture of ";" and "," as seperators in your formula ... depending on the language it should be only one

I am using German, so all is ";" ... you may need to change all to "," if you use English

Title: Using multiple AND in nested IF

Body:
I want a nested IF, and in seperate IF's I want to be able to use the AND function.

I have 7 different cells I need to check, so I'm getting pretty lost, what I have so far is:

=IF(G1="yes";"Result 1";(IF(AND(A1>=3;A1<=4),AND(B1>=800;B1<=1200),AND(C1>=1300;C1<=1400),AND(D1>=80;D1<=90),AND(E1>=100;E1<=120),AND(F1>=45;F1<=60);"Result 2"))

However this function doesn't work, I'd like to know where I went wrong, and if there's a shorter solution, because this seems like a formula that's way too long.

Body:
If I understand well, you want something like this ...

if
    G = yes
then
    Result 1
else
    if  A between 3 and 4
    and B between 800 and 1200
    and C between 1300 and 1400
    and D between 80 and 90
    and E between 100 and 120
    and F between 45 and 60
    then
        Result 2
    else ???
        ???
    endif
endif

You don't need to nest and bracket the various AND's , as

And(A, And(B, C)) == And(A, B, C)

therefore you could write

=IF(G1="yes";"Result 1";IF(AND(A1>=3;A1<=4;B1>=800;B1<=1200;C1>=1300;C1<=1400;D1>=80;D1<=90;E1>=100;E1<=120;F1>=45;F1<=60);"Result 2"))

and you should think of a "Result 3" if any of the "between" parts don't draw ... otherwise you just get a "FALSE" ... this is not a "not working" ... just a "badly thought" ggg

PLUS

you have a wild mixture of ";" and "," as seperators in your formula ... depending on the language it should be only one

I am using German, so all is ";" ... you may need to change all to "," if you use English


问:
Crashlytics: module-relative stack addresses?
We have a shared library which we do not wish to share the symbol names with anything - including Crashlytics.

As such we really want either:
1. The base address at which each .so has been loaded or
2. Module-relative addresses shown in addition to or instead of absolute addresses in stack traces

Either of those would allow us to produce post-processing tooling (ala addr2line, etc) that turn the crash report into something meaningful without sharing library symbols externally.

Is there some way already to get at this information with Crashlytics? If not, any chance it could be added in the near future? What about the crash reporting via Google Play Console?

答: Crashlytics does not offer a viable solution for this right now. Our symbolication is all or nothing. Thanks!</p>


问:
Deploy hyperledger on AWS - production setup
My company is currently evaluating hyperledger(fabric) and we're using it for our POC. It looks very promising and we're targeting rolling out to production in next few months.

We're targeting AWS as our production environment.

However, we're struggling to find good tutorial/practices/recommendations about operating hyperledger network in such environment.

I'm aware that Cello is aiming to solve/ease deploying/monitoring hyperledger network but i also read that its not production ready yet. Question is, should we even consider looking at Cello at this point?

If not, what are our alternatives? Docker swarm, kubernetes?

I also didn't find information about recommended instance types. I understand this is application and AWS specific but what are the minimal system requirements
(memory&CPU&network) for example for 'peer' node (our application is not network intensive, nor a lot of transactions will be submitted per hour/day, only few of them per day).

Another question is where to create those instances on AWS from geographical&decentralization point of view. Does it make sense all of them to be created in same region? Or, we must create instances running in different regions?

Tnx a lot.
Igor.

答:
yes, look at Cello.. if nothing else it will help you see the aws deployment model.

really nothing special..

design the desired system, peers, orderer, gateways, etc..
then decide who many ec2 instance u need to support that.

as for WHERE (region).. depends on where the connecting application is and what kind of fault tolerance you need for your business model.

one of the businesses I am working with wants a minimum of 99.99999 % availability.   so, multi-region is critical. its just another ec2 instance with sockets open from different hosts..


问:
In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic?
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.

Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.

Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.

Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.

For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?

Meanwhile, I think I have found better solutions, like

setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset

have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue

and I think the lock flag might be the best way to go. But I'm still curious: Is copying a variable atomic?

Follow-up: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?

Kudos to erickson for his very helpful answer on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too.

答:
As I understand it, not always.

Int32 will be, an Int64 won't be on a 32 bit sytem as it needs 2 x 32 bit. Therefore, it does not fit in one 32 bit cell.

OwnerDisplayName: Hanno

LastEditorDisplayName: Hanno

OwnerDisplayName: Carra


问:
find function inside vba code in excel
I got the following xml file that is all in one row of text (multiple rows here to make it more readable):

```<code><bla>
    <blabla>
        <moreblabla>
            <colheader>item1</colheader>
            <colheader>item2</colheader>
            <row>
                <col>apple1</col>
                <col>apple2</col>
            </row>
            <row>
                <col>pear1</col>
                <col>pear2</col>
            </row>
            <row>
                <col>grape1</col>
                <col>grape2</col>
            </row>
        </moreblabla>
    </blabla>
</bla>
</code>```

I wanted to do the following, since I have no idea of the lenght of the blabla before the <colheader> I want to use the excel function find, in order to have the start character of the part that I am interested: the row col part of the xml file.

This is my preliminary script:

```<code>Sub replacexml()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS
Dim strContents As String
Dim fileSpec As String
Dim start As Long
Dim finish As Long
Dim lenght As Long

fileSpec = "C:\path\out.xml"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll

start = InStr(strContents, "<colheader>")
finish = InStr(strContents, "</moreblabla>")
lenght = finsh - start
strContent = Mid(strContents, start, lenght)

objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

End Sub
</code>```

But I got an error, I guess is not recognizing the Find function. How I get the find function to work?

UPDATE: now the mid function is having an issue:

```<code>  strContent = Mid(strContents, start, lenght)
</code>```

答:
If you are trying to find some text in a String, you can use Instr.

https://www.techonthenet.com/excel/formulas/instr.php

Syntax

```<code>InStr( [start], string, substring, [compare] )
</code>```

Hope it helps.

For MID function:

https://www.techonthenet.com/excel/formulas/mid.php
  Syntax

```<code>MID( text, start_position, number_of_characters)
</code>```

You should define the start position and the number of characters, both should be numbers.

Title: find function inside vba code in excel

Body:
I got the following xml file that is all in one row of text (multiple rows here to make it more readable):

<bla>
    <blabla>
        <moreblabla>
            <colheader>item1</colheader>
            <colheader>item2</colheader>
            <row>
                <col>apple1</col>
                <col>apple2</col>
            </row>
            <row>
                <col>pear1</col>
                <col>pear2</col>
            </row>
            <row>
                <col>grape1</col>
                <col>grape2</col>
            </row>
        </moreblabla>
    </blabla>
</bla>

I wanted to do the following, since I have no idea of the lenght of the blabla before the <colheader> I want to use the excel function find, in order to have the start character of the part that I am interested: the row col part of the xml file.

This is my preliminary script:

Sub replacexml()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS
Dim strContents As String
Dim fileSpec As String
Dim start As Long
Dim finish As Long
Dim lenght As Long

fileSpec = "C:\path\out.xml"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll

start = InStr(strContents, "<colheader>")
finish = InStr(strContents, "</moreblabla>")
lenght = finsh - start
strContent = Mid(strContents, start, lenght)

objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

End Sub

But I got an error, I guess is not recognizing the Find function. How I get the find function to work?

UPDATE: now the mid function is having an issue:

  strContent = Mid(strContents, start, lenght)

Body:
If you are trying to find some text in a String, you can use Instr.

https://www.techonthenet.com/excel/formulas/instr.php

Syntax

InStr( [start], string, substring, [compare] )

Hope it helps.

For MID function:

https://www.techonthenet.com/excel/formulas/mid.php
  Syntax

MID( text, start_position, number_of_characters)

You should define the start position and the number of characters, both should be numbers.


问:
How to resolve MongoDB failing to instantiate
I followed the MongoDb Docs to setup my first MongoDb,

When I start MongoDB using the command

```<code>C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe
</code>```

I get the following error

```<code>exception in initAndListen: 29 Data directory C:\data\db\ not found., terminating
shutdown: going to close listening sockets...
shutdown: going to flush diaglog...
now exiting
shutting down with code:100
</code>```

答:
In MacOS:-

If you forgot to give the path of the previously created database while running the mongo server, the above error will appear.

sudo ./mongod --dbpath ../../mongo-data/

Reference

Note :- ./mongod &&  ../../mongo-data is relative path.
So you can avoid it by configuration in environment variable

Reference

ContentLicense: CC BY-SA 4.0

Body:
I followed the MongoDb Docs to setup my first MongoDb,

When I start MongoDB using the command

C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe

I get the following error

exception in initAndListen: 29 Data directory C:\data\db\ not found., terminating
shutdown: going to close listening sockets...
shutdown: going to flush diaglog...
now exiting
shutting down with code:100


问:
Spring configuration XML schema: with or without version?
I am new to Spring. One thing confuses me is that sometimes I see XML configuration files with versioned schemas, yet sometimes with non-versioned ones. For example, sometimes I see something like

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">

     <context:annotation-config/>
     <context:component-scan base-package="base.package"/>

</beans>
```
<p>And sometimes like this:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="base.package"/>

</beans>
</code>```

Note that the spring-beans and spring-context schemas are different in these two examples.

So, my question is, which style would you use and why? In particular, will the versioned schema become unavailable in the future, and will the non-versioned schema keep compatible with a current application when Spring updates the schema?

A side question is, where can I find a list of the versioned spring schemas?

答:
I have enroled for spring course on udemy. I followed every step that my instructor show me to do.
So if you are using spring mvc and hibernate you may encounter this error
Failed to read schema document 'http://www.springframework.org/schema/tx/spring-tx.xsd' etc for:

```<code><mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" /> elements
</code>```

in my spring configuration file i had these two urls

```<code>    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
</code>```

in xsi:schemaLocation, which i replaced with

```<code>    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
</code>```

actually i visited these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd

So, in my opinion specifying version no explicitly is a good practice.
Hope this helps.
Thank you.

Body:
I am new to Spring. One thing confuses me is that sometimes I see XML configuration files with versioned schemas, yet sometimes with non-versioned ones. For example, sometimes I see something like

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">

     <context:annotation-config/>
     <context:component-scan base-package="base.package"/>

</beans>

And sometimes like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="base.package"/>

</beans>

Note that the spring-beans and spring-context schemas are different in these two examples.

So, my question is, which style would you use and why? In particular, will the versioned schema become unavailable in the future, and will the non-versioned schema keep compatible with a current application when Spring updates the schema?

A side question is, where can I find a list of the versioned spring schemas?

Body:
I have enroled for spring course on udemy. I followed every step that my instructor show me to do.
So if you are using spring mvc and hibernate you may encounter this error
Failed to read schema document 'http://www.springframework.org/schema/tx/spring-tx.xsd' etc for:

<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" /> elements

in my spring configuration file i had these two urls

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd

in xsi:schemaLocation, which i replaced with

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

actually i visited these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd

So, in my opinion specifying version no explicitly is a good practice.
Hope this helps.
Thank you.


问:
Generate report that shows how each condition in a SQL CLAUSE effects the total rows outputted by the query?
For example, I'm trying to view how each condition in the below SQL will affect the total rows outputted.

```<code>SELECT * FROM   {Tables..}  WHERE date > '2017'
   AND ( location = 'US'
          OR location = 'CA'
          OR location = 'MX' )
   AND customer_order > 1
   AND latest_cust_order_tot >= 1000
</code>```

The ideal output would be  or the below output:

```<code>    Criteria Desc.                 SQL Code                                           Rows Removed    Records Remaining
    Total Purchases YTD            DATE > '2017'                                                     0             100020
    Customers from the North AmericLOCATION = 'US' OR LOCATION = 'CA' or LOCATION = 'M           44500              55520
    Repeat Customers               CUSTOMER_ORDER > 1                                            20300              35220
    Most recent order over $500    LATEST_CUST_ORDER_TOT >= 1000                                 33810               1410
</code>```

Trying to solve it with BI tools or just SQL. I'm not looking to hardcode a query to produce the results as the conditions can range to more then 50 and will change based on user input.

答:
Does this do what you want?

```<code>SELECT COUNT(*),
       SUM(CASE WHEN date > '2017' THEN 1 ELSE 0 END) as condition_1,
       SUM(CASE WHEN date > '2017' AND location IN ('US', 'CA', 'MX') THEN 1 ELSE 0 END) as condition_2,
       SUM(CASE WHEN date > '2017' AND location IN ('US', 'CA', 'MX') AND customer_order > 1 THEN 1 ELSE 0 END) as condition_3,
       SUM(CASE WHEN date > '2017' AND location IN ('US', 'CA', 'MX') AND customer_order > 1 AND latest_cust_order_tot >= 1000 THEN 1 ELSE 0 END) as condition_3,
FROM   {Tables..}  ;
</code>```

This puts the counts in separate columns.

Body:
For example, I'm trying to view how each condition in the below SQL will affect the total rows outputted.

SELECT * FROM   {Tables..}  WHERE date > '2017'
   AND ( location = 'US'
          OR location = 'CA'
          OR location = 'MX' )
   AND customer_order > 1
   AND latest_cust_order_tot >= 1000

The ideal output would be  or the below output:

    Criteria Desc.                 SQL Code                                           Rows Removed    Records Remaining
    Total Purchases YTD            DATE > '2017'                                                     0             100020
    Customers from the North AmericLOCATION = 'US' OR LOCATION = 'CA' or LOCATION = 'M           44500              55520
    Repeat Customers               CUSTOMER_ORDER > 1                                            20300              35220
    Most recent order over $500    LATEST_CUST_ORDER_TOT >= 1000                                 33810               1410

Trying to solve it with BI tools or just SQL. I'm not looking to hardcode a query to produce the results as the conditions can range to more then 50 and will change based on user input.

Body:
Does this do what you want?

SELECT COUNT(*),
       SUM(CASE WHEN date > '2017' THEN 1 ELSE 0 END) as condition_1,
       SUM(CASE WHEN date > '2017' AND location IN ('US', 'CA', 'MX') THEN 1 ELSE 0 END) as condition_2,
       SUM(CASE WHEN date > '2017' AND location IN ('US', 'CA', 'MX') AND customer_order > 1 THEN 1 ELSE 0 END) as condition_3,
       SUM(CASE WHEN date > '2017' AND location IN ('US', 'CA', 'MX') AND customer_order > 1 AND latest_cust_order_tot >= 1000 THEN 1 ELSE 0 END) as condition_3,
FROM   {Tables..}  ;

This puts the counts in separate columns.


问:
VS2010 reference dll is missing from the list
I'm trying to add System.Web.Extensions.dll to my C# console application so I can parse JSON.
I'm using VS2010.

When I right click -> Add reference though it does not list the dll.
However when I search for the file on my computer it does exist.

Please advise on the proper way to add this dll.

答:
Right click on your project and go to properties.

In the Target framework drop down ensure that you have ".NET Framework 4" selected and not ".NET Framework 4 Client Profile".

When you have Client Profile selected it will filter out the server side dlls like System.Web and System.Web.Extensions


问:
Get value from XML file by its name using PHP
How I can get a name and value stored in <set name = "height"> tag using the name of value I mean "height" in this case? Its ofcourse XML file and I'm using PHP.

```<code><list>
<npc id="25001" name="Greyclaw Kutus" title="Raid Boss">
<set name="level" val="23"/>
<set name="radius" val="21"/>
<set name="height" val="43.5"/>
<set name="rHand" val="67"/>
<set name="lHand" val="633"/>
<set name="sp" val="67170"/>
<set name="hp" val="40330.25972324"/>
<set name="mp" val="231.96"/>
<set name="hpRegen" val="17.5347470979605"/>
</npc>
</list>
</code>```

I've made something like this I have no idea how to itarete whole file by this:

```<code><?php
$list = simplexml_load_file('25000-25999.xml');

if($list === false){
echo "File open error";
}
else {

foreach($list ->npc as $npc) {
 $att = "height";

 $val = $list->npc->xpath('set[@name="' . $att . '"]');

 foreach ($val as $value) {
     echo $value['val'];
 }
 }
</code>```

答:
When you are accessing the 'height' element, you are accessing using $list->npc as the basis of your XPath expression.  This will give you the first element each time ( and always echo 43.5).  You need to change this to use $npc, so that each time the XPath is relative to the current element of npc...

```<code>   $val = $npc->xpath('set[@name="' . $att . '"]');
</code>```

Body:
How I can get a name and value stored in <set name = "height"> tag using the name of value I mean "height" in this case? Its ofcourse XML file and I'm using PHP.

<list>
<npc id="25001" name="Greyclaw Kutus" title="Raid Boss">
<set name="level" val="23"/>
<set name="radius" val="21"/>
<set name="height" val="43.5"/>
<set name="rHand" val="67"/>
<set name="lHand" val="633"/>
<set name="sp" val="67170"/>
<set name="hp" val="40330.25972324"/>
<set name="mp" val="231.96"/>
<set name="hpRegen" val="17.5347470979605"/>
</npc>
</list>

I've made something like this I have no idea how to itarete whole file by this:

<?php
$list = simplexml_load_file('25000-25999.xml');

if($list === false){
echo "File open error";
}
else {

foreach($list ->npc as $npc) {
 $att = "height";

 $val = $list->npc->xpath('set[@name="' . $att . '"]');

 foreach ($val as $value) {
     echo $value['val'];
 }
 }

Body:
When you are accessing the 'height' element, you are accessing using $list->npc as the basis of your XPath expression.  This will give you the first element each time ( and always echo 43.5).  You need to change this to use $npc, so that each time the XPath is relative to the current element of npc...

   $val = $npc->xpath('set[@name="' . $att . '"]');


问:
Why can't a class member's name be the same as one of its nested classes?
Or why is the following impossible:

```<code>class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}
</code>```

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

答:
You said,

When accessed by instance, return the property. When access statically, return the class.

But what if you say just Keys somewhere inside Material? Is this a static or instance access? Does this refer to the property Keys or the nested type Keys? It is actually ambiguous.

For example,

```<code>class Material
{
    class Keys
    {
        public static int Length;
    }

    string Keys { get; set; }

    public void Process()
    {
        // Does this refer to string.Length (via property Keys)
        // or Material.Keys.Length? It actually refers to both.
        Console.WriteLine(Keys.Length);
    }
}
</code>```

As pointed out in the comments, this is not the whole story; but almost. It is valid to have a property named Color of the type Color and there is no clash:

```<code>public Color Color { get; set; }

Color.FromName(...)   // refers to static method on the type ‘Color’
Color.ToString()      // refers to instance method on the property’s value
</code>```

But this is easy to resolve simply because things in the current scope win over things in more outer scopes:

```<code>public class MyType { public string FromName(string name) { return null; } }
public MyType Color;

Color.FromName(...)   // unambiguously refers to MyType::FromName(string)
                      // via the property Color
</code>```

Not so easy in your example — the nested class Keys and the property Keys are in the same scope (have the same declaring type). How do you decide which to give priority? And even if you did decide to give one of them priority, this would be only marginally useful because you could still only have two things of the same name, and one would have to be static and the other instance.

Body:
Or why is the following impossible:

class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

Body:
You said,

When accessed by instance, return the property. When access statically, return the class.

But what if you say just Keys somewhere inside Material? Is this a static or instance access? Does this refer to the property Keys or the nested type Keys? It is actually ambiguous.

For example,

class Material
{
    class Keys
    {
        public static int Length;
    }

    string Keys { get; set; }

    public void Process()
    {
        // Does this refer to string.Length (via property Keys)
        // or Material.Keys.Length? It actually refers to both.
        Console.WriteLine(Keys.Length);
    }
}

As pointed out in the comments, this is not the whole story; but almost. It is valid to have a property named Color of the type Color and there is no clash:

public Color Color { get; set; }

Color.FromName(...)   // refers to static method on the type ‘Color’
Color.ToString()      // refers to instance method on the property’s value

But this is easy to resolve simply because things in the current scope win over things in more outer scopes:

public class MyType { public string FromName(string name) { return null; } }
public MyType Color;

Color.FromName(...)   // unambiguously refers to MyType::FromName(string)
                      // via the property Color

Not so easy in your example — the nested class Keys and the property Keys are in the same scope (have the same declaring type). How do you decide which to give priority? And even if you did decide to give one of them priority, this would be only marginally useful because you could still only have two things of the same name, and one would have to be static and the other instance.


问:
TSQL Datetime conversion looses a period of time
i'm playing around with a MsSQL Server for some days now and stumbled upon a strange behaviour when converting a datetime to/from a decimal.

```<code>SELECT [date] = GETDATE()

, [as decimal] = CAST(GETDATE() AS decimal)
, [from decimal] = CAST(CAST(GETDATE() AS decimal) AS datetime)

, [as float] = CAST(GETDATE() AS float)
, [from float] = CAST(CAST(GETDATE() AS float) AS datetime)

--                                  should be: 2009-08-15
, [from stored float] = CAST(CAST('40039.9583333333' AS float) AS datetime)
</code>```

When i convert a datetime without adding anything specific the decimal will be handled as i would define it decimal(18, 0). So there is a data loss in some way.

If i directly convert a float back to datetime which was converted from a datetime (as shown in line 7 of my query) everything is fine.

But when i load a value from a database table, for example 40039.9583333333 which definitely was calculated from a user input (2009-08-15) and convert it back to a datetime, it'll add one day.

I wasn't able to find anything specific for this time loss.

Is somebody able to describe the problem behind this strange behaviour?
And, if possible: add an example on how to do those conversions correctly?

Thanks.

答:
I used the values you specified '2009-08-15' and converted it to both decimal and float, which resulted in a value of 40038 for both. I used this value to convert back to datetime and both the decimal and float returns '2009-08-15 00:00:00.000'.

The value 40039.9583333333 results in, as Renan just posted :), '2009-08-16 22:59:59.997'.

I would question whether it was 'definitely was calculated from a user input (2009-08-15)' because that does not appear to be the case. There is more to it than shared.

```<code>-- Microsoft SQL Server 2014 - 12.0.4100.1 (X64)

DECLARE @dt datetime = '2009-08-15'

SELECT CAST(@dt AS decimal) -- 40038
SELECT CAST(@dt AS float) -- 40038

DECLARE @dec1 decimal = 40038;
SELECT CAST(@dec1 AS datetime) -- 2009-08-15 00:00:00.000
DECLARE @flo1 float = 40038;
SELECT CAST(@flo1 AS datetime) -- 2009-08-15 00:00:00.000

DECLARE @dec2 decimal = 40039.9583333333;
SELECT CAST(@dec2 AS datetime) -- 2009-08-17 00:00:00.000
DECLARE @flo2 float = 40039.9583333333;
SELECT CAST(@flo2 AS datetime) -- 2009-08-16 22:59:59.997
</code>```

Body:
i'm playing around with a MsSQL Server for some days now and stumbled upon a strange behaviour when converting a datetime to/from a decimal.

SELECT [date] = GETDATE()

, [as decimal] = CAST(GETDATE() AS decimal)
, [from decimal] = CAST(CAST(GETDATE() AS decimal) AS datetime)

, [as float] = CAST(GETDATE() AS float)
, [from float] = CAST(CAST(GETDATE() AS float) AS datetime)

--                                  should be: 2009-08-15
, [from stored float] = CAST(CAST('40039.9583333333' AS float) AS datetime)

When i convert a datetime without adding anything specific the decimal will be handled as i would define it decimal(18, 0). So there is a data loss in some way.

If i directly convert a float back to datetime which was converted from a datetime (as shown in line 7 of my query) everything is fine.

But when i load a value from a database table, for example 40039.9583333333 which definitely was calculated from a user input (2009-08-15) and convert it back to a datetime, it'll add one day.

I wasn't able to find anything specific for this time loss.

Is somebody able to describe the problem behind this strange behaviour?
And, if possible: add an example on how to do those conversions correctly?

Thanks.

Body:
I used the values you specified '2009-08-15' and converted it to both decimal and float, which resulted in a value of 40038 for both. I used this value to convert back to datetime and both the decimal and float returns '2009-08-15 00:00:00.000'.

The value 40039.9583333333 results in, as Renan just posted :), '2009-08-16 22:59:59.997'.

I would question whether it was 'definitely was calculated from a user input (2009-08-15)' because that does not appear to be the case. There is more to it than shared.

-- Microsoft SQL Server 2014 - 12.0.4100.1 (X64)

DECLARE @dt datetime = '2009-08-15'

SELECT CAST(@dt AS decimal) -- 40038
SELECT CAST(@dt AS float) -- 40038

DECLARE @dec1 decimal = 40038;
SELECT CAST(@dec1 AS datetime) -- 2009-08-15 00:00:00.000
DECLARE @flo1 float = 40038;
SELECT CAST(@flo1 AS datetime) -- 2009-08-15 00:00:00.000

DECLARE @dec2 decimal = 40039.9583333333;
SELECT CAST(@dec2 AS datetime) -- 2009-08-17 00:00:00.000
DECLARE @flo2 float = 40039.9583333333;
SELECT CAST(@flo2 AS datetime) -- 2009-08-16 22:59:59.997


问:
.net core 2.0 external login - extra profile information
I have a .net core 2.0 app and am implementing external login providers like google, twitter, and facebook. I have the requirement to get the user's display name and profile picture, and can't find any documentaion of how to achieve this in .net core 2.0.

I add the authentication like this post: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/

Here are my twitter login and callback functions...

```<code>    [HttpGet]
    [Route("/api/security/login/type/socialmedia/twitter")]
    public IActionResult GetTwitterLogin(string redirect_uri)
    {
        ClientCallback = redirect_uri;
        string redirectUrl = "/api/security/login/type/socialmedia/twittercallback";
        var properties = SignInManager.ConfigureExternalAuthenticationProperties("Twitter", redirectUrl);
        return Challenge(properties, "Twitter");
    }

    [HttpGet]
    [Route("/api/security/login/type/socialmedia/twittercallback")]
    public async Task<HttpResponseMessage> GetTwitterCallBackAsync()
    {
        var info = await SignInManager.GetExternalLoginInfoAsync();

        var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
        if (result.Succeeded)
        {

        }
        else
        {

        }

        Response.StatusCode = (int)HttpStatusCode.OK;
        return null;
    }
</code>```

It looks like you can get some items from info.Principal.Claims, but nothing for the user's display name or profile picture.

How do you get the display name or profile picture for the various login providers?

答:
I finally figured this out...you need to add claims when you configure the authentication.  These claims look at the resulting json response and pulls items from it.  The pertinent lines are the ClaimActions items.

```<code> services.AddAuthentication()
               .AddTwitter(twitterOptions =>
               {
                   twitterOptions.ConsumerKey = cfg.SystemConfig["TwitterConsumerKey"];
                   twitterOptions.ConsumerSecret = cfg.SystemConfig["TwitterConsumerSecret"];
                   twitterOptions.SaveTokens = true;
                   twitterOptions.RetrieveUserDetails = true;
                   twitterOptions.ClaimActions.MapJsonKey("display-name", "name");
                   twitterOptions.ClaimActions.MapJsonKey("profile-image-url", "profile_image_url_https");
               })
               .AddFacebook(facebookOptions =>
               {
                   facebookOptions.AppId = cfg.SystemConfig["FacebookClientId"];
                   facebookOptions.AppSecret = cfg.SystemConfig["FacebookClientSecret"];
                   facebookOptions.SaveTokens = true;
                   facebookOptions.ClaimActions.MapJsonKey("display-name", "name");

               })
               .AddGoogle(googleOptions =>
               {
                   googleOptions.ClientId = cfg.SystemConfig["GoogleClientId"];
                   googleOptions.ClientSecret = cfg.SystemConfig["GoogleClientSecret"];
                   googleOptions.SaveTokens = true;
                   googleOptions.ClaimActions.MapJsonSubKey("profile-image-url", "image", "url");
                   googleOptions.ClaimActions.MapJsonKey("display-name", "displayName" );
               });
</code>```

After getting the login information in your callback using

```<code>var info = await SignInManager.GetExternalLoginInfoAsync();
</code>```

If populated successfully you can query the claims and find the values

```<code> var profileImageClaim = info.Principal.Claims.Where(x => x.Type == "profile-image-url").FirstOrDefault();
</code>```

Facebook images are different from google and twitter and can be found using...

```<code>var claim = info.Principal.Claims.Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").FirstOrDefault();
var url = "http://graph.facebook.com/" + claim.Value + "/picture";
</code>```

Body:
I have a .net core 2.0 app and am implementing external login providers like google, twitter, and facebook. I have the requirement to get the user's display name and profile picture, and can't find any documentaion of how to achieve this in .net core 2.0.

I add the authentication like this post: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/

Here are my twitter login and callback functions...

    [HttpGet]
    [Route("/api/security/login/type/socialmedia/twitter")]
    public IActionResult GetTwitterLogin(string redirect_uri)
    {
        ClientCallback = redirect_uri;
        string redirectUrl = "/api/security/login/type/socialmedia/twittercallback";
        var properties = SignInManager.ConfigureExternalAuthenticationProperties("Twitter", redirectUrl);
        return Challenge(properties, "Twitter");
    }

    [HttpGet]
    [Route("/api/security/login/type/socialmedia/twittercallback")]
    public async Task<HttpResponseMessage> GetTwitterCallBackAsync()
    {
        var info = await SignInManager.GetExternalLoginInfoAsync();

        var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
        if (result.Succeeded)
        {

        }
        else
        {

        }

        Response.StatusCode = (int)HttpStatusCode.OK;
        return null;
    }

It looks like you can get some items from info.Principal.Claims, but nothing for the user's display name or profile picture.

How do you get the display name or profile picture for the various login providers?

Body:
I finally figured this out...you need to add claims when you configure the authentication.  These claims look at the resulting json response and pulls items from it.  The pertinent lines are the ClaimActions items.

 services.AddAuthentication()
               .AddTwitter(twitterOptions =>
               {
                   twitterOptions.ConsumerKey = cfg.SystemConfig["TwitterConsumerKey"];
                   twitterOptions.ConsumerSecret = cfg.SystemConfig["TwitterConsumerSecret"];
                   twitterOptions.SaveTokens = true;
                   twitterOptions.RetrieveUserDetails = true;
                   twitterOptions.ClaimActions.MapJsonKey("display-name", "name");
                   twitterOptions.ClaimActions.MapJsonKey("profile-image-url", "profile_image_url_https");
               })
               .AddFacebook(facebookOptions =>
               {
                   facebookOptions.AppId = cfg.SystemConfig["FacebookClientId"];
                   facebookOptions.AppSecret = cfg.SystemConfig["FacebookClientSecret"];
                   facebookOptions.SaveTokens = true;
                   facebookOptions.ClaimActions.MapJsonKey("display-name", "name");

               })
               .AddGoogle(googleOptions =>
               {
                   googleOptions.ClientId = cfg.SystemConfig["GoogleClientId"];
                   googleOptions.ClientSecret = cfg.SystemConfig["GoogleClientSecret"];
                   googleOptions.SaveTokens = true;
                   googleOptions.ClaimActions.MapJsonSubKey("profile-image-url", "image", "url");
                   googleOptions.ClaimActions.MapJsonKey("display-name", "displayName" );
               });

After getting the login information in your callback using

var info = await SignInManager.GetExternalLoginInfoAsync();

If populated successfully you can query the claims and find the values

 var profileImageClaim = info.Principal.Claims.Where(x => x.Type == "profile-image-url").FirstOrDefault();

Facebook images are different from google and twitter and can be found using...

var claim = info.Principal.Claims.Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").FirstOrDefault();
var url = "http://graph.facebook.com/" + claim.Value + "/picture";


问:
Regex two digit pairing
I have the following regex I use to find numeric pairs; [0-9][0-9]

If the string is even length, I get exactly what I want.

```<code>string x ="1234";
Regex.Matches(enc, @"[0-9][0-9]")
</code>```

With the regex I get 12,34.

if I have string x="12345" I get 12,34.  How do I modify this if I want 23,45?

答:
Brief

This answer uses the input you entered in a comment below your question (see Results section for the inputs)

Code

Since I'm not certain exactly what the outputs should be, I'll present you with the following 3 methods.

Method 1

This method always ensures the pairs are matched from the end of the string.

See regex in use here

```<code>\d{2}(?=(?:(?:\d{2})+|)(?:\D|$))
</code>```

Method 2

This method always ensures the pairs are matched from the end of the string only when a specific token follows the numbers

See regex in use here

```<code>\d{2}(?=(?:\d{2})+\[|\[)
</code>```

Method 3

This method always ensures the pairs are matched from the end of the string only when a specific token follows the numbers and matches the remaining numbers normally (but also in pairs)

See regex in use here

```<code>\d{2}(?=(?:\d{2})+\[|\[)|\d{2}(?=\d*$)
</code>```

Results

Input

```<code>12345[FNC1]00112233
12345[FNC1]0011223
</code>```

Output

Method 1

```<code>23 45 00 11 22 33
23 45 01 12 23
</code>```

Method 2

```<code>23 45
23 45
</code>```

Method 3

```<code>23 45 00 11 22 33
23 45 00 11 22
</code>```

Explanation

Method 1

\d{2} Match any digit exactly twice

(?=(?:\d{2})+\b|\b) Positive lookahead ensuring either of the following matches

(?:\d{2})+\b Match the following

(?:\d{2})+ Match the following one or more times

\d{2} Match any digit exactly twice

\b Assert the position as a word boundary

\b Assert the position as a word boundary

Method 2

Same as Method 1's explanation, but instead of using \b, it uses \[ to assert that the following character matches [ literally.

Method 3

Same as Method 2's explanation, but adds |\d{2}(?=\d*$) to the end.

| acts like a boolean OR (match Method 2 or the following)

\d{2} Match any digit exactly twice

(?=\d*$) Positive lookahead ensuring what follows matches

\d* Match any digit any number of times

$ Assert position at the end of the line

Title: Regex two digit pairing

Body:
I have the following regex I use to find numeric pairs; [0-9][0-9]

If the string is even length, I get exactly what I want.

string x ="1234";
Regex.Matches(enc, @"[0-9][0-9]")

With the regex I get 12,34.

if I have string x="12345" I get 12,34.  How do I modify this if I want 23,45?

Body:
Brief

This answer uses the input you entered in a comment below your question (see Results section for the inputs)

Code

Since I'm not certain exactly what the outputs should be, I'll present you with the following 3 methods.

Method 1

This method always ensures the pairs are matched from the end of the string.

See regex in use here

\d{2}(?=(?:(?:\d{2})+|)(?:\D|$))

Method 2

This method always ensures the pairs are matched from the end of the string only when a specific token follows the numbers

See regex in use here

\d{2}(?=(?:\d{2})+\[|\[)

Method 3

This method always ensures the pairs are matched from the end of the string only when a specific token follows the numbers and matches the remaining numbers normally (but also in pairs)

See regex in use here

\d{2}(?=(?:\d{2})+\[|\[)|\d{2}(?=\d*$)

Results

Input

12345[FNC1]00112233
12345[FNC1]0011223

Output

Method 1

23 45 00 11 22 33
23 45 01 12 23

Method 2

23 45
23 45

Method 3

23 45 00 11 22 33
23 45 00 11 22

Explanation

Method 1

\d{2} Match any digit exactly twice

(?=(?:\d{2})+\b|\b) Positive lookahead ensuring either of the following matches

(?:\d{2})+\b Match the following

(?:\d{2})+ Match the following one or more times

\d{2} Match any digit exactly twice

\b Assert the position as a word boundary

\b Assert the position as a word boundary

Method 2

Same as Method 1's explanation, but instead of using \b, it uses \[ to assert that the following character matches [ literally.

Method 3

Same as Method 2's explanation, but adds |\d{2}(?=\d*$) to the end.

| acts like a boolean OR (match Method 2 or the following)

\d{2} Match any digit exactly twice

(?=\d*$) Positive lookahead ensuring what follows matches

\d* Match any digit any number of times

$ Assert position at the end of the line


问:
Rubocop error on Rspec/DescribeClass
I've recently updated to the most recent version of Rubocop (0.51) due to a bug in the previos version, but now it marks the following as error:

```<code>spec/controllers/loans_controller_spec.rb:3:10: C: RSpec/DescribeClass: The first argument to describe should be the class or module being tested.
describe LoansController do
         ^^^^^^^^^^^^^^^
</code>```

This is the way I've been doing it since forever, and is in fact the class I want to test.

The same is happening with all files in my spec folder. They all have the correspondent class name.

答:
you have to specify that the class you are testing is a controller, after the reference to the class you must specify what kind of class it is. In your case it would be :type => :controller

Example:

```<code>RSpec.describe LoansController, :type => :controller do
end
</code>```

for more information you can visit the following link Rspec Controllers

Title: Rubocop error on Rspec/DescribeClass

Body:
I've recently updated to the most recent version of Rubocop (0.51) due to a bug in the previos version, but now it marks the following as error:

spec/controllers/loans_controller_spec.rb:3:10: C: RSpec/DescribeClass: The first argument to describe should be the class or module being tested.
describe LoansController do
         ^^^^^^^^^^^^^^^

This is the way I've been doing it since forever, and is in fact the class I want to test.

The same is happening with all files in my spec folder. They all have the correspondent class name.

Body:
you have to specify that the class you are testing is a controller, after the reference to the class you must specify what kind of class it is. In your case it would be :type => :controller

Example:

RSpec.describe LoansController, :type => :controller do
end

for more information you can visit the following link Rspec Controllers


问:
Give CSS property to parent td using CSS
I have referred to many options but still I am not able to apply CSS to my parent container. My table structure is like:

```<code><td>
  <div id="div1">
      <div id="div2" class="colorMe"></div>
  </div>
</td>
</code>```

Now according to above structure if div2 has class colorMe then I want to color the entire td background in yellow.

I have used CSS like this but not working:

```<code>td > div> div.colorMe {
background-color:yellow;
}
</code>```

Can you please tell me how I can color my td using css?

答:
I know that you mentioned only using css but adding some javascript event to change a class is a very well documented approach. There are dozens of examples online and including the the script in your file takes no extra work if you use vanilla.

Here is a small example of changing a parent div's color on a click event

var box2 = document.querySelector('.color2');
box2.addEventListener("click", function() {
  this.parentNode.style.backgroundColor = "white";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 100px;
  height: 100px;
  border: 2px solid black;
}

.color1 {
  background-color: red;
}

.color2 {
  background-color: rebeccapurple;
  width: 50px;
  height: 20px;
}</code>```

```

Body:
I have referred to many options but still I am not able to apply CSS to my parent container. My table structure is like:

Now according to above structure if div2 has class colorMe then I want to color the entire td background in yellow.

I have used CSS like this but not working:

td > div> div.colorMe {
background-color:yellow;
}

Can you please tell me how I can color my td using css?

Body:
I know that you mentioned only using css but adding some javascript event to change a class is a very well documented approach. There are dozens of examples online and including the the script in your file takes no extra work if you use vanilla.

Here is a small example of changing a parent div's color on a click event

var box2 = document.querySelector('.color2');
box2.addEventListener("click", function() {
  this.parentNode.style.backgroundColor = "white";
});

div {
  width: 100px;
  height: 100px;
  border: 2px solid black;
}

.color1 {
  background-color: red;
}

.color2 {
  background-color: rebeccapurple;
  width: 50px;
  height: 20px;
}

<div class="color1">
  <div class="color2"></div>
</div>


问:
Python import MySQLdb error - Mac 10.6
I downloaded and followed the install instructions for MySQL 5.5.8 (http://dev.mysql.com/downloads/mysql/) and for the MySQLdb python plugin. (http://sourceforge.net/projects/mysql-python/)

When I attempt to import MySQLdb to a python terminal, I get the below error:

```<code>Safira:~ yanigisawa$ python --version
Python 2.6.1
Safira:~ yanigisawa$ python -c "import MySQLdb"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
  File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
  File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.16.dylib
  Referenced from: /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
  Reason: image not found
Safira:~ yanigisawa$
</code>```

I found question 4559699 on stack overflow, and followed the instructions there:

```<code>Safira:~ yanigisawa$ echo $DYLD_LIBRARY_PATH
/usr/local/mysql/lib
Safira:~ yanigisawa$ ls -l /usr/local/mysql/lib
total 363224
-rwxr-xr-x   1 root  wheel   3787328 Jan 18 19:41 libmysqlclient.16.dylib
-rw-r--r--   1 root  wheel  10035336 Dec  3 13:26 libmysqlclient.a
lrwxr-xr-x   1 root  wheel        23 Jan 14 22:01 libmysqlclient.dylib -> libmysqlclient.16.dylib
lrwxr-xr-x   1 root  wheel        20 Jan 14 22:01 libmysqlclient_r.16.dylib -> libmysqlclient.dylib
lrwxr-xr-x   1 root  wheel        16 Jan 14 22:01 libmysqlclient_r.a -> libmysqlclient.a
lrwxr-xr-x   1 root  wheel        20 Jan 14 22:01 libmysqlclient_r.dylib -> libmysqlclient.dylib
-rw-r--r--   1 root  wheel  88033760 Dec  3 13:22 libmysqld-debug.a
-rw-r--r--   1 root  wheel  84075304 Dec  3 13:26 libmysqld.a
-rw-r--r--   1 root  wheel      8472 Dec  3 13:26 libmysqlservices.a
drwxr-xr-x  13 root  wheel       442 Dec  3 13:53 plugin
Safira:~ yanigisawa$ md5 /usr/local/mysql/lib/libmysqlclient.16.dylib
MD5 (/usr/local/mysql/lib/libmysqlclient.16.dylib) = b8a78a93183720021b9dbe9ddad57111
Safira:~ yanigisawa$
</code>```

And after cleaning all of the python egg files, and rebuilding, I still got the same error. Then I found bug 59006 (http://bugs.mysql.com/bug.php?id=59006) in MySQL 5.5.8 affecting Mac 10.6. I tried the work-around listed there, cleaned eggs and rebuilt, and I'm still getting this error.

Is there another work-around for this problem specific to python? Am I missing something else?

EDIT: Adding output from otool commands:

```<code>Safira:~ yanigisawa$ otool -L /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
/Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so:
    libmysqlclient.16.dylib (compatibility version 16.0.0, current version 16.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)
Safira:~ yanigisawa$ otool -DX /usr/local/mysql/lib/libmysqlclient.16.dylib
/usr/local/mysql/lib/libmysqlclient.16.dylib
Safira:~ yanigisawa$
</code>```

答:
You could try running otool to find out exactly what library paths the MySQLdb C extension, _mysql.so is looking for:

```<code>$ otool -L /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
</code>```

and then the installed library name of the MySQL library file:

```<code>$ otool -DX /usr/local/mysql/lib/libmysqlclient.16.dylib
</code>```

But you should not have to resort to setting DYLD_LIBRARY_PATH (or using install_name_tool to modify an executable); the need to set it is almost always a sign of a component that was built or installed incorrectly. In my experience, the MySQL project does not have a very good track record for consistency in their OS X builds and installers, as that issue you cite tends to confirm.

Trying to get a working combination of Python, MySQLdb, and MySQL libraries in OS X 10.6 is a very common cause of frustration: lots of questions about it here on SO and elsewhere.  There are a number reasons for that.  My advice is to go with a complete solution from one of the third-party distributors that will build and install compatible versions of everything you need.  And it should keep working if you need to upgrade components as time goes on.  I've had good success over the years with MacPorts; others prefer Fink or the newer HomeBrew.  With MacPorts, after installing the base files from the MacPorts .dmg, you can get everything built like so:

```<code>$ sudo port selfupdate  # ensure the port files are up-to-date
$ sudo port install py26-mysql
</code>```

The MacPorts Python will be available at /opt/local/bin/python2.6.  If you are looking to run Django, there's a port for that as well.

EDIT: With the updated output from otool, you can see that there is a mismatch of library path names.  The MySQLdb extension is asking for a relative path name (no initial /), while the MySQL library advertises itself with an absolute path, normally what you want.  It seems to be the reverse of the MySQL issue 59006 but, without knowing exactly what steps you've performed up until now, it is really hard to say how you got to this state.  You may be able to use install_name_tool to patch the _mysql.so to have the absolute path name which would also eliminate any need to set DYLD_LIBRARY_PATH.  It's worth trying:

```<code>$ cd ~/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp
$ sudo install_name_tool -change libmysqlclient.16.dylib \
                                 /usr/local/mysql/lib/libmysqlclient.16.dylib \
                         _mysql.so
</code>```

But that should not leave you with a warm and fuzzy feeling that you can reproduce the results when you need to update something.  There really is no virtue in trying to glue all these pieces from different sources into something that works.

Title: Python import MySQLdb error - Mac 10.6

Body:
I downloaded and followed the install instructions for MySQL 5.5.8 (http://dev.mysql.com/downloads/mysql/) and for the MySQLdb python plugin. (http://sourceforge.net/projects/mysql-python/)

When I attempt to import MySQLdb to a python terminal, I get the below error:

Safira:~ yanigisawa$ python --version
Python 2.6.1
Safira:~ yanigisawa$ python -c "import MySQLdb"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
  File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
  File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.16.dylib
  Referenced from: /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
  Reason: image not found
Safira:~ yanigisawa$

I found question 4559699 on stack overflow, and followed the instructions there:

Safira:~ yanigisawa$ echo $DYLD_LIBRARY_PATH
/usr/local/mysql/lib
Safira:~ yanigisawa$ ls -l /usr/local/mysql/lib
total 363224
-rwxr-xr-x   1 root  wheel   3787328 Jan 18 19:41 libmysqlclient.16.dylib
-rw-r--r--   1 root  wheel  10035336 Dec  3 13:26 libmysqlclient.a
lrwxr-xr-x   1 root  wheel        23 Jan 14 22:01 libmysqlclient.dylib -> libmysqlclient.16.dylib
lrwxr-xr-x   1 root  wheel        20 Jan 14 22:01 libmysqlclient_r.16.dylib -> libmysqlclient.dylib
lrwxr-xr-x   1 root  wheel        16 Jan 14 22:01 libmysqlclient_r.a -> libmysqlclient.a
lrwxr-xr-x   1 root  wheel        20 Jan 14 22:01 libmysqlclient_r.dylib -> libmysqlclient.dylib
-rw-r--r--   1 root  wheel  88033760 Dec  3 13:22 libmysqld-debug.a
-rw-r--r--   1 root  wheel  84075304 Dec  3 13:26 libmysqld.a
-rw-r--r--   1 root  wheel      8472 Dec  3 13:26 libmysqlservices.a
drwxr-xr-x  13 root  wheel       442 Dec  3 13:53 plugin
Safira:~ yanigisawa$ md5 /usr/local/mysql/lib/libmysqlclient.16.dylib
MD5 (/usr/local/mysql/lib/libmysqlclient.16.dylib) = b8a78a93183720021b9dbe9ddad57111
Safira:~ yanigisawa$

And after cleaning all of the python egg files, and rebuilding, I still got the same error. Then I found bug 59006 (http://bugs.mysql.com/bug.php?id=59006) in MySQL 5.5.8 affecting Mac 10.6. I tried the work-around listed there, cleaned eggs and rebuilt, and I'm still getting this error.

Is there another work-around for this problem specific to python? Am I missing something else?

EDIT: Adding output from otool commands:

Safira:~ yanigisawa$ otool -L /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
/Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so:
    libmysqlclient.16.dylib (compatibility version 16.0.0, current version 16.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)
Safira:~ yanigisawa$ otool -DX /usr/local/mysql/lib/libmysqlclient.16.dylib
/usr/local/mysql/lib/libmysqlclient.16.dylib
Safira:~ yanigisawa$

Body:
You could try running otool to find out exactly what library paths the MySQLdb C extension, _mysql.so is looking for:

$ otool -L /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so

and then the installed library name of the MySQL library file:

$ otool -DX /usr/local/mysql/lib/libmysqlclient.16.dylib

But you should not have to resort to setting DYLD_LIBRARY_PATH (or using install_name_tool to modify an executable); the need to set it is almost always a sign of a component that was built or installed incorrectly. In my experience, the MySQL project does not have a very good track record for consistency in their OS X builds and installers, as that issue you cite tends to confirm.

Trying to get a working combination of Python, MySQLdb, and MySQL libraries in OS X 10.6 is a very common cause of frustration: lots of questions about it here on SO and elsewhere.  There are a number reasons for that.  My advice is to go with a complete solution from one of the third-party distributors that will build and install compatible versions of everything you need.  And it should keep working if you need to upgrade components as time goes on.  I've had good success over the years with MacPorts; others prefer Fink or the newer HomeBrew.  With MacPorts, after installing the base files from the MacPorts .dmg, you can get everything built like so:

$ sudo port selfupdate  # ensure the port files are up-to-date
$ sudo port install py26-mysql

The MacPorts Python will be available at /opt/local/bin/python2.6.  If you are looking to run Django, there's a port for that as well.

EDIT: With the updated output from otool, you can see that there is a mismatch of library path names.  The MySQLdb extension is asking for a relative path name (no initial /), while the MySQL library advertises itself with an absolute path, normally what you want.  It seems to be the reverse of the MySQL issue 59006 but, without knowing exactly what steps you've performed up until now, it is really hard to say how you got to this state.  You may be able to use install_name_tool to patch the _mysql.so to have the absolute path name which would also eliminate any need to set DYLD_LIBRARY_PATH.  It's worth trying:

$ cd ~/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp
$ sudo install_name_tool -change libmysqlclient.16.dylib \
                                 /usr/local/mysql/lib/libmysqlclient.16.dylib \
                         _mysql.so

But that should not leave you with a warm and fuzzy feeling that you can reproduce the results when you need to update something.  There really is no virtue in trying to glue all these pieces from different sources into something that works.


问:
Is it mandatory to call NSUserDefaults synchronize method?
Please, anyone, help me: Is calling NSUserDefaults's synchronize() method mandatory?. If I don't call it, what will happen? My application is working fine without it.

答:
No.

Since iOS12, it isn't mandatory anymore.
Apple says:

This method is unnecessary and shouldn't be used.

You can find more information on iOS12 release note:

UserDefaults

NSUserDefaults has several bug fixes and improvements:

Removed synchronization requirements. It's no longer necessary to use synchronize, CFPreferencesAppSynchronize, or CFPreferencesSynchronize. These methods will be deprecated in a future version of the OS.

Now that you don't need to call these synchronization methods, the performance characteristics of NSUserDefaults and Preferences Utilities are slightly different: The time taken for enqueueing write operations is now paid by the writing thread, rather than by the next thread to call synchronize or do a read operation.