问:
How can I handle DLL errors in VBA?
The API declaration:

```<code>Private Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" ( _
                         ByVal lpPrevWndFunc As Long, _
                         ByVal HWnd As Long, _
                         ByVal msg As Long, _
                         ByVal wParam As Long, _
                         ByVal lParam As Long) As Long
</code>```

will crash Excel when provided with a non-existent function pointer for the lpPrevWndFunc parameter.

Similarly,

```<code>Private Declare Sub RtlMoveMemory Lib "kernel32" (ByRef Destination As LongPtr, _
                                                  ByRef Source As LongPtr, _
                                                  ByVal Length As Long)
</code>```

isn't happy when Destination or Source don't exist.

I think these errors are memory access violations. I assume Windows tells the caller that it's doing something it can't1 - perhaps it sends a message to Excel and there's no handler for it? MSDN has this to say about it:

System errors during calls to Windows dynamic-link libraries (DLL) or
  Macintosh code resources do not raise exceptions and cannot be trapped
  with Visual Basic error trapping. When calling DLL functions, you
  should check each return value for success or failure (according to
  the API specifications), and in the event of a failure, check the
  value in the Err object's LastDLLError property. LastDLLError always
  returns zero on the Macintosh.
  (emphasis my own)

But in these instances I have no values to check for errors, I just get a crash.

1: Provided it catches the error which it might not always, if say a memory rewrite is valid but undefined. But certainly writing to restricted memory or calling fake pointers should be caught before they're executed right?

I'm most interested in:

What causes this crash (both how it is triggered, and what exactly the mechanism is behind it - how does Excel know it needs to be crashing?). What is the message channel over which these errors are being communicated, and can I intercept them with VBA code?

Whether the crash can be pro-actively (i.e. sanitising inputs etc.) or retro-actively (handling errors) prevented.

I think (1) will likely shed light on (2) and vice-versa

Anyway, if anyone knows how to handle API errors like these without Excel crashing, or how to avoid them happening, or anything that would be fab. On Error Resume Next doesn't seem to work...

```<code>Sub CrashExcel()
    On Error Resume Next 'Lord preserve us
    'Copy 300 bytes from one non existent memory pointer to another
    RtlMoveMemory ByVal 100, ByVal 200, 300
    On Error Goto 0
    Debug.Assert Err.LastDllError = 0 'Yay no errors
End Sub
</code>```

Motivation

There are 2 main reasons I'm asking about this:

Developing code (the process of debugging etc.) is made much harder when Excel crashes every time I make a mistake. This is not something that can be solved by simply getting it right myself (and exposing a different interface to client code, which uses my existing correct implementations of API calls) because I rarely get it right first time!

I would like to create robust code which is able to handle errors in user input (e.g. invalid function pointers or memory write locations). This can be dealt with to an extent by, for example, abstracting function pointers away into callable classes, but that's not a general solution for other kinds of dll errors (and still doesn't deal with 1.)

Specifically, I'm trying to develop a friendly interface to wrap WinAPI timers. These require callback functions to be registered with them, which (given the limitations of VBA) have to come in the form of Long function pointers (generated with the AddressOf keyword).

The callbacks come from user code and may be invalid. The whole point of my wrapping is to improve stability of the API calls, and this is one area that needs improvement.

The memory copy problem is probably out of scope of this question, it's to do with making generators in VBA, but I think the same error handling techniques would be applicable there too, and it makes for an easier example.

I also get errors and crashes from the Timer API generating too many unhandled messages for Excel. Once again I wonder, how does Windows tell Excel "Time to crash now", why can't I intercept that instruction and deal with the error myself (i.e. Kill all the Timers I made & flush the message queue)?

答:
Some of these Windows API calls can be dangerous.  If you want to ship Windows API functionality as a library feature then it would be courteous not to expose you clients to such danger.  So, you are best to implement your own interface layer.

Below is code that ships the Windows Timer API as a library feature that is safe for use because it passes string names of callback code instead of pointers.

This code was first published on my blog.  Also on that blog post I discuss alternatives to Application.Run if you want options.

```<code>Option Explicit
Option Private Module

'* Brought to you by the Excel Development Platform blog
'* First published at https://exceldevelopmentplatform.blogspot.com/2019/05/vba-make-windows-timer-as-library.html

Private Declare Function ApiSetTimer Lib "user32.dll" Alias "SetTimer" (ByVal hWnd As Long, ByVal nIDEvent As Long, _
                        ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Private Declare Function ApiKillTimer Lib "user32.dll" Alias "KillTimer" (ByVal hWnd As Long, ByVal nIDEvent As Long) As Long

Private mdicCallbacks As New Scripting.Dictionary

Private Sub SetTimer(ByVal sUserCallback As String, lMilliseconds As Long)
    Dim retval As Long  ' return value

    Dim lUniqueId As Long
    lUniqueId = mdicCallbacks.HashVal(sUserCallback) 'should be unique enough

    mdicCallbacks.Add lUniqueId, sUserCallback

    retval = ApiSetTimer(Application.hWnd, lUniqueId, lMilliseconds, AddressOf TimerProc)
End Sub

Private Sub TimerProc(ByVal hWnd As Long, ByVal uMsg As Long, ByVal idEvent As Long, _
        ByVal dwTime As Long)

    ApiKillTimer Application.hWnd, idEvent

    Dim sUserCallback As String
    sUserCallback = mdicCallbacks.Item(idEvent)
    mdicCallbacks.Remove idEvent

    Application.Run sUserCallback
End Sub

'****************************************************************************************************************************************
' User code below
'****************************************************************************************************************************************

Private Sub TestSetTimer()
    SetTimer "UserCallBack", 500
End Sub

Private Function UserCallBack()
    Debug.Print "hello from UserCallBack"
End Function
</code>```

Title: How can I handle DLL errors in VBA?

Body:
The API declaration:

Private Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" ( _
                         ByVal lpPrevWndFunc As Long, _
                         ByVal HWnd As Long, _
                         ByVal msg As Long, _
                         ByVal wParam As Long, _
                         ByVal lParam As Long) As Long

will crash Excel when provided with a non-existent function pointer for the lpPrevWndFunc parameter.

Similarly,

Private Declare Sub RtlMoveMemory Lib "kernel32" (ByRef Destination As LongPtr, _
                                                  ByRef Source As LongPtr, _
                                                  ByVal Length As Long)

isn't happy when Destination or Source don't exist.

I think these errors are memory access violations. I assume Windows tells the caller that it's doing something it can't1 - perhaps it sends a message to Excel and there's no handler for it? MSDN has this to say about it:

System errors during calls to Windows dynamic-link libraries (DLL) or
  Macintosh code resources do not raise exceptions and cannot be trapped
  with Visual Basic error trapping. When calling DLL functions, you
  should check each return value for success or failure (according to
  the API specifications), and in the event of a failure, check the
  value in the Err object's LastDLLError property. LastDLLError always
  returns zero on the Macintosh.
  (emphasis my own)

But in these instances I have no values to check for errors, I just get a crash.

1: Provided it catches the error which it might not always, if say a memory rewrite is valid but undefined. But certainly writing to restricted memory or calling fake pointers should be caught before they're executed right?

I'm most interested in:

What causes this crash (both how it is triggered, and what exactly the mechanism is behind it - how does Excel know it needs to be crashing?). What is the message channel over which these errors are being communicated, and can I intercept them with VBA code?

Whether the crash can be pro-actively (i.e. sanitising inputs etc.) or retro-actively (handling errors) prevented.

I think (1) will likely shed light on (2) and vice-versa

Anyway, if anyone knows how to handle API errors like these without Excel crashing, or how to avoid them happening, or anything that would be fab. On Error Resume Next doesn't seem to work...

Sub CrashExcel()
    On Error Resume Next 'Lord preserve us
    'Copy 300 bytes from one non existent memory pointer to another
    RtlMoveMemory ByVal 100, ByVal 200, 300
    On Error Goto 0
    Debug.Assert Err.LastDllError = 0 'Yay no errors
End Sub

Motivation

There are 2 main reasons I'm asking about this:

Developing code (the process of debugging etc.) is made much harder when Excel crashes every time I make a mistake. This is not something that can be solved by simply getting it right myself (and exposing a different interface to client code, which uses my existing correct implementations of API calls) because I rarely get it right first time!

I would like to create robust code which is able to handle errors in user input (e.g. invalid function pointers or memory write locations). This can be dealt with to an extent by, for example, abstracting function pointers away into callable classes, but that's not a general solution for other kinds of dll errors (and still doesn't deal with 1.)

Specifically, I'm trying to develop a friendly interface to wrap WinAPI timers. These require callback functions to be registered with them, which (given the limitations of VBA) have to come in the form of Long function pointers (generated with the AddressOf keyword).

The callbacks come from user code and may be invalid. The whole point of my wrapping is to improve stability of the API calls, and this is one area that needs improvement.

The memory copy problem is probably out of scope of this question, it's to do with making generators in VBA, but I think the same error handling techniques would be applicable there too, and it makes for an easier example.

I also get errors and crashes from the Timer API generating too many unhandled messages for Excel. Once again I wonder, how does Windows tell Excel "Time to crash now", why can't I intercept that instruction and deal with the error myself (i.e. Kill all the Timers I made & flush the message queue)?

Body:
Some of these Windows API calls can be dangerous.  If you want to ship Windows API functionality as a library feature then it would be courteous not to expose you clients to such danger.  So, you are best to implement your own interface layer.

Below is code that ships the Windows Timer API as a library feature that is safe for use because it passes string names of callback code instead of pointers.

This code was first published on my blog.  Also on that blog post I discuss alternatives to Application.Run if you want options.

Option Explicit
Option Private Module

'* Brought to you by the Excel Development Platform blog
'* First published at https://exceldevelopmentplatform.blogspot.com/2019/05/vba-make-windows-timer-as-library.html

Private Declare Function ApiSetTimer Lib "user32.dll" Alias "SetTimer" (ByVal hWnd As Long, ByVal nIDEvent As Long, _
                        ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Private Declare Function ApiKillTimer Lib "user32.dll" Alias "KillTimer" (ByVal hWnd As Long, ByVal nIDEvent As Long) As Long

Private mdicCallbacks As New Scripting.Dictionary

Private Sub SetTimer(ByVal sUserCallback As String, lMilliseconds As Long)
    Dim retval As Long  ' return value

    Dim lUniqueId As Long
    lUniqueId = mdicCallbacks.HashVal(sUserCallback) 'should be unique enough

    mdicCallbacks.Add lUniqueId, sUserCallback

    retval = ApiSetTimer(Application.hWnd, lUniqueId, lMilliseconds, AddressOf TimerProc)
End Sub

Private Sub TimerProc(ByVal hWnd As Long, ByVal uMsg As Long, ByVal idEvent As Long, _
        ByVal dwTime As Long)

    ApiKillTimer Application.hWnd, idEvent

    Dim sUserCallback As String
    sUserCallback = mdicCallbacks.Item(idEvent)
    mdicCallbacks.Remove idEvent

    Application.Run sUserCallback
End Sub

'****************************************************************************************************************************************
' User code below
'****************************************************************************************************************************************

Private Sub TestSetTimer()
    SetTimer "UserCallBack", 500
End Sub

Private Function UserCallBack()
    Debug.Print "hello from UserCallBack"
End Function


来源: stackexchange

问:
Deploy Web App from Visual Studio Code to Azure App Service
I have a "Hello, World" Node.js app. My app has the following structure:

```<code>/
  /src
    index.html
  package.json
  README.md
</code>```

The index.html file just contains this:

```<code><html>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
</code>```

I am successfully running this locally using npm test via lite-server. My package.json file looks like this:

```<code>{
  "name":"my-hello-world",
  "version":"0.0.1",
  "description":"This is a test",
  "main":"index.js"
  "scripts": {
    "start": "lite-server --baseDir=src"
  },
  "author":"",
  "devDependencies": {
    "lite-server":"^2.5.3"
  }
}
</code>```

I am attempting to deploy this via the "Azure App Service" Visual Studio Code extension. To do this, I:

Right-click on my app service in the explorer.

Choose "Deploy to Web App..."

Select the "src" directory.

Click the "Deploy" button

When I click "Browse Website", I just see a "Hey, Node developers!" splash screen. However, when I run npm start on my local machine, the "Hello World!" page shows as expected. What am I missing?

答:
I tried to deploy the node web to azure and configure the bs-config.json, the page will show error page. Then I check the Application Logs, then I found it will open localhost port and I check the lite-server github page, found it uses BrowserSync, it's a tool for local development.

If you just want to test node web with azure, you could try with the code provided by the official doc: Create a Node.js web app in Azure. You don't need change anything just extract the zip file and deploy it. It will work.

ContentLicense: CC BY-SA 4.0

Body:
I have a "Hello, World" Node.js app. My app has the following structure:

/
  /src
    index.html
  package.json
  README.md

The index.html file just contains this:

Hello World!

I am successfully running this locally using npm test via lite-server. My package.json file looks like this:

{
  "name":"my-hello-world",
  "version":"0.0.1",
  "description":"This is a test",
  "main":"index.js"
  "scripts": {
    "start": "lite-server --baseDir=src"
  },
  "author":"",
  "devDependencies": {
    "lite-server":"^2.5.3"
  }
}

I am attempting to deploy this via the "Azure App Service" Visual Studio Code extension. To do this, I:

Right-click on my app service in the explorer.

Choose "Deploy to Web App..."

Select the "src" directory.

Click the "Deploy" button

When I click "Browse Website", I just see a "Hey, Node developers!" splash screen. However, when I run npm start on my local machine, the "Hello World!" page shows as expected. What am I missing?


问:
Classify file extension and applying logic
Need to execute logic depending on the file extension.

Input: $FileName = "ABC.tar.gz.manifest" or "ABC.tar.gz" or "ABC.zip"

```<code>$EXTZ = ".zip"
$EXTGZ = "tar.gz"
$EXT = $FileName -match "$EXTZ"

$EXT
if ($EXT = 'True') {
    Write-Host "$EXTZ"
} elseif ($EXT = 'False') {
   Write-Host "$EXTGZ"
}
</code>```

But the problem is some files are having the double extension.
How we can solve this?

If the extension is .zip need to print "ABC".

If the file extension is .tar.gz or .tar.gz.manifest need to print "XYZ".

答:
You can check if the $fileInfo contains the extension (you have a problem in the if, in PowerShell you can't do =, you do -eq):

```<code>$Filename = "ABC.tar.gz.manifest"
$EXTGZ = "tar.gz"
$EXT = $Filename.Contains($EXTGZ)
if($EXT -eq $true)
{
   # Do Something
}
</code>```

Body:
Need to execute logic depending on the file extension.

Input: $FileName = "ABC.tar.gz.manifest" or "ABC.tar.gz" or "ABC.zip"

$EXTZ = ".zip"
$EXTGZ = "tar.gz"
$EXT = $FileName -match "$EXTZ"

$EXT
if ($EXT = 'True') {
    Write-Host "$EXTZ"
} elseif ($EXT = 'False') {
   Write-Host "$EXTGZ"
}

But the problem is some files are having the double extension.
How we can solve this?

If the extension is .zip need to print "ABC".

If the file extension is .tar.gz or .tar.gz.manifest need to print "XYZ".

Body:
You can check if the $fileInfo contains the extension (you have a problem in the if, in PowerShell you can't do =, you do -eq):

$Filename = "ABC.tar.gz.manifest"
$EXTGZ = "tar.gz"
$EXT = $Filename.Contains($EXTGZ)
if($EXT -eq $true)
{
   # Do Something
}


问:
Google Analytic API Error (500) Backend Error
We have a sales tracker app. In this app, we collect all analytic data from 5 different analytic accounts (websites) and creating reports. It was working till today morning itself. Now it shows some errors like 500 Backend Error:

PHP Fatal error:  Uncaught Google_Service_Exception: {"error":{"errors":[{"domain":"global","reason":"backendError","message":"Backend Error"}],"code":500,"message":"Backend Error"}}

答:
500 errors are catch all errors that normally mean that there is something on the servers end that is the issue. If you check the documentation you will see the above comment.  Google says that they dont want you to retry that error.  However if you scroll down a bit more in the documentation you will find this section.

However we find the following as well.

However there is nothing with both "code":500,"message":"Backend Error"

backoff

There are a number of error messages where backoff would work.

With a python example that includes

This is because the Google analytics api is slightly different than the other Google apis the way it returns errors is not the same and in most cases its better. The reason for this is that backend error can be cause by flood protection.  Not often but it can happen mostly around the hour.  You should never run a large script on the hour because then you are competing with everyone that has cron jobs set up to extract data every hour.

I normally only use backoff for 'userRateLimitExceeded', 'quotaExceeded',                               'internalServerError' errors not for 'backendError' but Google is stating it in their documentation so it may be worth a shot.

In the mean time i am going to send an email off to the team to get some clarification on the documentation.

500,"message":"Backend Error"

As for the message above i have seen this a few times and its often related to an issue on Googles end.  Give back off a try while i wait to hear back from the team.


问:
Angularjs custom directive using http promise not binding with template
I am new to angularjs and want to add new feature in existing code. But code is not working as expected. I know i am not doing it the right way. Please correct me where is the mistake.
I don't know why controller is not used but directive is used in this approach?

Here is my custom service and custom directive directive code.

Service code:

```<code>angular.module("quickquiz-builder").service("SettingsService", function ($http, $q) {
    return {
    /* Return deffered promise response */
        get: function() {
            var deferred = $q.defer();
            $http.get('get.php')
            .then(function(response){
                var config = response.data.config;
                config = JSON.parse(config);
                this.generalSettings = config.settings;
                deferred.resolve(this);
            })
            .catch(function(response){
              deferred.reject(response);
            });
            return deferred.promise;
        }
    }
})
</code>```

Custom Directive:

```<code>angular.module("quickquiz-builder").directive("quizbuilderSettings", ["SettingsService", "QuestionsService", "$filter", function (SettingsService, QuestionsService, c) {
    return {
        restrict: "E",
        scope: {},
        templateUrl: "templates/settings.html",
        controllerAs: "ctrl",
        controller: ["$scope", function (scope) {
            SettingsService.get().then(function (data){
    /* get response from service inside callback */
                this.settingsService = data;
                scope.settingsService = this.settingsService;
                this.questionsService = QuestionsService;
                console.log(1);
                console.log(scope.settingsService.generalSettings);
                console.log(1+' end');
            }).catch(function(e){
                console.dir(e);
            });
        }]
    }
}])
</code>```

The service response is retrieved successfully inside callback in directive. But this response is not binding with view.

A piece of template code is:

```<code><div layout="row" class="option">
    <md-switch class="md-primary var-label" aria-label="graded" ng-model="ctrl.settingsService.generalSettings.graded" ng-change="ctrl.onChangeGraded()">
         <strong>Graded</strong>
    </md-switch>
    <p flex=""><span ng-if="ctrl.settingsService.generalSettings.graded">The quiz has at least one graded question (a question that has a right/wrong answer).</span><span ng-if="!ctrl.settingsService.generalSettings.graded">It's not a graded quiz.</span>
    </p>
</div>
</code>```

答:
@doublesharp, you are absolutely right. The problem was with data binding and scoping.

First we need to bind the data properly inside App directive, so it is available in the view.

scope.settingsService = this.settingsService;

Which I was doing already right. Because simply with 'this' operator, its scope was inside the promise callback function. 'this' operator was not representing for controller/directive level.

Access the value properly in view.

Use

```<code><element nm-model="settingsService.generalSettings.graded"></element>
</code>```

Instead of

```<code><element nm-model="ctrl.settingsService.generalSettings.graded"></element>
</code>```

Accessing the variable/object inside view with ctrl (i.e controllerAs) was not according to scope of directive. Because binding at directive level was not with 'this' operator.

Body:
I am new to angularjs and want to add new feature in existing code. But code is not working as expected. I know i am not doing it the right way. Please correct me where is the mistake.
I don't know why controller is not used but directive is used in this approach?

Here is my custom service and custom directive directive code.

Service code:

angular.module("quickquiz-builder").service("SettingsService", function ($http, $q) {
    return {
    /* Return deffered promise response */
        get: function() {
            var deferred = $q.defer();
            $http.get('get.php')
            .then(function(response){
                var config = response.data.config;
                config = JSON.parse(config);
                this.generalSettings = config.settings;
                deferred.resolve(this);
            })
            .catch(function(response){
              deferred.reject(response);
            });
            return deferred.promise;
        }
    }
})

Custom Directive:

angular.module("quickquiz-builder").directive("quizbuilderSettings", ["SettingsService", "QuestionsService", "$filter", function (SettingsService, QuestionsService, c) {
    return {
        restrict: "E",
        scope: {},
        templateUrl: "templates/settings.html",
        controllerAs: "ctrl",
        controller: ["$scope", function (scope) {
            SettingsService.get().then(function (data){
    /* get response from service inside callback */
                this.settingsService = data;
                scope.settingsService = this.settingsService;
                this.questionsService = QuestionsService;
                console.log(1);
                console.log(scope.settingsService.generalSettings);
                console.log(1+' end');
            }).catch(function(e){
                console.dir(e);
            });
        }]
    }
}])

The service response is retrieved successfully inside callback in directive. But this response is not binding with view.

A piece of template code is:

    <md-switch class="md-primary var-label" aria-label="graded" ng-model="ctrl.settingsService.generalSettings.graded" ng-change="ctrl.onChangeGraded()">
         Graded
    </md-switch>

The quiz has at least one graded question (a question that has a right/wrong answer).It's not a graded quiz.

Body:
@doublesharp, you are absolutely right. The problem was with data binding and scoping.

First we need to bind the data properly inside App directive, so it is available in the view.

scope.settingsService = this.settingsService;

Which I was doing already right. Because simply with 'this' operator, its scope was inside the promise callback function. 'this' operator was not representing for controller/directive level.

Access the value properly in view.

Use

<element nm-model="settingsService.generalSettings.graded"></element>

Instead of

<element nm-model="ctrl.settingsService.generalSettings.graded"></element>

Accessing the variable/object inside view with ctrl (i.e controllerAs) was not according to scope of directive. Because binding at directive level was not with 'this' operator.


问:
How convert template HTML with images to PDF in ServiceNow?
I need to create dynamic pdf with html templates in servicenow, but my problem is that these pdf must contain images and styles, and I have not been able to solve it.

try using the api of GeneralPDF of servicenow and get the template converted to pdf but only when it contains text. when I put images I get the following error:

This error appears to me when executing my code:

ExceptionConverter: java.io.IOException: The document has no pages.:
  org.mozilla.javascript.JavaScriptException: ExceptionConverter:
  java.io.IOException: The document has no pages.:

this is in a script include and is called from UI Action
my code to convert the html to pdf is the following:

```<code>create : function (sys_id){

   var carta = new GlideRecord('x_solsa_casos_plant_doc');
    carta.addQuery('sys_id','6f1e4ac8db29f300ab7c0f95ca96197a');
    carta.query();
    if(carta.next()){
        var parsedBody = carta.body;
        var gr = new GlideRecord('x_solsa_casos_x_solsa_casos');
        gr.get('sys_id',sys_id);
        var sampleString=parsedBody.toString();
        var reg = new SNC.Regex('/\\$\\{(.*?)\\}/i');
        var match = reg.match(sampleString);
        var count =0;
        var variables = [];
        var values = [];
        var tmpValue;
        while (match != null)
        {
            variables.push(match.toString().substring(match.toString().indexOf(',')+1));
            match = reg.match();
            values.push(variables[count]);
            gs.log("array values : " + values);
            if(gr.getDisplayValue(values[count])==null || JSUtil.nil(gr.getDisplayValue(values[count])))
            {
                tmpValue='';
            }else{
                tmpValue=gr.getDisplayValue(values[count]);
                gs.log("tmpValue :" +tmpValue);
            }
            parsedBody = parsedBody.replace('${'+variables[count]+'}', tmpValue);
                count++;
                gs.log("parsedBody : " + parsedBody);
        }
        this.createPDF(parsedBody,'x_solsa_casos_x_solsa_casos',sys_id,'carta.pdf');
    }
</code>```

},

```<code>createPDF : function(html, table, sys_id, filename) {
  var pdfDoc = new GeneralPDF.Document(null, null, null, null, null, null);
  this._document = new GeneralPDF(pdfDoc);
  this._document.startHTMLParser();
  this._document.addHTML(html);
  this._document.stopHTMLParser();
  this.saveAs(table, sys_id, filename);
</code>```

},

```<code>saveAs : function (table, sys_id, filename){
  var att = new GeneralPDF.Attachment();
  att.setTableName(table);
  att.setTableId(sys_id);
  att.setName(filename);
  att.setType('application/pdf');
  att.setBody(this._document.get());
  GeneralPDF.attach(att);
</code>```

},

答:
Looks like parsedBody is empty or doesn't always contain HTML. According to this answer, paseXHtml (which ServiceNow probably uses and should be in the complete stack trace) expects HTML tags, not just text:
https://stackoverflow.com/a/20902124/2157581

Body:
I need to create dynamic pdf with html templates in servicenow, but my problem is that these pdf must contain images and styles, and I have not been able to solve it.

try using the api of GeneralPDF of servicenow and get the template converted to pdf but only when it contains text. when I put images I get the following error:

This error appears to me when executing my code:

ExceptionConverter: java.io.IOException: The document has no pages.:
  org.mozilla.javascript.JavaScriptException: ExceptionConverter:
  java.io.IOException: The document has no pages.:

this is in a script include and is called from UI Action
my code to convert the html to pdf is the following:

create : function (sys_id){

   var carta = new GlideRecord('x_solsa_casos_plant_doc');
    carta.addQuery('sys_id','6f1e4ac8db29f300ab7c0f95ca96197a');
    carta.query();
    if(carta.next()){
        var parsedBody = carta.body;
        var gr = new GlideRecord('x_solsa_casos_x_solsa_casos');
        gr.get('sys_id',sys_id);
        var sampleString=parsedBody.toString();
        var reg = new SNC.Regex('/\\$\\{(.*?)\\}/i');
        var match = reg.match(sampleString);
        var count =0;
        var variables = [];
        var values = [];
        var tmpValue;
        while (match != null)
        {
            variables.push(match.toString().substring(match.toString().indexOf(',')+1));
            match = reg.match();
            values.push(variables[count]);
            gs.log("array values : " + values);
            if(gr.getDisplayValue(values[count])==null || JSUtil.nil(gr.getDisplayValue(values[count])))
            {
                tmpValue='';
            }else{
                tmpValue=gr.getDisplayValue(values[count]);
                gs.log("tmpValue :" +tmpValue);
            }
            parsedBody = parsedBody.replace('${'+variables[count]+'}', tmpValue);
                count++;
                gs.log("parsedBody : " + parsedBody);
        }
        this.createPDF(parsedBody,'x_solsa_casos_x_solsa_casos',sys_id,'carta.pdf');
    }

},

createPDF : function(html, table, sys_id, filename) {
  var pdfDoc = new GeneralPDF.Document(null, null, null, null, null, null);
  this._document = new GeneralPDF(pdfDoc);
  this._document.startHTMLParser();
  this._document.addHTML(html);
  this._document.stopHTMLParser();
  this.saveAs(table, sys_id, filename);

},

saveAs : function (table, sys_id, filename){
  var att = new GeneralPDF.Attachment();
  att.setTableName(table);
  att.setTableId(sys_id);
  att.setName(filename);
  att.setType('application/pdf');
  att.setBody(this._document.get());
  GeneralPDF.attach(att);

},


问:
how to do pagination in GridView (Flutter)
I want to implement pagination in GridView I use GridView.builder I want to download 10 by 10 items when the user reaches the last row

答: You can use this plugin here: Paging. Wrap your GridView inside of it and tell me if this works!</p>


问:
How to have a final jar with the dependency inside that jar in the jar format?
I need a configuration for Maven where all the libraries inside the project are in the final jar in the jar format... So i need to have jars inside the final jar. For that i can only use maven. I already tried without success with plugins like one-jar.
Thanks</p>

答:
To make a fat jar that includes all you jar files, add the following code to your pom.xml. When you clean and build the project this will automatically make a fat jar file. You need to give your main class inside <mainClass> tag. That's it.

```<code><project>
      <build>
          <plugins>
              <plugin>
                  <artifactId>maven-assembly-plugin</artifactId>
                  <configuration>
                      <archive>
                          <manifest>
                              <addClasspath>true</addClasspath>
                              <mainClass>your.main.class</mainClass>
                          </manifest>
                      </archive>
                      <descriptorRefs>
                          <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                  </configuration>
                  <executions>
                      <execution>
                          <id>final-jar-with-dependencies</id>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
              </plugin>
          </plugins>
      </build>
    </project>
</code>```

Body:
To make a fat jar that includes all you jar files, add the following code to your pom.xml. When you clean and build the project this will automatically make a fat jar file. You need to give your main class inside <mainClass> tag. That's it.

<project>
      <build>
          <plugins>
              <plugin>
                  <artifactId>maven-assembly-plugin</artifactId>
                  <configuration>
                      <archive>
                          <manifest>
                              <addClasspath>true</addClasspath>
                              <mainClass>your.main.class</mainClass>
                          </manifest>
                      </archive>
                      <descriptorRefs>
                          <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                  </configuration>
                  <executions>
                      <execution>
                          <id>final-jar-with-dependencies</id>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
              </plugin>
          </plugins>
      </build>
    </project>


问:
Power BI Custom Visual : Colour Change when modify date slicer
I created a custom visual in power BI that allowed to insert different types of chart in one plot. But when I insert the plot on the dashboard, I have some trouble with date slicer. I define a colour for ma data and I save it with:

let view = dataView[0].categorical;
let categories = view.categories[0];
let objects = categories.objects;
let value = view.values;

for (let i = 0, len = Math.max(value.length); i < len; i++) {
  viewModel.dataPoints.push({
    category: < string > value[i].source.displayName,
    colour: objects && objects[i] && DataViewObjects.getFillColor(objects[i], {
      objectName: "colorSelector",
      propertyName: "fill"
    }, null),
    selectionId: this.host.createSelectionIdBuilder()
      .withCategory(categories, i)
      .createSelectionId(),
  });
}```

But when I change the date slicer, objects is null or undefined and colour is reset to default.

There is a solution to always save the color in object when slicer is modify.

Thanks for yours help.

答:
enumerateObjectInstances method :

public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstanceEnumeration {
 let objectName = options.objectName;
 let objectEnumeration: VisualObjectInstance[] = [];
 let index = 0;
 switch (objectName) {
  case 'xAxis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.xAxis,
    selector: null
   });
   break;
  case 'y1Axis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.y1Axis,
    selector: null
   });
   break;
  case 'y2Axis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.y2Axis,
    selector: null
   });
   break;
  case 'margin':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.margin,
    selector: null
   });
   break;
  case 'legend':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.legend,
    selector: null
   });
   break;
  case 'colorSelector':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       fill: {
        solid: {
         color: dp.colour || this.settings.colorSelector[Object.keys(this.settings.colorSelector)[index]]
        }
       }
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
  case 'datashape':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       shape: dp.symbol || this.settings.datashape[Object.keys(this.settings.datashape)[index]]
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
  case 'datatrace':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       charttype: dp.trace || this.settings.datatrace[Object.keys(this.settings.datatrace)[index]]
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
   };
   return objectEnumeration;
}```
</div>
</div>
</p>

<p>Capabilities.json :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
    "dataRoles": [
        {
            "displayName": "X-Axis",
            "name": "x",
            "kind": "Grouping"
        },
        {
            "displayName": "Y-Axis 1",
            "name": "y1",
            "kind": "Measure"
        },
        {
            "displayName": "Y-Axis 2",
            "name": "y2",
            "kind": "Measure"
        },
        {
            "displayName": "Split by",
            "name": "splitby1",
            "kind": "Grouping"
        }
    ],
    "dataViewMappings": [
        {
            "conditions": [
                {
                    "x": {
                        "max": 1
                    },
                    "legend": {
                        "max": 1
                    },
                    "splitby1": {
                        "max": 1
                    }
                }
            ],
            "categorical": {
                "categories": {
                    "for": {
                        "in": "x"
                    }
                },
                "values": {
                    "group": {
                        "by": "splitby1",
                        "select": [
                            {
                                "for": {
                                    "in": "y1"
                                }
                            },
                            {
                                "for": {
                                    "in": "y2"
                                }
                            }
                        ]
                    }
                }
            }
        }
    ],
    "suppressDefaultTitle": true,
    "objects": {
        "xAxis": {
            "displayName": "X-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "y1Axis": {
            "displayName": "Y1-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "y2Axis": {
            "displayName": "Y2-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "datatrace": {
            "displayName": "Trace Type",
            "properties": {
                "charttype": {
                    "displayName": "Trace",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Line Chart",
                                "value": "line"
                            },
                            {
                                "displayName": "Line Marker Chart",
                                "value": "lineMarker"
                            }
                        ]
                    }
                }
            }
        },
        "margin": {
            "displayName": "Margins",
            "properties": {
                "l": {
                    "displayName": "Left",
                    "type": {
                        "numeric": true
                    }
                },
                "r": {
                    "displayName": "Right",
                    "type": {
                        "numeric": true
                    }
                },
                "t": {
                    "displayName": "Top",
                    "type": {
                        "numeric": true
                    }
                },
                "b": {
                    "displayName": "Bottom",
                    "type": {
                        "numeric": true
                    }
                }
            }
        },
        "legend": {
            "displayName": "Legend",
            "properties": {
                "enabled": {
                    "displayName": "Enabled",
                    "type": {
                        "bool": true
                    }
                },
                "orientation": {
                    "displayName": "Orientation",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Vertical",
                                "value": "v"
                            },
                            {
                                "displayName": "Horizontal",
                                "value": "h"
                            }
                        ]
                    }
                }
            }
        },
        "colorSelector": {
            "displayName": "Data Colors",
            "properties": {
                "fill": {
                    "displayName": "Color",
                    "type": {
                        "fill": {
                            "solid": {
                                "color": true
                            }
                        }
                    }
                }
            }
        },
        "datashape": {
            "displayName": "Shape Type",
            "properties": {
                "shape": {
                    "displayName": "Shape",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Default",
                                "value": "none"
                            },
                            {
                                "displayName": "Circle",
                                "value": "circle"
                            }
                        ]
                    }
                }
            }
        }
    }
}</code>```

Body:
I created a custom visual in power BI that allowed to insert different types of chart in one plot. But when I insert the plot on the dashboard, I have some trouble with date slicer. I define a colour for ma data and I save it with:

let view = dataView[0].categorical;
let categories = view.categories[0];
let objects = categories.objects;
let value = view.values;

for (let i = 0, len = Math.max(value.length); i < len; i++) {
  viewModel.dataPoints.push({
    category: < string > value[i].source.displayName,
    colour: objects && objects[i] && DataViewObjects.getFillColor(objects[i], {
      objectName: "colorSelector",
      propertyName: "fill"
    }, null),
    selectionId: this.host.createSelectionIdBuilder()
      .withCategory(categories, i)
      .createSelectionId(),
  });
}

But when I change the date slicer, objects is null or undefined and colour is reset to default.

There is a solution to always save the color in object when slicer is modify.

Thanks for yours help.

Body:
enumerateObjectInstances method :

public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstanceEnumeration {
 let objectName = options.objectName;
 let objectEnumeration: VisualObjectInstance[] = [];
 let index = 0;
 switch (objectName) {
  case 'xAxis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.xAxis,
    selector: null
   });
   break;
  case 'y1Axis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.y1Axis,
    selector: null
   });
   break;
  case 'y2Axis':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.y2Axis,
    selector: null
   });
   break;
  case 'margin':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.margin,
    selector: null
   });
   break;
  case 'legend':
   objectEnumeration.push({
    objectName: objectName,
    properties: this.settings.legend,
    selector: null
   });
   break;
  case 'colorSelector':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       fill: {
        solid: {
         color: dp.colour || this.settings.colorSelector[Object.keys(this.settings.colorSelector)[index]]
        }
       }
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
  case 'datashape':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       shape: dp.symbol || this.settings.datashape[Object.keys(this.settings.datashape)[index]]
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
  case 'datatrace':
   if (this.viewModel) {
    for (let dp of this.viewModel.dataPoints) {
     objectEnumeration.push({
      objectName: objectName,
      displayName: dp.category,
      properties: {
       charttype: dp.trace || this.settings.datatrace[Object.keys(this.settings.datatrace)[index]]
      },
      selector: dp.selectionId.getSelector()
     });
    }
   }
   break;
   };
   return objectEnumeration;
}

Capabilities.json :

{
    "dataRoles": [
        {
            "displayName": "X-Axis",
            "name": "x",
            "kind": "Grouping"
        },
        {
            "displayName": "Y-Axis 1",
            "name": "y1",
            "kind": "Measure"
        },
        {
            "displayName": "Y-Axis 2",
            "name": "y2",
            "kind": "Measure"
        },
        {
            "displayName": "Split by",
            "name": "splitby1",
            "kind": "Grouping"
        }
    ],
    "dataViewMappings": [
        {
            "conditions": [
                {
                    "x": {
                        "max": 1
                    },
                    "legend": {
                        "max": 1
                    },
                    "splitby1": {
                        "max": 1
                    }
                }
            ],
            "categorical": {
                "categories": {
                    "for": {
                        "in": "x"
                    }
                },
                "values": {
                    "group": {
                        "by": "splitby1",
                        "select": [
                            {
                                "for": {
                                    "in": "y1"
                                }
                            },
                            {
                                "for": {
                                    "in": "y2"
                                }
                            }
                        ]
                    }
                }
            }
        }
    ],
    "suppressDefaultTitle": true,
    "objects": {
        "xAxis": {
            "displayName": "X-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "y1Axis": {
            "displayName": "Y1-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "y2Axis": {
            "displayName": "Y2-Axis",
            "properties": {
                "title": {
                    "displayName": "Title",
                    "type": {
                        "text": true
                    }
                },
                "margin": {
                    "displayName": "Margin",
                    "type": {
                        "text": true
                    }
                }
            }
        },
        "datatrace": {
            "displayName": "Trace Type",
            "properties": {
                "charttype": {
                    "displayName": "Trace",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Line Chart",
                                "value": "line"
                            },
                            {
                                "displayName": "Line Marker Chart",
                                "value": "lineMarker"
                            }
                        ]
                    }
                }
            }
        },
        "margin": {
            "displayName": "Margins",
            "properties": {
                "l": {
                    "displayName": "Left",
                    "type": {
                        "numeric": true
                    }
                },
                "r": {
                    "displayName": "Right",
                    "type": {
                        "numeric": true
                    }
                },
                "t": {
                    "displayName": "Top",
                    "type": {
                        "numeric": true
                    }
                },
                "b": {
                    "displayName": "Bottom",
                    "type": {
                        "numeric": true
                    }
                }
            }
        },
        "legend": {
            "displayName": "Legend",
            "properties": {
                "enabled": {
                    "displayName": "Enabled",
                    "type": {
                        "bool": true
                    }
                },
                "orientation": {
                    "displayName": "Orientation",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Vertical",
                                "value": "v"
                            },
                            {
                                "displayName": "Horizontal",
                                "value": "h"
                            }
                        ]
                    }
                }
            }
        },
        "colorSelector": {
            "displayName": "Data Colors",
            "properties": {
                "fill": {
                    "displayName": "Color",
                    "type": {
                        "fill": {
                            "solid": {
                                "color": true
                            }
                        }
                    }
                }
            }
        },
        "datashape": {
            "displayName": "Shape Type",
            "properties": {
                "shape": {
                    "displayName": "Shape",
                    "type": {
                        "enumeration": [
                            {
                                "displayName": "Default",
                                "value": "none"
                            },
                            {
                                "displayName": "Circle",
                                "value": "circle"
                            }
                        ]
                    }
                }
            }
        }
    }
}


问:
user defined exceptions
Are there user-defined exceptions in tsql ?</p>

答:
RAISERROR

Generates an error message and
  initiates error processing for the
  session. RAISERROR can either
  reference a user-defined message
  stored in the sys.messages catalog
  view or build a message dynamically.
  The message is returned as a server
  error message to the calling
  application or to an associated CATCH
  block of a TRY…CATCH construct.

from MSDN

ContentLicense: CC BY-SA 3.0

Title: user defined exceptions


问:
Get data into Graphite/Carbon using Python3
I've got a Grafana docker image running with Graphite/Carbon. Getting data using CLI works, example:

echo "local.random.diceroll $(((RANDOM%6)+1)) `date +%s`" | nc localhost 2003;

The following Python 2 code also works:

```<code>sock = socket.socket()
sock.connect((CARBON_SERVER, CARBON_PORT))
sock.sendall(message)
sock.close()
</code>```

message is a string containing key value timestamp and this works, the data can be found. So the Grafana docker image is accepting data.

I wanted to get this working in Python 3, but the sendall function requires bytes as parameter. The code change is:

```<code>sock = socket.socket()
sock.connect((CARBON_SERVER, CARBON_PORT))
sock.sendall(str.encode(message))
sock.close()
</code>```

Now the data isn't inserted and I can't figure out why. I tried this on a remote machine (same network) and on the local server. I also tried several packages (graphiti, graphiteudp), but they all seem to fail to insert the data. They also don't show any error message.

The simple example for graphiteudp doesn't work either on the Github page

Got an idea what I'm doing wrong?

答: You can add \n to the message you send. I have tried it with Python 3, and that works.

Body:
I've got a Grafana docker image running with Graphite/Carbon. Getting data using CLI works, example:

echo "local.random.diceroll $(((RANDOM%6)+1)) `date +%s`" | nc localhost 2003;

The following Python 2 code also works:

sock = socket.socket()
sock.connect((CARBON_SERVER, CARBON_PORT))
sock.sendall(message)
sock.close()

message is a string containing key value timestamp and this works, the data can be found. So the Grafana docker image is accepting data.

I wanted to get this working in Python 3, but the sendall function requires bytes as parameter. The code change is:

sock = socket.socket()
sock.connect((CARBON_SERVER, CARBON_PORT))
sock.sendall(str.encode(message))
sock.close()

Now the data isn't inserted and I can't figure out why. I tried this on a remote machine (same network) and on the local server. I also tried several packages (graphiti, graphiteudp), but they all seem to fail to insert the data. They also don't show any error message.

The simple example for graphiteudp doesn't work either on the Github page

Got an idea what I'm doing wrong?


问:
3DES Key Size Matter in C#.Net

Below Code is Working Fine in c#.NET

```<code>byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters
byte[] plainText = Encoding.ASCII.GetBytes("lasaa");
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));
</code>```

My questions regarding above are...

How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?

答:
I think the problem here is that 192bits is the maximum key size supported for 3DES in C# (and elsewhere I assume)

http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgori...

Have you tryed setting the key to a 16 byte/char value?

The only other supported size seems to be 128bits. If you want somthing stronger you'll have to use a different algorithm, Aes/Rijndael.

If you look TDES up on Wikipedia, it seems the maximum key size is 168bits so I'm not sure how Microsoft have implemented it.

I suspect it was omitted from your example for brevity but you should probably hash your key from a good dose of salt. There are several RNG/HSH algorithms for this in the crypto namespace.

Title: 3DES Key Size Matter in C#.Net

Body:
Below Code is Working Fine in c#.NET

byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters
byte[] plainText = Encoding.ASCII.GetBytes("lasaa");
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));

My questions regarding above are...

How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?


问:
Regex to check number of spaces after full stop - Strictly 2 required
I need to check occurrences where I have put one whitespace after a full-stop, and replace it by 2 spaces. I have the Regex for it, but Atom seems to call in invalid.

(?<=\.|\") {1,}(?=[a-zA-Z])

Conditions:

1 spaces after period.

If period in with a closing double quote, then 1 space after the quote.

The above regex works perfectly for my conditions however Atom is not able to validate it. I need to use it for existing files.

答:
You may use

```<code>([."]) ([a-zA-Z])
</code>```

and replace with $1  $2. See the regex demo and a regex graph:

Details

([."]) - Group 1 (its value is referred to with $1 backreference from the replacement pattern): . or "

  - a space (use \s to match any whitespace)

([a-zA-Z]) - Group 2 ($2): an ASCII letter.

Body:
You may use

([."]) ([a-zA-Z])

and replace with $1  $2. See the regex demo and a regex graph:

Details

([."]) - Group 1 (its value is referred to with $1 backreference from the replacement pattern): . or "

  - a space (use \s to match any whitespace)

([a-zA-Z]) - Group 2 ($2): an ASCII letter.


问:
Ionic AngularFireDatabase saying not authorized even though rules are open

Overview

I am attempting to get data from a firebase database but it is saying I do not have permission, even though the rules are totally open.

I started building this current implementation by following this youtube tutorial. After running into errors with the deprecated FirebaseListObservable, I changed my provider according to this update information. I also tried using the default open Firebase rules as well as the ones they recommend for "Allow All" in the Firebase documentation.

Provider

Error Message

Firebase Rules

The default open version of the rules, which also didn't work, had the line as allow read, write;

Database

Other possibly-relevant info

In the same way as can be seen 1 minute into the mentioned youtube tutorial, I am calling initializeApp(firebaseConfig) in the imports of my app.module.ts using the information from clicking "Add Firebase to your web app"

I am using angularfire2@5.0.0-rc.8.0 which I installed with npm install angularfire2. When I ran npm list just now it gave me the following two warnings, which may be relevant to the issue. I'm using @angular/common@5.2.10 and @angular/core@5.2.10

npm ERR! peer dep missing: @angular/common@^6.0.0, required by angularfire2@5.0.0-rc.8.0
  npm ERR! peer dep missing: @angular/core@^6.0.0, required by angularfire2@5.0.0-rc.8.0

答:
As @brenthompson2 mentions, I share the method using Firestore(beta) instead

in app.module.ts

```<code>import { AngularFirestoreModule } from 'angularfire2/firestore';

...
@ngModule({
...
imports: [
...
    AngularFireModule.initializeApp(environment),
    AngularFirestoreModule,
  ],
})
</code>```

and in any angular module or injectables

```<code>  constructor(private store:AngularFirestore) {

  }
  ...

  this.store.doc<any>(`users/${uid}`).snapshotChanges().subscribe(
    data=>{console.log(data.payload.data())}
  );

</code>```

Not that different to firebase2/database

Body:
As @brenthompson2 mentions, I share the method using Firestore(beta) instead

in app.module.ts

import { AngularFirestoreModule } from 'angularfire2/firestore';

...
@ngModule({
...
imports: [
...
    AngularFireModule.initializeApp(environment),
    AngularFirestoreModule,
  ],
})

and in any angular module or injectables

  constructor(private store:AngularFirestore) {

  }
  ...

  this.store.doc<any>(`users/${uid}`).snapshotChanges().subscribe(
    data=>{console.log(data.payload.data())}
  );

Not that different to firebase2/database


问:
Return value as -0 from oracle sql
is there any way to return 0 as -0 from oracle sql/plsql so that we can do some validation , this is just to make sure if the value 0 is rounded from a negative value or positive value.

If there is any alternate approach, to handle this , please let me know, rounding the value in Javascript is not exactly as rounding in oracle sql.

答:
Try to use below way to get your condition satisfied.

```<code>SELECT (CASE WHEN 0=0 THEN '-0' ELSE 'FALSE' END) AS CHK_ZERO FROM DUAL;
</code>```

In the above statement replace one zero with your parameterized variable and get the result as required.

Title: Return value as -0 from oracle sql

Body:
Try to use below way to get your condition satisfied.

SELECT (CASE WHEN 0=0 THEN '-0' ELSE 'FALSE' END) AS CHK_ZERO FROM DUAL;

In the above statement replace one zero with your parameterized variable and get the result as required.


问:
SQL Retrieve data from first table based on search criteria in second table
i Have 2 tables i want to get data from the first table based on where condition applied on the second table.

```<code>PHARMASTOCK(1)      Pharma Products(2)
ID                  ProductID
ProductID           GenericName
TradeName           TradeName
MRP                 Supplier
Rate                Manufacturer
Stock               PurchasePTR
Batch               UnitRate
Expiry              MRP
StockSection
</code>```

This is the SQL stored procedure that i have written but it is not working
as expected!

```<code>@StockSupplier varchar(50), @StockManufacturer Varchar(50)
AS

SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
    Full JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like + @StockSupplier + '%' and Manufacturer  like + @StockManufacturer + '%'
order by Manufacturer asc
</code>```

答:
```<code>SELECT  PS.ProductID,PS.TradeName,PS.MRP,PS.Rate,PS.Batch,PS.Expiry,PS.StockSection,PS.Stock,PP.Supplier,PP.Manufacturer
    from PharmaStock PS
        inner JOIN PharmaProducts PP ON PS.ProductID = PP.ProductID
    where Supplier  like CONCAT(@StockSupplier , '%') and Manufacturer  like CONCAT(@StockManufacturer ,'%') order by Manufacturer asc
</code>```

The concatenate function is changed in the query and then the plus symbol(after like needs to be removed).

Body:
i Have 2 tables i want to get data from the first table based on where condition applied on the second table.

PHARMASTOCK(1)      Pharma Products(2)
ID                  ProductID
ProductID           GenericName
TradeName           TradeName
MRP                 Supplier
Rate                Manufacturer
Stock               PurchasePTR
Batch               UnitRate
Expiry              MRP
StockSection

This is the SQL stored procedure that i have written but it is not working
as expected!

@StockSupplier varchar(50), @StockManufacturer Varchar(50)
AS

SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
    Full JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like + @StockSupplier + '%' and Manufacturer  like + @StockManufacturer + '%'
order by Manufacturer asc

Body:
SELECT  PS.ProductID,PS.TradeName,PS.MRP,PS.Rate,PS.Batch,PS.Expiry,PS.StockSection,PS.Stock,PP.Supplier,PP.Manufacturer
    from PharmaStock PS
        inner JOIN PharmaProducts PP ON PS.ProductID = PP.ProductID
    where Supplier  like CONCAT(@StockSupplier , '%') and Manufacturer  like CONCAT(@StockManufacturer ,'%') order by Manufacturer asc

The concatenate function is changed in the query and then the plus symbol(after like needs to be removed).


问:
Spring Security - Implementing UserDetailsService
I understand that Spring will pass the principal into controller's method if I include it as a method parameter.

I'm trying to extend this functionality by implementing UserDetailsService:

I created a class named CustomUserDetails that extends org.springframework.security.core.userdetails.User

I created a service named CustomUserDetailsService that implements UserDetailsService

Exception

HTTP Status 500 - Request processing failed; nested exception is
  java.lang.ClassCastException:
  org.springframework.security.authentication.UsernamePasswordAuthenticationToken
  cannot be cast to com.demo.model.CustomUserDetails

The following line in my controller method is throwing the exception:

```<code>CustomUserDetails userDetails = (CustomUserDetails) principal;
</code>```

Controller.java

```<code>@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
    public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal, HttpServletRequest request) {

        // Throws exception here
        CustomUserDetails userDetails = (CustomUserDetails) principal;

        System.out.println(userDetails.getFirstName());

        // Tried this and it also throws exception
        // User cannot be cast to CustomUserDetails
        //Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        //CustomUserDetails userDetails = (CustomUserDetails)auth.getPrincipal();

        // Render template located at
        // src/main/resources/templates/dashboard.html
        modelAndView.setViewName("dashboard");

        return modelAndView;
    }
</code>```

SecurityConfiguration.java

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Autowired
    SecurityHandler successHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/register*").permitAll()
                .antMatchers("/reset").permitAll().antMatchers("/forgot").permitAll().antMatchers("/grid").permitAll()
                .antMatchers("/login").permitAll().antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error")
                .defaultSuccessUrl("/dashboard").successHandler(successHandler).usernameParameter("email")
                .passwordParameter("password").and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout").and().exceptionHandling().accessDeniedPage("/access-denied");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/error**", "/resources/**", "/static/**", "/css/**", "/js/**", "/img/**");
    }

}
</code>```

CustomUserDetails.java

```<code>public class CustomUserDetails extends org.springframework.security.core.userdetails.User {

    public CustomUserDetails(String username, String password,
         Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}
</code>```

CustomUserDetailsService.java

```<code>@Service
public class CustomUserDetailsService implements UserDetailsService{

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{

        if(StringUtils.isEmpty(userName))
            throw new UsernameNotFoundException("User name is empty");

        //if you don't use authority based security, just add empty set
        Set<GrantedAuthority> authorities = new HashSet<>();
        CustomUserDetails userDetails = new CustomUserDetails(userName, "", authorities);

        userDetails.setFirstName("Testing: " + new Date());

        return userDetails;
    }

}
</code>```

答:
Change your controller to:

CONTROLLER

```<code>@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Authentication authentication, HttpServletRequest request) {

    CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal;
</code>```

Note it returns a Authentication object.

Body:
I understand that Spring will pass the principal into controller's method if I include it as a method parameter.

I'm trying to extend this functionality by implementing UserDetailsService:

I created a class named CustomUserDetails that extends org.springframework.security.core.userdetails.User

I created a service named CustomUserDetailsService that implements UserDetailsService

Exception

HTTP Status 500 - Request processing failed; nested exception is
  java.lang.ClassCastException:
  org.springframework.security.authentication.UsernamePasswordAuthenticationToken
  cannot be cast to com.demo.model.CustomUserDetails

The following line in my controller method is throwing the exception:

CustomUserDetails userDetails = (CustomUserDetails) principal;

Controller.java

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
    public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal, HttpServletRequest request) {

        // Throws exception here
        CustomUserDetails userDetails = (CustomUserDetails) principal;

        System.out.println(userDetails.getFirstName());

        // Tried this and it also throws exception
        // User cannot be cast to CustomUserDetails
        //Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        //CustomUserDetails userDetails = (CustomUserDetails)auth.getPrincipal();

        // Render template located at
        // src/main/resources/templates/dashboard.html
        modelAndView.setViewName("dashboard");

        return modelAndView;
    }

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Autowired
    SecurityHandler successHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/register*").permitAll()
                .antMatchers("/reset").permitAll().antMatchers("/forgot").permitAll().antMatchers("/grid").permitAll()
                .antMatchers("/login").permitAll().antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error")
                .defaultSuccessUrl("/dashboard").successHandler(successHandler).usernameParameter("email")
                .passwordParameter("password").and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout").and().exceptionHandling().accessDeniedPage("/access-denied");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/error**", "/resources/**", "/static/**", "/css/**", "/js/**", "/img/**");
    }

}

CustomUserDetails.java

public class CustomUserDetails extends org.springframework.security.core.userdetails.User {

    public CustomUserDetails(String username, String password,
         Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

CustomUserDetailsService.java

@Service
public class CustomUserDetailsService implements UserDetailsService{

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{

        if(StringUtils.isEmpty(userName))
            throw new UsernameNotFoundException("User name is empty");

        //if you don't use authority based security, just add empty set
        Set<GrantedAuthority> authorities = new HashSet<>();
        CustomUserDetails userDetails = new CustomUserDetails(userName, "", authorities);

        userDetails.setFirstName("Testing: " + new Date());

        return userDetails;
    }

}

Body:
Change your controller to:

CONTROLLER

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Authentication authentication, HttpServletRequest request) {

    CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal;

Note it returns a Authentication object.


问:
VHDL equivalent to Verilog "10'h234"
I just need to know how to translate constant values from Verilog to VHDL. I wonder if I could still indicate the range and if it is hex, oct, binary, etc., just like in Verilog:
14'h1 -> I do not want to type anything like X"00000000000001"
Thanks!</p>

答:
```<code>constant my_const : std_logic_vector(13 downto 0) := std_logic_vector(to_unsigned(1, 14));
</code>```

or

```<code>constant my_const : std_logic_vector(13 downto 0) := "00" & x"001";
</code>```

Title: VHDL equivalent to Verilog "10'h234"

Body:
constant my_const : std_logic_vector(13 downto 0) := std_logic_vector(to_unsigned(1, 14));

or

constant my_const : std_logic_vector(13 downto 0) := "00" & x"001";


问:
How to change counting label text in Swift 5
```<code>class ViewController: UIViewController {
    var flipCount = 0

    @IBAction func card1(_ sender: UIButton) {
        flipCount += 1
        flipCard(emoje: "☠" , button: sender)
    }

    @IBAction func card2(_ sender: UIButton) {
        flipCount += 1
        flipCard(emoje: "", button: sender)
    }

    @IBOutlet weak var counter: UILabel!
}
</code>```

How can I link my counter to my UI? I can't put flipcountLabel.text.

答:
In your code, you can simply update the UI with flipCount by adding a property observer to the flipCount, i.e.

```<code>var flipCount = 0 {
    didSet {
        counter.text = String(flipCount)
    }
}
</code>```

In the above code, the counter label will be updated with the latest flipCount value whenever there is a change in flipCount.

Body:
class ViewController: UIViewController {
    var flipCount = 0

    @IBAction func card1(_ sender: UIButton) {
        flipCount += 1
        flipCard(emoje: "☠" , button: sender)
    }

    @IBAction func card2(_ sender: UIButton) {
        flipCount += 1
        flipCard(emoje: "", button: sender)
    }

    @IBOutlet weak var counter: UILabel!
}

How can I link my counter to my UI? I can't put flipcountLabel.text.

Body:
In your code, you can simply update the UI with flipCount by adding a property observer to the flipCount, i.e.

var flipCount = 0 {
    didSet {
        counter.text = String(flipCount)
    }
}

In the above code, the counter label will be updated with the latest flipCount value whenever there is a change in flipCount.


问:
jQuery show and enter div on hover
There are answers to the question how to show a div when hovering over another div, but in my example I need to hover over an anchor tag which shows a list of menu bar items and after that to go with the mouse over that list of menu bar items. After that, when I mouseout the entered list, the list should hide. The problem is when I hover out of the menu bar list, it does not disappear.

I tried to do it when hovering over js-expand to show js-am-content and when mouseout over menu-bar-item to hide the content if menu-bar-item is not hovered on, but the content does not hide.

This is my simplified HTML

```<code><div>
  <a class="expand js-expand fa fa-bars"></a>
  <div class="action-menu-content js-am-content">
    <a class="menu-bar-item"> SHOW </a>
    <a class="menu-bar-item"> EDIT </a>
    <a class="menu-bar-item"> COLLECTIVE </a>
    <a class="menu-bar-item"> PER ORDER </a>
    <a class="menu-bar-item"> CUSTOMS </a>
    <a class="menu-bar-item"> HISTORY </a>
  </div>
</div>
</code>```

and jQuery (coffee script)

```<code>$(document).on 'mouseover', '.js-expand', (event) =>
  $parent = $(event.currentTarget).parent()
  $parent.children(".js-am-content").slideToggle('fast')

$(document).on 'mouseout', '.menu-bar-item', (event) =>
  if !$('.menu-bar-item:hover')
    $('.js-am-content').fadeOut('fast')
</code>```

答:
Why don't you just try this :

```<code> $(document).on 'mouseout', '.menu-bar-item', (event) =>
    $('.js-am-content').fadeOut('fast');
</code>```

I mean why do we need to check for "item:hover" when we are already making mouseout  event on the parent

Title: jQuery show and enter div on hover

Body:
There are answers to the question how to show a div when hovering over another div, but in my example I need to hover over an anchor tag which shows a list of menu bar items and after that to go with the mouse over that list of menu bar items. After that, when I mouseout the entered list, the list should hide. The problem is when I hover out of the menu bar list, it does not disappear.

I tried to do it when hovering over js-expand to show js-am-content and when mouseout over menu-bar-item to hide the content if menu-bar-item is not hovered on, but the content does not hide.

This is my simplified HTML

     SHOW
     EDIT
     COLLECTIVE
     PER ORDER
     CUSTOMS
     HISTORY

and jQuery (coffee script)

$(document).on 'mouseover', '.js-expand', (event) =>
  $parent = $(event.currentTarget).parent()
  $parent.children(".js-am-content").slideToggle('fast')

$(document).on 'mouseout', '.menu-bar-item', (event) =>
  if !$('.menu-bar-item:hover')
    $('.js-am-content').fadeOut('fast')

Body:
Why don't you just try this :

 $(document).on 'mouseout', '.menu-bar-item', (event) =>
    $('.js-am-content').fadeOut('fast');

I mean why do we need to check for "item:hover" when we are already making mouseout  event on the parent


问:
Ant Design Upload get file content
I am using the Ant Design Upload component. Is there a way I can get the content of the selected file as a string in JavaScript in order to display it on the page?

Ideally, I would like to access file.data or something.

```<code><Upload
    accept=".txt, .csv"
    showUploadList={false}
    beforeUpload={(file, fileList) => {
        // Access file content here and do something with it
        console.log(file);

        // Prevent upload
        return false;
    }}
>
    <Button>
        <Icon type="upload" /> Click to Upload
    </Button>
</Upload>
</code>```

答:
Heavily inspired by this answer from Shreyans Shrivastav but modified to better suit what has been asked. You can use a FileReader to read the content of the file:

```<code><Upload
    accept=".txt, .csv"
    showUploadList={false}
    beforeUpload={file => {
        const reader = new FileReader();

        reader.onload = e => {
            console.log(e.target.result);
        };
        reader.readAsText(file);

        // Prevent upload
        return false;
    }}
>
    <Button>
        <Icon type="upload" /> Click to Upload
    </Button>
</Upload>;
</code>```

Title: Ant Design Upload get file content

Body:
I am using the Ant Design Upload component. Is there a way I can get the content of the selected file as a string in JavaScript in order to display it on the page?

Ideally, I would like to access file.data or something.

<Upload
    accept=".txt, .csv"
    showUploadList={false}
    beforeUpload={(file, fileList) => {
        // Access file content here and do something with it
        console.log(file);

        // Prevent upload
        return false;
    }}
>
    <Button>
        <Icon type="upload" /> Click to Upload
    </Button>
</Upload>

Body:
Heavily inspired by this answer from Shreyans Shrivastav but modified to better suit what has been asked. You can use a FileReader to read the content of the file:

<Upload
    accept=".txt, .csv"
    showUploadList={false}
    beforeUpload={file => {
        const reader = new FileReader();

        reader.onload = e => {
            console.log(e.target.result);
        };
        reader.readAsText(file);

        // Prevent upload
        return false;
    }}
>
    <Button>
        <Icon type="upload" /> Click to Upload
    </Button>
</Upload>;


问:
MALLOC_CHECK_ for linux daemons
Can we use MALLOC_CHECK_ for linux daemon processes?

Basically I want to examine an another process(a C program) which runs as daemon and is crashing when my application(a C program) is using it(other process).
The crash is as follows:

```<code>#0  0xffffe430 in __kernel_vsyscall ()
#1  0xf7426e30 in raise () from /lib/libc.so.6
#2  0xf7428765 in abort () from /lib/libc.so.6
#3  0xf7465d75 in __libc_message () from /lib/libc.so.6
#4  0xf746bd04 in malloc_printerr () from /lib/libc.so.6
#5  0xf746d613 in _int_free () from /lib/libc.so.6
#6  0xf747074d in free () from /lib/libc.so.6
#7  0xf6043a61 in BufferFree (memblk=0xf1f82f90) at ../allocator/alloclib.c:447
</code>```

Is there any other way to debug other then valgrind?

答:
How to enable MALLOC_CHECK_

The below article explains the usage of MALLOC_CHECK_

MALLOC_CHECK_ can be used in the script from where you are triggering your daemons. Below export in the script will enable malloc check for all the daemons which are triggered using the script.

```<code>export MALLOC_CHECK_=X, Where X can be 0,1 or 3
</code>```

If MALLOC_CHECK_ is set to 0 (zero), the memory management functions
are simply most tolerant of errors and do not give warnings. Maybe be
useful if we are prevented from finding one memory bug by another that
is not convenient to fix at the moment; it might allow us to use other
tools to chase down the other memory bug. It may also be useful if you
are running code that works on another system but not on Linux.  It
can provide a quick workaround that may allow the code to temporarily
function before you have the chance to resolve the error.

If MALLOC_CHECK_ is set to 1 (one), the memory management functions
print out warning messages on standard error when problems are
noticed. It is useful if we are not aware of any problems and just
wants to be notified if any problem exists.

If MALLOC_CHECK_ is set to 2 (two), the memory management functions
call abort()when problems are noticed. This is most useful from inside
the debugger or a shell starting an application or daemon.  It allows
a backtrace to be obtained as soon as the memory management functions
discover an error, providing information closest to the point at which
the error has happened. If a core is caused by memory corruption, we
have more information about memory allocations.  This is better for
troubleshooting and determining where/which application overwrote a
memory address.

Settings 1 and 2 can be combined by setting MALLOC_CHECK_ to 3
(three).  This will enable the print out of warning messages on
standard error (1) and will call abort() when problems are noticed.

Title: MALLOC_CHECK_ for linux daemons

Body:
Can we use MALLOC_CHECK_ for linux daemon processes?

Basically I want to examine an another process(a C program) which runs as daemon and is crashing when my application(a C program) is using it(other process).
The crash is as follows:

#0  0xffffe430 in __kernel_vsyscall ()
#1  0xf7426e30 in raise () from /lib/libc.so.6
#2  0xf7428765 in abort () from /lib/libc.so.6
#3  0xf7465d75 in __libc_message () from /lib/libc.so.6
#4  0xf746bd04 in malloc_printerr () from /lib/libc.so.6
#5  0xf746d613 in _int_free () from /lib/libc.so.6
#6  0xf747074d in free () from /lib/libc.so.6
#7  0xf6043a61 in BufferFree (memblk=0xf1f82f90) at ../allocator/alloclib.c:447

Is there any other way to debug other then valgrind?

Body:
How to enable MALLOC_CHECK_

The below article explains the usage of MALLOC_CHECK_

MALLOC_CHECK_ can be used in the script from where you are triggering your daemons. Below export in the script will enable malloc check for all the daemons which are triggered using the script.

export MALLOC_CHECK_=X, Where X can be 0,1 or 3

If MALLOC_CHECK_ is set to 0 (zero), the memory management functions
are simply most tolerant of errors and do not give warnings. Maybe be
useful if we are prevented from finding one memory bug by another that
is not convenient to fix at the moment; it might allow us to use other
tools to chase down the other memory bug. It may also be useful if you
are running code that works on another system but not on Linux.  It
can provide a quick workaround that may allow the code to temporarily
function before you have the chance to resolve the error.

If MALLOC_CHECK_ is set to 1 (one), the memory management functions
print out warning messages on standard error when problems are
noticed. It is useful if we are not aware of any problems and just
wants to be notified if any problem exists.

If MALLOC_CHECK_ is set to 2 (two), the memory management functions
call abort()when problems are noticed. This is most useful from inside
the debugger or a shell starting an application or daemon.  It allows
a backtrace to be obtained as soon as the memory management functions
discover an error, providing information closest to the point at which
the error has happened. If a core is caused by memory corruption, we
have more information about memory allocations.  This is better for
troubleshooting and determining where/which application overwrote a
memory address.

Settings 1 and 2 can be combined by setting MALLOC_CHECK_ to 3
(three).  This will enable the print out of warning messages on
standard error (1) and will call abort() when problems are noticed.


问:
standard_init_linux.go:178: exec user process caused "exec format error" kubernetes
I know this issue has been encountered by many people, but none of the given answers resolved my issue.

Workflow

I run all my dockers in a kubernetes cluster (google cloud).

I've setup the compilation_trigger to auto build my dockerfile when I commit in my master branch on github.

Then I update my kubernetes deployment with kubectl set image deployment/MYPROJECT MYPROJECT=eu.gcr.io/foo/MYPROJECT:$TRAVIS_COMMIT

Whats wrong ?

My pod stays in crashloop back-off and in the logs I read: standard_init_linux.go:178: exec user process caused "exec format error"

A bit of context

My workflow used to work untill the begining of June 2018, I don't understand what's wrong so Ive searched on the internet, modified my dockerfile, updated my dependencies, changed the dockerfile base image version, etc... Nothing works

Dockerfile

```<code>FROM golang:1.10-alpine3.7 AS builder
ADD . /go/src/github.com/foo/MYPROJECT
WORKDIR /go/src/github.com/foo/MYPROJECT/api
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -a -installsuffix cgo -o /go/bin/api

FROM alpine:3.7
RUN apk --no-cache add ca-certificates
COPY --from=builder /go/bin/api /go/bin/api
COPY --from=builder /go/src/github.com/foo/MYPROJECT/api/sql /go/migrations/sql
COPY --from=builder /go/src/github.com/foo/MYPROJECT/api/.docs/swagger.yml /static/swagger.yml
RUN chmod +x /go/bin/api
ENTRYPOINT ["/go/bin/api"]
</code>```

[EDIT: 12 June]

I noticed the docker image size went from 6.3 Mo to 2.3 Mo when the problem started. I suspect an update from alpine, I continue to investigate.

答: Although not the solution to this question, another cause may be if your command is a script without shebang.</p>

Body:
I know this issue has been encountered by many people, but none of the given answers resolved my issue.

Workflow

I run all my dockers in a kubernetes cluster (google cloud).

I've setup the compilation_trigger to auto build my dockerfile when I commit in my master branch on github.

Then I update my kubernetes deployment with kubectl set image deployment/MYPROJECT MYPROJECT=eu.gcr.io/foo/MYPROJECT:$TRAVIS_COMMIT

Whats wrong ?

My pod stays in crashloop back-off and in the logs I read: standard_init_linux.go:178: exec user process caused "exec format error"

A bit of context

My workflow used to work untill the begining of June 2018, I don't understand what's wrong so Ive searched on the internet, modified my dockerfile, updated my dependencies, changed the dockerfile base image version, etc... Nothing works

Dockerfile

FROM golang:1.10-alpine3.7 AS builder
ADD . /go/src/github.com/foo/MYPROJECT
WORKDIR /go/src/github.com/foo/MYPROJECT/api
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -a -installsuffix cgo -o /go/bin/api

FROM alpine:3.7
RUN apk --no-cache add ca-certificates
COPY --from=builder /go/bin/api /go/bin/api
COPY --from=builder /go/src/github.com/foo/MYPROJECT/api/sql /go/migrations/sql
COPY --from=builder /go/src/github.com/foo/MYPROJECT/api/.docs/swagger.yml /static/swagger.yml
RUN chmod +x /go/bin/api
ENTRYPOINT ["/go/bin/api"]

[EDIT: 12 June]

I noticed the docker image size went from 6.3 Mo to 2.3 Mo when the problem started. I suspect an update from alpine, I continue to investigate.


问:
configure: error: libpq is not installed or libpq is old
I'm trying to install pgpool-II in Ubuntu 13.10 environment. I'm following this tutorial to get it done.

I get below error.

configure: error: libpq is not installed or libpq is old

From the docs.

Note: pgpool-II requires libpq library in PostgreSQL 7.4 or later
  (version 3 protocol). If configure script displays the following error
  message, libpq library may not be installed, or it is not of version
  3.

configure: error: libpq is not installed or libpq is old

If the library is version 3, but above message is still displayed,
  your libpq library is probably not recognized by configure script.

configure script searches for libpq library under /usr/local/pgsql
  libaray. If you have installed PostgreSQL to a directory other than
  /usr/local/pgsql, use --with-pgsql, or --with-pgsql-includedir and
  --with-pgsql-libdir command line options when you execute configure.

I'm using below command to fix it as instructed but it does not work.

```<code>./configure --with-pgsql-includedir /usr/lib/
</code>```

I also followed this from Database Administrators Stack Exchange too.

How can I fix this?

答:
I find the main reason, it is because we lack of some information.
   if the postgresql was installed with YUM. confirm that the /usr/pgsql-[version]/lib/ /usr/pgsql-[version]/include/ /usr/pgsql-[version]/bin/ are exists in your server

yum install postgresql10-server postgresql10-devel postgresql10-libs
  -y

then

./configure --prefix=/opt/pgpool-II/ --with-pgsql=/usr/pgsql-10/bin/
  --with-pgsql-includedir=/usr/pgsql-10/include --with-pgsql-libdir=/usr/pgsql-10/lib

Body:
I'm trying to install pgpool-II in Ubuntu 13.10 environment. I'm following this tutorial to get it done.

I get below error.

configure: error: libpq is not installed or libpq is old

From the docs.

Note: pgpool-II requires libpq library in PostgreSQL 7.4 or later
  (version 3 protocol). If configure script displays the following error
  message, libpq library may not be installed, or it is not of version
  3.

configure: error: libpq is not installed or libpq is old

If the library is version 3, but above message is still displayed,
  your libpq library is probably not recognized by configure script.

configure script searches for libpq library under /usr/local/pgsql
  libaray. If you have installed PostgreSQL to a directory other than
  /usr/local/pgsql, use --with-pgsql, or --with-pgsql-includedir and
  --with-pgsql-libdir command line options when you execute configure.

I'm using below command to fix it as instructed but it does not work.

./configure --with-pgsql-includedir /usr/lib/

I also followed this from Database Administrators Stack Exchange too.

How can I fix this?