问:
Can we define a "function declaration" also as a "function statement"?
This question born considering the function declarations VS function expressions.

We clearly know that a function declaration have this form

```<code>function foo() {
    var a = 3;
    console.log( a );
}
</code>```

while a function expression can have this form (appearing like what is known like Immediately invoked function expression)

```<code>(function foo() {
    var a = 3;
    console.log( a );
})()
</code>```

Looking at the immediately invoked function expression I can just notice the first function (the one used in the function declaration) wrapped in parethesis.

Now, the point is: I know that the grouping operator (most commonly known as "the parethesis" () ) can only contain an expression. If this is true I can't say that the function declaration is also a function statement (because it would be like saying that I have wrapped in parenthesis a statement...).

So, can you give some help, I'm a little confused.
A function declaration is also a function statement? If yes, the function wrapped in parenthesis is a statement or what?

I must clarify that I'm not asking about the difference beetwen a function declaration and a function expression. If I mention them and their differences is just to describe my question that is: a "function declaration" is also a "function statement"?

答:
In expression hoisting will not happened, but in function statement hoisting is occurred.

In function statement, You can write function definition anywhere in js file before or after function call. JIT compiler will hoisting at top of programming file.

For function expression, JIT compiler will not do as same as function statement, which reads where its occurred. If you try to access function before its defined it will show type error.

IIFE is pattern mostly used to avoid access variable outside function.

callMe();  // Function statement

function callMe(){

return console.log("I am function statement");
}

// callMe2();  // TypeError if you call before expression defined.

var callMe2 = function(){
  return console.log("I am function expression");
};

callMe2(); //Function expression call

(function(){
return console.log("I am IIFE");
}());```

Body:
This question born considering the function declarations VS function expressions.

We clearly know that a function declaration have this form

function foo() {
    var a = 3;
    console.log( a );
}

while a function expression can have this form (appearing like what is known like Immediately invoked function expression)

(function foo() {
    var a = 3;
    console.log( a );
})()

Looking at the immediately invoked function expression I can just notice the first function (the one used in the function declaration) wrapped in parethesis.

Now, the point is: I know that the grouping operator (most commonly known as "the parethesis" () ) can only contain an expression. If this is true I can't say that the function declaration is also a function statement (because it would be like saying that I have wrapped in parenthesis a statement...).

So, can you give some help, I'm a little confused.
A function declaration is also a function statement? If yes, the function wrapped in parenthesis is a statement or what?

I must clarify that I'm not asking about the difference beetwen a function declaration and a function expression. If I mention them and their differences is just to describe my question that is: a "function declaration" is also a "function statement"?


来源: stackexchange

问:
Spring Boot 2.0 disable default security
I want to use Spring Security for JWT authentication. But it comes with default authentication. I am trying to disable it, but the old approach of doing this - disabling it through application.properties - is deprecated in 2.0.

This is what I tried:

```<code>@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}
</code>```

How can I simply disable basic security?

UPDATE

It might be nice to know that I am not using web mvc but web flux.

Screenshot:

答:
According to the reference documentation, the Security configuration for allowing all requests with WebFlux should look like this:</p>

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange().anyExchange().permitAll();
        return http.build();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use Spring Security for JWT authentication. But it comes with default authentication. I am trying to disable it, but the old approach of doing this - disabling it through application.properties - is deprecated in 2.0.

This is what I tried:

@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}

How can I simply disable basic security?

UPDATE

It might be nice to know that I am not using web mvc but web flux.

Screenshot:

Body:
According to the reference documentation, the Security configuration for allowing all requests with WebFlux should look like this:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange().anyExchange().permitAll();
        return http.build();
    }
}

ContentLicense: CC BY-SA 3.0


问:
Puppet: Error: SSL_read:: shutdown while in init
We are running Puppet master and agents version: 3.5.1

The puppet master is on RHEL 6.9 with OpenSSL 1.0.1e-fips 11 Feb 2013

And puppet agents WERE on Amazon Linux with OpenSSL 1.0.1k-fips 8 Jan 2015

After a yum update, the agents now have: OpenSSL 1.0.2k-fips 26 Jan 2017

After which, we've now started seeing the following puppet error:

```<code>...
Info: Applying configuration version 1508328365
Notice: /Stage[main]/Someservice/Somemodule::Instance[someservice]/File[/usr/local/somemodule/someservice.jar]/content:
Binary files /usr/local/somemodule/someservice.jar and /tmp/puppet-file20171018-31408-194p0ni-0 differ
Error: SSL_read:: shutdown while in init
Error: /Stage[main]/Someservice/Somemodule::Instance[someservice]/File[/usr/local/somemodule/someservice.jar]/content: change from {md5}500bd479fe3d5b6c06f7912c9326ea8d to {md5}e85ee20d004783e85b0820b07d3537a9 failed: SSL_read:: shutdown while in init
...
</code>```

At first I thought of upgrading the version of openssl on the server, but it would seem that the above is the latest for Redhat Enterprise 6.9.

This error only occurs when binary files differ (i.e. puppet needs to update jars or zip files).

I can only get things to work again, when we run a yum downgrade to the previous patch level on the client.

Anyone else seen this or have any other ideas?

答: In the end we just ended up upgrading the affected puppet agents to the latest one available in the Amazon AWS yum repo (3.7.4). Luckily not many code changes were required in our manifests.</p>

Body:
We are running Puppet master and agents version: 3.5.1

The puppet master is on RHEL 6.9 with OpenSSL 1.0.1e-fips 11 Feb 2013

And puppet agents WERE on Amazon Linux with OpenSSL 1.0.1k-fips 8 Jan 2015

After a yum update, the agents now have: OpenSSL 1.0.2k-fips 26 Jan 2017

After which, we've now started seeing the following puppet error:

...
Info: Applying configuration version 1508328365
Notice: /Stage[main]/Someservice/Somemodule::Instance[someservice]/File[/usr/local/somemodule/someservice.jar]/content:
Binary files /usr/local/somemodule/someservice.jar and /tmp/puppet-file20171018-31408-194p0ni-0 differ
Error: SSL_read:: shutdown while in init
Error: /Stage[main]/Someservice/Somemodule::Instance[someservice]/File[/usr/local/somemodule/someservice.jar]/content: change from {md5}500bd479fe3d5b6c06f7912c9326ea8d to {md5}e85ee20d004783e85b0820b07d3537a9 failed: SSL_read:: shutdown while in init
...

At first I thought of upgrading the version of openssl on the server, but it would seem that the above is the latest for Redhat Enterprise 6.9.

This error only occurs when binary files differ (i.e. puppet needs to update jars or zip files).

I can only get things to work again, when we run a yum downgrade to the previous patch level on the client.

Anyone else seen this or have any other ideas?


问:
Error on car's license plate regex validation
I'm running the following test to validate a car's license plate. What am I doing wrong?

testInvalid return error

testValid return success

```<code>@Test
fun testInvalid() {
 val value = "ABC12345"
 val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}")
 val matcher = pattern.matcher(value)

 val found = matcher.find()

 System.out.print("$value is valid: $found")
 Assert.assertFalse(found)
}

@Test
fun testValid() {
 val value = "ABC1234"
 val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}")
 val matcher = pattern.matcher(value)

 val found = matcher.find()

 System.out.print("$value is valid: $found")
 Assert.assertTrue(found)
}
</code>```

答:
You need to use the $ character at the end of regEx to indicate the end:</p>

```<code>@Test
fun testInvalid() {
    val value = "ABC12345"
    val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}$")
    val matcher = pattern.matcher(value)

    val found = matcher.find()

    System.out.print("$value is valid: $found")
    Assert.assertFalse(found)
}
@Test
fun testValid() {
    val value = "ABC1234"
    val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}$")
    val matcher = pattern.matcher(value)

    val found = matcher.find()

    System.out.print("$value is valid: $found")
    Assert.assertTrue(found)
}
</code>```

Body:
I'm running the following test to validate a car's license plate. What am I doing wrong?

testInvalid return error

testValid return success

@Test
fun testInvalid() {
 val value = "ABC12345"
 val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}")
 val matcher = pattern.matcher(value)

 val found = matcher.find()

 System.out.print("$value is valid: $found")
 Assert.assertFalse(found)
}

@Test
fun testValid() {
 val value = "ABC1234"
 val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}")
 val matcher = pattern.matcher(value)

 val found = matcher.find()

 System.out.print("$value is valid: $found")
 Assert.assertTrue(found)
}

Body:
You need to use the $ character at the end of regEx to indicate the end:

@Test
fun testInvalid() {
    val value = "ABC12345"
    val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}$")
    val matcher = pattern.matcher(value)

    val found = matcher.find()

    System.out.print("$value is valid: $found")
    Assert.assertFalse(found)
}
@Test
fun testValid() {
    val value = "ABC1234"
    val pattern = Pattern.compile("[A-Z]{3}[0-9]{4}$")
    val matcher = pattern.matcher(value)

    val found = matcher.find()

    System.out.print("$value is valid: $found")
    Assert.assertTrue(found)
}


问:
Add cordova plugin from GitLab private repo
```<code>cordova plugin add http://gitlab.com/<user>/<private-repo>.git
</code>```

I am unable to add a cordova plugin from a private repo in GitLab. When I run the above command it throws me the following error:

```<code>Error: Failed to fetch plugin http://gitlab.com/<user>/<private-repo>.git via registry.
    Probably this is either a connection problem, or plugin spec is incorrect.
    Check your connection and plugin name/version/URL.
    Error: npm: Command failed with exit code 1 Error output:
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 401
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 401
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm ERR! Darwin 16.7.0
    npm ERR! argv "~/.nvm/versions/node/v6.4.0/bin/node"
    "~/.nvm/versions/node/v6.4.0/bin/npm" "install"
    "http://gitlab.com/<user>/<private-repo>.git" "--save"
    npm ERR! node v6.4.0
    npm ERR! npm  v3.10.3

    npm ERR! fetch failed with status code 401
    npm ERR!
    npm ERR! If you need help, you may report this error at:
    npm ERR!     <https://github.com/npm/npm/issues>

    npm ERR! Please include the following file with any support request:
</code>```

Note: I am using cordova 7.0.1

I can see that status code is 401. I was accepting a password prompt for fetching from the private repo but unfortunately thats not the case.
similar question was asked but I don't want to clone the repo and add via local folder. Any kind of help will be appreciated. Thanks :)

答:
you need to no-fetch this plugin. So, you need to run that command:

```<code>sudo cordova plugin add http://gitlab.com/<user>/<private-repo>.git --save --nofetch
</code>```

Regards

Body:
cordova plugin add http://gitlab.com/<user>/<private-repo>.git

I am unable to add a cordova plugin from a private repo in GitLab. When I run the above command it throws me the following error:

Error: Failed to fetch plugin http://gitlab.com/<user>/<private-repo>.git via registry.
    Probably this is either a connection problem, or plugin spec is incorrect.
    Check your connection and plugin name/version/URL.
    Error: npm: Command failed with exit code 1 Error output:
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 401
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 401
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm ERR! Darwin 16.7.0
    npm ERR! argv "~/.nvm/versions/node/v6.4.0/bin/node"
    "~/.nvm/versions/node/v6.4.0/bin/npm" "install"
    "http://gitlab.com/<user>/<private-repo>.git" "--save"
    npm ERR! node v6.4.0
    npm ERR! npm  v3.10.3

    npm ERR! fetch failed with status code 401
    npm ERR!
    npm ERR! If you need help, you may report this error at:
    npm ERR!     <https://github.com/npm/npm/issues>

    npm ERR! Please include the following file with any support request:

Note: I am using cordova 7.0.1

I can see that status code is 401. I was accepting a password prompt for fetching from the private repo but unfortunately thats not the case.
similar question was asked but I don't want to clone the repo and add via local folder. Any kind of help will be appreciated. Thanks :)

Body:
you need to no-fetch this plugin. So, you need to run that command:

sudo cordova plugin add http://gitlab.com/<user>/<private-repo>.git --save --nofetch

Regards


问:
FBNativeAdsManager nextNativeAd() is crashing if first cell
Code is crashing in the following line if the cell is first </p>

```<code>let nativeAdd = nativeAdsManager.nextNativeAd() as FBNativeAd?
</code>```

<p>I guess the ads are not ready yet or something. But is should not crash!!! I try putting it in do-try-catch but it didn't help. </p>

```<code>func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        if (self.shouldShowAd(indexPath))
        {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(AdCell), forIndexPath: indexPath) as! AdCell

            let nativeAdd = nativeAdsManager.nextNativeAd() as FBNativeAd?

            if (nativeAdd != nil)
            {
                cell.setDetails(nativeAdd!)
                return cell
            }
            else
            {
                return self.createRegularCell(collectionView, cellForItemAtIndexPath: indexPath)
            }
        }
        else
        {
            return self.createRegularCell(collectionView, cellForItemAtIndexPath: indexPath)
        }
    }
</code>```

答:
I have similar issue and seldom crash when click the ad (which is in 5th cell in my app, using FBAudienceNetwork iOS SDK 4.26.0 with CocoaPods)

Fatal Exception: NSInvalidArgumentException
-[FullScreenCatalogViewController nativeAdDidClick:]: unrecognized selector sent to instance 0x161ff12d0

```<code>Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x185dabd38 __exceptionPreprocess
1  libobjc.A.dylib                0x1852c0528 objc_exception_throw
2  CoreFoundation                 0x185db91f8 __methodDescriptionForSelector
3  UIKit                          0x18f573cc4 -[UIResponder doesNotRecognizeSelector:]
4  CoreFoundation                 0x185db13f0 ___forwarding___
5  CoreFoundation                 0x185c970dc _CF_forwarding_prep_0
6  Black Friday                   0x100f446e0 __33-[FBMediaView loadMultiProductAd]_block_invoke_2 (FBMediaView.m:447)
7  Black Friday                   0x100f5f9f0 -[FBAdCommandProcessor callCompletionHandlerForCommand:withAdAction:] (FBAdCommandProcessor.m:296)
8  Black Friday                   0x100f5f938 -[FBAdCommandProcessor launchURLOutOfApp:withAdAction:] (FBAdCommandProcessor.m:283)
9  Black Friday                   0x100f5ec84 -[FBAdCommandProcessor launchAppForEngagement:] (FBAdCommandProcessor.m:164)
10 Black Friday                   0x100f5ea2c -[FBAdCommandProcessor processCommand:withExtraData:adDataModel:completionHandler:] (FBAdCommandProcessor.m:142)
11 Black Friday                   0x100f444d0 __33-[FBMediaView loadMultiProductAd]_block_invoke.218 (FBMediaView.m:439)
12 Black Friday                   0x100f84540 -[FBAdMultiProductView multiProductCellClicked:withPosition:inRect:] (FBAdMultiProductView.m:115)
13 Black Friday                   0x100f83b28 -[FBAdMultiProductCell dispatchClickedWithPosition:inRect:] (FBAdMultiProductCell.m:151)
14 Black Friday                   0x100f839f0 -[FBAdMultiProductCell gestureRecognizerTappedCell:] (FBAdMultiProductCell.m:129)
15 UIKit                          0x18f848f78 -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:]
16 UIKit                          0x18f84d4dc _UIGestureRecognizerSendTargetActions
17 UIKit                          0x18f337dc8 _UIGestureRecognizerSendActions
18 UIKit                          0x18f1ec748 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:]
19 UIKit                          0x18f8373fc _UIGestureEnvironmentUpdate
20 UIKit                          0x18f836f88 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:]
21 UIKit                          0x18f8360e4 -[UIGestureEnvironment _updateGesturesForEvent:window:]
22 UIKit                          0x18f1eaa54 -[UIWindow sendEvent:]
23 UIKit                          0x18f1bc078 -[UIApplication sendEvent:]
24 UIKit                          0x18fafbf98 __dispatchPreprocessedEventFromEventQueue
25 UIKit                          0x18fafe408 __handleEventQueueInternal
26 UIKit                          0x18faf7574 __handleHIDEventFetcherDrain
27 CoreFoundation                 0x185d54358 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
28 CoreFoundation                 0x185d542d8 __CFRunLoopDoSource0
29 CoreFoundation                 0x185d53b60 __CFRunLoopDoSources0
30 CoreFoundation                 0x185d51738 __CFRunLoopRun
31 CoreFoundation                 0x185c722d8 CFRunLoopRunSpecific
32 GraphicsServices               0x187b03f84 GSEventRunModal
33 UIKit                          0x18f21f880 UIApplicationMain
34 Black Friday                   0x100e7649c main (main.m:15)
35 libdyld.dylib                  0x18579656c start
</code>```

Body:
Code is crashing in the following line if the cell is first

let nativeAdd = nativeAdsManager.nextNativeAd() as FBNativeAd?

I guess the ads are not ready yet or something. But is should not crash!!! I try putting it in do-try-catch but it didn't help.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        if (self.shouldShowAd(indexPath))
        {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(AdCell), forIndexPath: indexPath) as! AdCell

            let nativeAdd = nativeAdsManager.nextNativeAd() as FBNativeAd?

            if (nativeAdd != nil)
            {
                cell.setDetails(nativeAdd!)
                return cell
            }
            else
            {
                return self.createRegularCell(collectionView, cellForItemAtIndexPath: indexPath)
            }
        }
        else
        {
            return self.createRegularCell(collectionView, cellForItemAtIndexPath: indexPath)
        }
    }

Body:
I have similar issue and seldom crash when click the ad (which is in 5th cell in my app, using FBAudienceNetwork iOS SDK 4.26.0 with CocoaPods)

Fatal Exception: NSInvalidArgumentException
-[FullScreenCatalogViewController nativeAdDidClick:]: unrecognized selector sent to instance 0x161ff12d0

Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x185dabd38 __exceptionPreprocess
1  libobjc.A.dylib                0x1852c0528 objc_exception_throw
2  CoreFoundation                 0x185db91f8 __methodDescriptionForSelector
3  UIKit                          0x18f573cc4 -[UIResponder doesNotRecognizeSelector:]
4  CoreFoundation                 0x185db13f0 ___forwarding___
5  CoreFoundation                 0x185c970dc _CF_forwarding_prep_0
6  Black Friday                   0x100f446e0 __33-[FBMediaView loadMultiProductAd]_block_invoke_2 (FBMediaView.m:447)
7  Black Friday                   0x100f5f9f0 -[FBAdCommandProcessor callCompletionHandlerForCommand:withAdAction:] (FBAdCommandProcessor.m:296)
8  Black Friday                   0x100f5f938 -[FBAdCommandProcessor launchURLOutOfApp:withAdAction:] (FBAdCommandProcessor.m:283)
9  Black Friday                   0x100f5ec84 -[FBAdCommandProcessor launchAppForEngagement:] (FBAdCommandProcessor.m:164)
10 Black Friday                   0x100f5ea2c -[FBAdCommandProcessor processCommand:withExtraData:adDataModel:completionHandler:] (FBAdCommandProcessor.m:142)
11 Black Friday                   0x100f444d0 __33-[FBMediaView loadMultiProductAd]_block_invoke.218 (FBMediaView.m:439)
12 Black Friday                   0x100f84540 -[FBAdMultiProductView multiProductCellClicked:withPosition:inRect:] (FBAdMultiProductView.m:115)
13 Black Friday                   0x100f83b28 -[FBAdMultiProductCell dispatchClickedWithPosition:inRect:] (FBAdMultiProductCell.m:151)
14 Black Friday                   0x100f839f0 -[FBAdMultiProductCell gestureRecognizerTappedCell:] (FBAdMultiProductCell.m:129)
15 UIKit                          0x18f848f78 -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:]
16 UIKit                          0x18f84d4dc _UIGestureRecognizerSendTargetActions
17 UIKit                          0x18f337dc8 _UIGestureRecognizerSendActions
18 UIKit                          0x18f1ec748 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:]
19 UIKit                          0x18f8373fc _UIGestureEnvironmentUpdate
20 UIKit                          0x18f836f88 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:]
21 UIKit                          0x18f8360e4 -[UIGestureEnvironment _updateGesturesForEvent:window:]
22 UIKit                          0x18f1eaa54 -[UIWindow sendEvent:]
23 UIKit                          0x18f1bc078 -[UIApplication sendEvent:]
24 UIKit                          0x18fafbf98 __dispatchPreprocessedEventFromEventQueue
25 UIKit                          0x18fafe408 __handleEventQueueInternal
26 UIKit                          0x18faf7574 __handleHIDEventFetcherDrain
27 CoreFoundation                 0x185d54358 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
28 CoreFoundation                 0x185d542d8 __CFRunLoopDoSource0
29 CoreFoundation                 0x185d53b60 __CFRunLoopDoSources0
30 CoreFoundation                 0x185d51738 __CFRunLoopRun
31 CoreFoundation                 0x185c722d8 CFRunLoopRunSpecific
32 GraphicsServices               0x187b03f84 GSEventRunModal
33 UIKit                          0x18f21f880 UIApplicationMain
34 Black Friday                   0x100e7649c main (main.m:15)
35 libdyld.dylib                  0x18579656c start


问:
How to make a div's background color translucent?
I only want the background color of white in my div to be translucent roughly 50%.  The content should be fully opaque.  What's the proper way to do this?  I imagined when I looked up the background CSS property, I'd find an opacity setting, but didn't.  Don't care about IE6.

UPDATE: solving with the rgba solution given below in conjunction with CSS3PIE's solution for getting rgba to work in IE browsers.

答:
You can use the background-color: rgba() notation:

```<code>#theIdofYourElement,
.classOfElements {
    background-color: #fff;
    background-color: rgba(255,255,255,0.5);
}
</code>```

Edited to add the default background-color (for browsers that don't understand the rgba() notation). Albeit I was under the impression that all but IE do understand it (but I could be wrong, and haven't tested to be sure...).

Edit with thanks to @akamike.

Edited to address question from OP (in comments):

which browsers don't understand rgba? will they all in the future, is this part of css3?

The best information I could find is the CSS Tricks' rgba() browser support table, with a link to a demo and 'more complete' compatibility table.

Body:
You can use the background-color: rgba() notation:

#theIdofYourElement,
.classOfElements {
    background-color: #fff;
    background-color: rgba(255,255,255,0.5);
}

Edited to add the default background-color (for browsers that don't understand the rgba() notation). Albeit I was under the impression that all but IE do understand it (but I could be wrong, and haven't tested to be sure...).

Edit with thanks to @akamike.

Edited to address question from OP (in comments):

which browsers don't understand rgba? will they all in the future, is this part of css3?

The best information I could find is the CSS Tricks' rgba() browser support table, with a link to a demo and 'more complete' compatibility table.

ContentLicense: CC BY-SA 2.5


问:
SpeechToTextV1 - Missing required modules SSCZLib, SSCommonCrypto
I am working on XCode 9.1 project that uses IBM Watson swift-sdk SpeechToTextV1 package. After upgrading swift-sdk to the version 0.19.0 and building XCode project the compiler error has occured: Missing required modules: 'SSCZLib', 'SSCommonCrypto' pointing to the import SpeechToTextV1 statement. swift-sdk updated via Carthage.
Cartfile content: github "watson-developer-cloud/swift-sdk".
command line update: carthage update --platform ios --no-use-binaries.

How can I include SSCZLib and SSCommonCrypto modules into XCode project?

Please help. Thanks a lot.

答: Use carthage update --platform iOS --no-use-binaries. It takes a while, but it works.


问:
Image.fromarray just produces black image
I'm trying to save a numpy matrix as a grayscale image using Image.fromarray. It seems to work on a random matrix, but not on a particular one (where there should appear a circle). Can anyone explain what I'm doing wrong?

```<code>from PIL import Image
import numpy as np
radius = 0.5
size = 10
x,y = np.meshgrid(np.linspace(-1,1,size),np.linspace(-1,1,size))
f = np.vectorize(lambda x,y: ( 1.0 if x*x + y*y < radius*radius else 0.0))
z = f(x,y)
print(z)
zz = np.random.random((size,size))
img = Image.fromarray(zz,mode='L') #replace z with zz and it will just produce a black image
img.save('my_pic.png')
</code>```

答:
Image.fromarray is poorly defined with floating-point input; it's not well documented but the function assumes the input is laid-out as unsigned 8-bit integers.

To produce the output you're trying to get, multiply by 255 and convert to uint8:

```<code>z = (z * 255).astype(np.uint8)
</code>```

The reason it seems to work with the random array is that the bytes in this array, when interpreted as unsigned 8-bit integers, also look random. But the output is not the same random array as the input, which you can check by doing the above conversion on the random input:

```<code>np.random.seed(0)
zz = np.random.rand(size, size)
Image.fromarray(zz, mode='L').save('pic1.png')
</code>```

```<code>Image.fromarray((zz * 255).astype('uint8'), mode='L').save('pic2.png')
</code>```

Since the issue doesn't seem to be reported anywhere, I reported it on github: https://github.com/python-pillow/Pillow/issues/2856

Body:
I'm trying to save a numpy matrix as a grayscale image using Image.fromarray. It seems to work on a random matrix, but not on a particular one (where there should appear a circle). Can anyone explain what I'm doing wrong?

from PIL import Image
import numpy as np
radius = 0.5
size = 10
x,y = np.meshgrid(np.linspace(-1,1,size),np.linspace(-1,1,size))
f = np.vectorize(lambda x,y: ( 1.0 if x*x + y*y < radius*radius else 0.0))
z = f(x,y)
print(z)
zz = np.random.random((size,size))
img = Image.fromarray(zz,mode='L') #replace z with zz and it will just produce a black image
img.save('my_pic.png')

Body:
Image.fromarray is poorly defined with floating-point input; it's not well documented but the function assumes the input is laid-out as unsigned 8-bit integers.

To produce the output you're trying to get, multiply by 255 and convert to uint8:

z = (z * 255).astype(np.uint8)

The reason it seems to work with the random array is that the bytes in this array, when interpreted as unsigned 8-bit integers, also look random. But the output is not the same random array as the input, which you can check by doing the above conversion on the random input:

np.random.seed(0)
zz = np.random.rand(size, size)
Image.fromarray(zz, mode='L').save('pic1.png')

Image.fromarray((zz * 255).astype('uint8'), mode='L').save('pic2.png')

Since the issue doesn't seem to be reported anywhere, I reported it on github: https://github.com/python-pillow/Pillow/issues/2856


问:
Regex matching multiple negative lookaheads
I'm trying to match a string (using a Perl regex) only if it doesn't start with "abc:" or "defg:", but I can't seem to find out how. I've tried something like</p>
```<code>^(?:(?!abc:)|(?!defg:))
</code>```

答:
Lookahead (?=foo), (?!foo) and lookbehind (?<=foo), (?<!foo) do not consume any characters.

You can do multiple assertions:

```<code>^(?!abc:)(?!defg:)
</code>```

or:

```<code>^(?!defg:)(?!abc:)
</code>```

...and the order does not make a difference.

You can use De Morgan (as other answers do):

```<code>(NOT A) AND (NOT B) <=> NOT (A OR B)
</code>```

...and shorten the expression to:

```<code>^(?!abc:|defg:)
</code>```

Body:
I'm trying to match a string (using a Perl regex) only if it doesn't start with "abc:" or "defg:", but I can't seem to find out how. I've tried something like

^(?:(?!abc:)|(?!defg:))

Body:
Lookahead (?=foo), (?!foo) and lookbehind (?<=foo), (?<!foo) do not consume any characters.

You can do multiple assertions:

^(?!abc:)(?!defg:)

or:

^(?!defg:)(?!abc:)

...and the order does not make a difference.

You can use De Morgan (as other answers do):

(NOT A) AND (NOT B) <=> NOT (A OR B)

...and shorten the expression to:

^(?!abc:|defg:)


问:
DynamoDB Design Pattern
I'm currently trying to design a database pattern to store data that needs the ability to scale on demand. I'm looking at DynamoDB to complete this task. I'm not familiar with the no-sql design pattern and am having some trouble with going about the design. My data set, is to be tied to a camera system that tracks people entering and exiting a room.

My current design plan is to have a table that has the device id for the particular camera as the primary key. Every 5 minutes, the camera will send the total number into the room, the total out of the room, the group id (to track a room as a whole where there are multiple entrances/exits), and a timestamp.

My issue is that, DynamoDB seems to only want one entry for a given primary key. Whenever I want to make a new addition, It wants to overwrite my data.

I was thinking that a design such as the following may work:

```<code>DeviceID: ID
{
    GroupID: ID,
    Entries: [
        {
            In: numIN,
            Out: numOUT,
            TimeStamp: time
        },
        // appending on each entry to the list
    ]
}
</code>```

Am I using DynamoDB inefficiently? Is there a better way to go about this? It seems like making queries, such as "how many people were in room x on day y?" would be difficult.

答:
Is it inefficient?

No. Your not using it inefficiently. DynamoDB is good at storing and retrieving groups of hierarchical data for a single element per request. Nesting/denormalizing your data so a singled device has an array of entries is definitely recommended by AWS since you can't do joins (An entries table and devices table) as you've designed for correctly in my opinion. https://aws.amazon.com/blogs/database/should-your-dynamodb-table-be-normalized-or-denormalized/ A drawback is you have to pull every entry for the single device and append but given you make updates every 5 mins this would seem tolerable. On a small app with low user traffic I do the same thing appending to the users list of info then putting the user back. DynamoDB is very cheap per request so if you don't have millions of requests this is worth it in my opinion.

How do I run more complex Queries?

With DynamoDB you lose query flexibility in return for it being 100% managed and cheap per-request in some instances...For more complex queries you can add Global Secondary indexes so you can run queries that involve columns other than the primary key for that table. They have their own drawback too though; you still only get 2 properties per index, a where clause of 2 columns essentially and each GS index gets its own provisioned throughput, so you pay an additional flat rate for the new index. For me the Global secondary index doesn't really help when the data you want to query against is denormalized similar to how your nesting your entries. In your case you wouldn't be able to apply the in, out, timestamp fields to a Global Secondary index because the "Entries" column is a document type. There are however other NoSQL databases that you could dump your entire device JSON object into and they would index even the nested fields...

Another Database for Complex Queries

I myself did not want to use another database because I thought I could get away with DynamoDB being my primary or only datastore but if you need to ask "Give me x where A=1 AND B=2 AND C=3" its really not possible. Trying to denormalize your data while also making it query friendly I have found to be difficult. So instead I use DynamoDB to store items and to retrieve items and AWS Elasticsearch Service to run queries across those items. So in your case I would store devices with their nested entries in both DynamoDB and elasticsearch. When I need to retrieve an individual device or entry or pull anything by Id it would come from DynamoDB. When I want to run analysis across any property then I use elasticsearch.

Title: DynamoDB Design Pattern

Body:
I'm currently trying to design a database pattern to store data that needs the ability to scale on demand. I'm looking at DynamoDB to complete this task. I'm not familiar with the no-sql design pattern and am having some trouble with going about the design. My data set, is to be tied to a camera system that tracks people entering and exiting a room.

My current design plan is to have a table that has the device id for the particular camera as the primary key. Every 5 minutes, the camera will send the total number into the room, the total out of the room, the group id (to track a room as a whole where there are multiple entrances/exits), and a timestamp.

My issue is that, DynamoDB seems to only want one entry for a given primary key. Whenever I want to make a new addition, It wants to overwrite my data.

I was thinking that a design such as the following may work:

DeviceID: ID
{
    GroupID: ID,
    Entries: [
        {
            In: numIN,
            Out: numOUT,
            TimeStamp: time
        },
        // appending on each entry to the list
    ]
}

Am I using DynamoDB inefficiently? Is there a better way to go about this? It seems like making queries, such as "how many people were in room x on day y?" would be difficult.


问:
jQuery attach same event to many id
My question is: How to attach the same series of events to many id's

in this case I'm attaching all of this code to "#employeeBox"

```<code>$("#employeeBox").autocomplete({
                                source: function (request, response) {
                                    $.ajax({
                                        url: '<%:ResolveUrl("~/Lookup/SearchEnterpriseUsers")%>',
                                        dataType: "json",
                                        data: {
                                            featureClass: "P",
                                            style: "full",
                                            maxRows: 12,
                                            nameLike: request.term
                                        },
                                        success: function (data) {
                                            response($.map(data, function (item) {
                                                return {
                                                    label: item.FullName,
                                                    value: item.EmployeeId
                                                }
                                            }))
                                        }
                                    })
                                },
                                minLength: 2,
                                select: function (event, ui) {
                                    alert(ui.item.value)
                                },
                                open: function () {
                                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                                },
                                close: function () {
                                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                                }
                            });
</code>```

What if I want to attach it to many id's.

Like

```<code>for (int i=0; i < count; i++)
"#employee_" + i + "_Box"
</code>```

what's the best way to do this without a lot of repeated code?

thanks!

答:
if you can, just add a class to all your elements and attach the event to that class instead of to a bunch of ids.</p>

```<code>$('.myClass').live('myevent', function(e) { //some function });
</code>```

Title: jQuery attach same event to many id

Body:
My question is: How to attach the same series of events to many id's

in this case I'm attaching all of this code to "#employeeBox"

$("#employeeBox").autocomplete({
                                source: function (request, response) {
                                    $.ajax({
                                        url: '<%:ResolveUrl("~/Lookup/SearchEnterpriseUsers")%>',
                                        dataType: "json",
                                        data: {
                                            featureClass: "P",
                                            style: "full",
                                            maxRows: 12,
                                            nameLike: request.term
                                        },
                                        success: function (data) {
                                            response($.map(data, function (item) {
                                                return {
                                                    label: item.FullName,
                                                    value: item.EmployeeId
                                                }
                                            }))
                                        }
                                    })
                                },
                                minLength: 2,
                                select: function (event, ui) {
                                    alert(ui.item.value)
                                },
                                open: function () {
                                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                                },
                                close: function () {
                                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                                }
                            });

What if I want to attach it to many id's.

Like

for (int i=0; i < count; i++)
"#employee_" + i + "_Box"

what's the best way to do this without a lot of repeated code?

thanks!

Body:
if you can, just add a class to all your elements and attach the event to that class instead of to a bunch of ids.

$('.myClass').live('myevent', function(e) { //some function });


问:
Gracefully restarting explorer.exe as of Windows 10 1709, Fall Creators Update aka Redstone 3
For the current version of Windows 10, 1703, the Creators Update, I have this little C# app getting called to restart explorer.exe during an installation sequence. This is to help refresh the taskbar/registry entries, so that one of the virtual peripherals will appear on the taskbar after installation without rebooting.

```<code>using System;
using System.Diagnostics;

namespace RestartExplorer
{
    class Program
    {
        static int Main(string[] args)
        {
            var process = Process.GetProcessesByName("explorer")[0];
            process.Kill();
            Process.Start("explorer");
            return 0;
        }
    }
}
</code>```

This was working fine in Redstone 2, but in the current Insiders Preview Windows 10 1709 Redstone 3 build of 16294.1.170916-2023, it doesn't just kill the explorer shell, it kills all the open file explorer windows too. That's super invasive, and if I had a couple dozen windows open while working when that happened, I don't think I'd be very happy about the UX.

I verified that CTRL+SHIFTRight-Click on the Taskbar for Exit Explorer also shows the same diverging behavior, not just my little app.

So, if I want to make sure my users' windows aren't all lost, how should I now be restarting explorer, or better yet, is there an even better way to get the end-result for what I'm looking to do?

答:
Use the restart manager API to close all open explorers. It will restart any that were closed.  Only downside is that restarted apps will be activated so you have to code around your app losing focus.

See https://msdn.microsoft.com/en-us/library/windows/desktop/aa373649(v=vs.85).aspx

```<code>var sessionKey = Guid.NewGuid().ToString();
NativeMethods.RmStartSession(out IntPtr session, 0, sessionKey).CheckError();
try
{
    NativeMethods.RmRegisterResources(session, 1, new[] { Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe") }, 0, null, 0, null).CheckError();
    NativeMethods.RmShutdown(session, 0, null).CheckError();
    NativeMethods.RmRestart(session, 0, null).CheckError();
}
finally
{
    NativeMethods.RmEndSession(session);
}
</code>```

You will also need the following NativeMethods

```<code>public static class NativeMethods
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public com.FILETIME ProcessStartTime;
    }

    [Flags]
    internal enum RM_SHUTDOWN_TYPE : uint
    {
        RmForceShutdown = 0x1,
        RmShutdownOnlyRegistered = 0x10
    }

    internal delegate void RM_WRITE_STATUS_CALLBACK(UInt32 nPercentComplete);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    internal static extern int RmStartSession(out IntPtr pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    internal static extern int RmEndSession(IntPtr pSessionHandle);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    internal static extern int RmRegisterResources(IntPtr pSessionHandle, UInt32 nFiles, string[] rgsFilenames, UInt32 nApplications, RM_UNIQUE_PROCESS[] rgApplications, UInt32 nServices, string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll")]
    internal static extern int RmShutdown(IntPtr pSessionHandle, RM_SHUTDOWN_TYPE lActionFlags, RM_WRITE_STATUS_CALLBACK fnStatus);

    [DllImport("rstrtmgr.dll")]
    internal static extern int RmRestart(IntPtr pSessionHandle, int dwRestartFlags, RM_WRITE_STATUS_CALLBACK fnStatus);

    [DllImport("kernel32.dll")]
    internal static extern bool GetProcessTimes(IntPtr hProcess, out com.FILETIME lpCreationTime, out com.FILETIME lpExitTime, out com.FILETIME lpKernelTime, out com.FILETIME lpUserTime);
}
</code>```

Body:
For the current version of Windows 10, 1703, the Creators Update, I have this little C# app getting called to restart explorer.exe during an installation sequence. This is to help refresh the taskbar/registry entries, so that one of the virtual peripherals will appear on the taskbar after installation without rebooting.

using System;
using System.Diagnostics;

namespace RestartExplorer
{
    class Program
    {
        static int Main(string[] args)
        {
            var process = Process.GetProcessesByName("explorer")[0];
            process.Kill();
            Process.Start("explorer");
            return 0;
        }
    }
}

This was working fine in Redstone 2, but in the current Insiders Preview Windows 10 1709 Redstone 3 build of 16294.1.170916-2023, it doesn't just kill the explorer shell, it kills all the open file explorer windows too. That's super invasive, and if I had a couple dozen windows open while working when that happened, I don't think I'd be very happy about the UX.

I verified that CTRL+SHIFTRight-Click on the Taskbar for Exit Explorer also shows the same diverging behavior, not just my little app.

So, if I want to make sure my users' windows aren't all lost, how should I now be restarting explorer, or better yet, is there an even better way to get the end-result for what I'm looking to do?

Body:
Use the restart manager API to close all open explorers. It will restart any that were closed.  Only downside is that restarted apps will be activated so you have to code around your app losing focus.

See https://msdn.microsoft.com/en-us/library/windows/desktop/aa373649(v=vs.85).aspx

var sessionKey = Guid.NewGuid().ToString();
NativeMethods.RmStartSession(out IntPtr session, 0, sessionKey).CheckError();
try
{
    NativeMethods.RmRegisterResources(session, 1, new[] { Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe") }, 0, null, 0, null).CheckError();
    NativeMethods.RmShutdown(session, 0, null).CheckError();
    NativeMethods.RmRestart(session, 0, null).CheckError();
}
finally
{
    NativeMethods.RmEndSession(session);
}

You will also need the following NativeMethods

public static class NativeMethods
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public com.FILETIME ProcessStartTime;
    }

    [Flags]
    internal enum RM_SHUTDOWN_TYPE : uint
    {
        RmForceShutdown = 0x1,
        RmShutdownOnlyRegistered = 0x10
    }

    internal delegate void RM_WRITE_STATUS_CALLBACK(UInt32 nPercentComplete);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    internal static extern int RmStartSession(out IntPtr pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    internal static extern int RmEndSession(IntPtr pSessionHandle);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    internal static extern int RmRegisterResources(IntPtr pSessionHandle, UInt32 nFiles, string[] rgsFilenames, UInt32 nApplications, RM_UNIQUE_PROCESS[] rgApplications, UInt32 nServices, string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll")]
    internal static extern int RmShutdown(IntPtr pSessionHandle, RM_SHUTDOWN_TYPE lActionFlags, RM_WRITE_STATUS_CALLBACK fnStatus);

    [DllImport("rstrtmgr.dll")]
    internal static extern int RmRestart(IntPtr pSessionHandle, int dwRestartFlags, RM_WRITE_STATUS_CALLBACK fnStatus);

    [DllImport("kernel32.dll")]
    internal static extern bool GetProcessTimes(IntPtr hProcess, out com.FILETIME lpCreationTime, out com.FILETIME lpExitTime, out com.FILETIME lpKernelTime, out com.FILETIME lpUserTime);
}


问:
How do I close a command prompt after opening it?
I want to open a command prompt and then close it, it opens the command prompt but it doesn't close it, the error I get is:

FileNotFoundError: [WinError 2] The system cannot find the file
  specified

```<code>import sys
import random
import subprocess
import os

def x():
    subprocess.call('start',shell=True)
    os.system('taskkill /fi r"C:\Windows\system32\cmd.exe"')
    #subprocess.run("exit")

x()
</code>```

答:
Maybe this SO question might help.
I believe it is better practice to get the process ID, and call an exit or kill on that PID rather than calling it on the application itself.

Body:
I want to open a command prompt and then close it, it opens the command prompt but it doesn't close it, the error I get is:

FileNotFoundError: [WinError 2] The system cannot find the file
  specified

import sys
import random
import subprocess
import os

def x():
    subprocess.call('start',shell=True)
    os.system('taskkill /fi r"C:\Windows\system32\cmd.exe"')
    #subprocess.run("exit")

x()


问:
System.Action and non-static variables
This is probably a duplicate, but I cannot find any threads which explain this behavior. At least not pertaining to Action (which are basically Func's with no return type). It's to do with static references.

Look at these two examples. I'm merely trying to subscribe to the System.Action OnButton1Down, to make it call a non-static function when the Action is invoked with .Invoke().

Why does the first method work, but not the second or third ones? I would much rather have the Action saved/prepared, so I can also unsubscribe it again without trickery, by simply doing: OnButton1Down -=

```<code>System.Action OnButton1Down;

void MyNonStaticFunction() { }

// This example works
void MyFirstFunction()
{
    OnButton1Down += () => { MyNonStaticFunction(); };
}

// This example gives the following error on "MyNonStaticFunction()":
// "A field initializer cannot reference the non-static field, method
// or property MyNonStaticFunction()."
System.Action MyAction = () => { MyNonStaticFunction(); };

void MySecondStartFunction()
{
    OnButton1Down += MyAction;
}

// This example is to show what happens, if I just try to subscribe the raw
// method to the Action, as suggested in the comments.
// It gives the following error on "MyNonStaticFunction()":
// "Cannot implicitly convert type 'void' to type 'System.Action'."
void MyThirdStartFunction()
{
    OnButton1Down += MyNonStaticFunction();
}
</code>```

I sort of understand that the errors make sense, but I don't see why the first example is OK. I would much rather be able to do either of the other examples.

答:
The compiler doesn't allow you to access any instance members before the object is fully constructed (i.e. all field initializers have run).

To get around this you can initialize MyAction in the class constructor, which will run after all the field initializers.

Edit: To reply to the second part of your question:

```<code>OnButton1Down += MyNonStaticFunction();
</code>```

You're calling MyNonStaticFunction, not converting it to a delegate! Remove the () and it'll work better!

Title: System.Action and non-static variables

Body:
This is probably a duplicate, but I cannot find any threads which explain this behavior. At least not pertaining to Action (which are basically Func's with no return type). It's to do with static references.

Look at these two examples. I'm merely trying to subscribe to the System.Action OnButton1Down, to make it call a non-static function when the Action is invoked with .Invoke().

Why does the first method work, but not the second or third ones? I would much rather have the Action saved/prepared, so I can also unsubscribe it again without trickery, by simply doing: OnButton1Down -=

System.Action OnButton1Down;

void MyNonStaticFunction() { }

// This example works
void MyFirstFunction()
{
    OnButton1Down += () => { MyNonStaticFunction(); };
}

// This example gives the following error on "MyNonStaticFunction()":
// "A field initializer cannot reference the non-static field, method
// or property MyNonStaticFunction()."
System.Action MyAction = () => { MyNonStaticFunction(); };

void MySecondStartFunction()
{
    OnButton1Down += MyAction;
}

// This example is to show what happens, if I just try to subscribe the raw
// method to the Action, as suggested in the comments.
// It gives the following error on "MyNonStaticFunction()":
// "Cannot implicitly convert type 'void' to type 'System.Action'."
void MyThirdStartFunction()
{
    OnButton1Down += MyNonStaticFunction();
}

I sort of understand that the errors make sense, but I don't see why the first example is OK. I would much rather be able to do either of the other examples.

Body:
The compiler doesn't allow you to access any instance members before the object is fully constructed (i.e. all field initializers have run).

To get around this you can initialize MyAction in the class constructor, which will run after all the field initializers.

Edit: To reply to the second part of your question:

OnButton1Down += MyNonStaticFunction();

You're calling MyNonStaticFunction, not converting it to a delegate! Remove the () and it'll work better!


问:
how to add Facebook's pixel into Google's AMP?
For the time being, it appears that no one at Facebook nor Google have added Facebook tracking pixel into amp-analytics yet.

Does anybody here knows how to do it ? sample code or github is preferred.

thank you very much

答:
It seems support was added on June 6, 2017. You can do:

```<code><!-- Facebook Pixel Analytics tracking -->
<amp-analytics type="facebookpixel" id="facebook-pixel">
    <script type="application/json">
    {
        "vars": {
            "pixelId": "YOUR_ID"
        },
        "triggers": {
            "trackPageview": {
                "on": "visible",
                "request": "pageview"
            }
        }
    }
    </script>
</amp-analytics>
<!-- End Facebook Pixel Analytics example -->
</code>```

The documentation can be found here.

Body:
It seems support was added on June 6, 2017. You can do:

<!-- Facebook Pixel Analytics tracking -->
<amp-analytics type="facebookpixel" id="facebook-pixel">
    <script type="application/json">
    {
        "vars": {
            "pixelId": "YOUR_ID"
        },
        "triggers": {
            "trackPageview": {
                "on": "visible",
                "request": "pageview"
            }
        }
    }
    </script>
</amp-analytics>
<!-- End Facebook Pixel Analytics example -->

The documentation can be found here.


问:
Value types inherit from System.Object...why?

Possible Duplicates:

  Is everything in .NET an object?

  How do ValueTypes derive from Object (ReferenceType) and still be ValueTypes?

Hi,
I just do not get it. System.Object is (I think) reference type but all data types in .NET inherit from it. Also value types do as well. I do not understand it - value type has its value on the stack but its inherited from Object?
Hope anyone could help me to understand

答:
Ask yourself why you think it's strange that a type that is typically allocated on the stack would inherit from System.Object and I think you'll find you can't formulate a good reason.

If you think it's because an object's type defines where it is allocated, you're mistaken. What member of ValueType is responsible for defining its allocation mechanism? (What member of System.Object, for that matter?)

Type inheritance in .NET is supposed to comprise "is a" relationships: a string is an object, for example. Everything in the .NET world is an object, so an int is an object, a double is an object, etc.

You can think of this in terms of the Liskov substitution principle: if I write code that expects an object, I should be capable of dealing with any type that is an object—i.e., anything at all. My code should be equally comfortable with a string, an int, a List<int>, etc.

Also note that object guarantees certain members that all types have as a consequence of this: GetType, ToString, and GetHashCode.


问:
Golden Gate replication from primary to secondary database, WARNING OGG-01154 Oracle GoldenGate Delivery for Oracle, rgg1ab.prm: SQL error 1403
I am using golden gate to replicate data from primary to secondary. I have inserted records in the primary database, but replication abdends with error message

WARNING OGG-01154  Oracle GoldenGate Delivery for Oracle, rgg1ab.prm:  SQL error 1403 mapping primaryDB_GG1.TB_myTableName to secondaryDB.TB_myTableName OCI Error ORA-01403: no data found, SQL < UPDATE ......

The update statement has all the columns from table in the where clause.
Whereas there is no such update statement in the application with so many columns in where clause.

Can you help on this issue. Why Golden Gate replication is converting insert in to update while replication.

答:
For replication, you might have already enabled the transaction log in the source db. Now, you need to run from ggsci:

"ADD TRANDATA schema_name.table_name, COLS(...)"

In the COLS part, you need to mention the Column/Columns(comma seperated) that can be used to identify a unique record (You can mention the unique indexed columns if present). If there is no unique index on the table and you are not sure of what columns could be used to uniquely identify a row, then just run from ggsci:

"ADD TRANDATA schema_name.table_name"

Then Golden gate will start logging all the necessary columns for uniquely identifying a row.
Note: This should be done before you start the replication process.


问:
Azure virtual network hybrid connection
I've got an Azure Virtual Network setup and a VM setup within the network. I've installed the Hybrid Connection Manager app on the VM.

I also have an Azure App Service and I've created a hybrid connection between it and the VM and they are both claiming they are happily connected to each other.

Also on the VM I've installed an app that is listening on http://localhost:1234

Can someone tell me what IP I use from my app service to talk to http://localhost:1234 on the VM? e.g. Is it [VM internal IP]:1234 or [VM public IP]:1234, or something else. Nothing is talking at the moment so I want to make sure the IP address is not the problem.

答:
Just use the computer name of the VM. For example, call to SQLSRV009:1234 from your code in App Service. The Hybrid Connection definition in the portal should reflect the same name (same as computer name, same as what you're calling from your code).

Check out this well written guide for the full picture —
https://learn.microsoft.com/en-us/azure/biztalk-services/integration-hybrid-connection-create-manage

It is possible to set a Hybrid Connection endpoint to an IP address. If you use an IP address, you may or may not reach the on-premises resource, depending on your client.

The Hybrid Connection depends on the client doing a DNS lookup. In most cases, the client is your application code. If the client does not perform a DNS lookup, (it does not try to resolve the IP address as if it were a domain name (x.x.x.x)), then traffic is not sent through the Hybrid Connection.

For example (pseudocode), you define 10.4.5.6 as your on-premises host:
  The following scenario works:

  Application code -> GetHostByName("10.4.5.6") -> Resolves to 127.0.0.3 -> Connect("127.0.0.3") -> Hybrid Connection -> on-prem host

The following scenario doesn't work:

  Application code -> Connect("10.4.5.6") -> ?? -> No route to host

Also make your app listen on either 0.0.0.0 or the private IP since i'm not terribly sure localhost will work with HC.

Why not use VNET integration for the Web App? All you need to do is create a route based (IKEv2) VPN gateway in the VNET, like so —
https://learn.microsoft.com/en-us/azure/app-service/web-sites-integrate-with-vnet

Title: Azure virtual network hybrid connection


问:
Substitute multiple spaces with character during SELECT
I have some field values that contain 5 spaces as a separator e.g.

AWERDC     123

I do a weekly extract that ends up being submitted to an outside party, but any of these particular values need to have a '#' substituted (AWERDC#123).  I am looking for the best way to do the transform during the SELECT.

What can I do?

答:
You can try with a simple Replace in your query.   </p>

```<code>SELECT REPLACE([Column], '     ','#') From [dbo.Table]
</code>```

Body:
You can try with a simple Replace in your query.

SELECT REPLACE([Column], '     ','#') From [dbo.Table]


问:
Airflow: Log file isn't local, Unsupported remote log location
I am not able see the logs attached to the tasks from the Airflow UI:

Log related settings in airflow.cfg file are:

remote_base_log_folder =

base_log_folder = /home/my_projects/ksaprice_project/airflow/logs

worker_log_server_port = 8793

child_process_log_directory =
/home/my_projects/ksaprice_project/airflow/logs/scheduler

Although I am setting remote_base_log_folter it is trying to fetch the log from http://:8793/log/tutorial/print_date/2017-08-02T00:00:00 - I don't understand this behavior. According to the settings the workers should store the logs at /home/my_projects/ksaprice_project/airflow/logs and they should be fetched from the same location instead of remote.

Update
task_instance table content:

答:
As you can see in the image-1 there is a timestamp , make sure in your logs you have the folder/file with that timestamp as name ..

You are looking at UI, so first make sure you have log files created in the directory, in my case my log folder looks like

```<code>(AIRFLOW-ENV) [cloudera@quickstart dags]$ ll /home/cloudera/workspace/python/airflow_home/logs/my_test_dag/my_sensor_task
total 8
-rw-rw-rw- 1 cloudera cloudera 3215 Nov 14 08:45 2017-11-12T12:00:00
-rw-rw-rw- 1 cloudera cloudera 2694 Nov 14 08:45 2017-11-14T08:36:06.920727
(AIRFLOW-ENV) [cloudera@quickstart dags]$
</code>```

So my log URL is

```<code>http://localhost:8080/admin/airflow/log?task_id=my_sensor_task&dag_id=my_test_dag&execution_date=2017-11-14T08:36:06.920727
</code>```

When you go to your DAG, and select the GRAPH-VIEW, you can see a dropdown next to "RUN", select the appropriate run, and then in the graph-view below , select the appropriate task/operator and select view-log

Body:
As you can see in the image-1 there is a timestamp , make sure in your logs you have the folder/file with that timestamp as name ..

You are looking at UI, so first make sure you have log files created in the directory, in my case my log folder looks like

(AIRFLOW-ENV) [cloudera@quickstart dags]$ ll /home/cloudera/workspace/python/airflow_home/logs/my_test_dag/my_sensor_task
total 8
-rw-rw-rw- 1 cloudera cloudera 3215 Nov 14 08:45 2017-11-12T12:00:00
-rw-rw-rw- 1 cloudera cloudera 2694 Nov 14 08:45 2017-11-14T08:36:06.920727
(AIRFLOW-ENV) [cloudera@quickstart dags]$

So my log URL is

http://localhost:8080/admin/airflow/log?task_id=my_sensor_task&dag_id=my_test_dag&execution_date=2017-11-14T08:36:06.920727

When you go to your DAG, and select the GRAPH-VIEW, you can see a dropdown next to "RUN", select the appropriate run, and then in the graph-view below , select the appropriate task/operator and select view-log


问:
Ios 11.2 beta universal links open my app and safari
On previous versions of the OS my universal links have been functioning correctly. In the iOS 11.2 beta when I click on a link that is defined in my Associated Domains, and whose path is defined in the apple-app-site-association file, my app opens. However, immediately after displaying my launch screen, safari also opens and my app is put in the background. Any explanation or possible solutions would be greatly appreciated.</p>

答: It was a bug with the beta. iOS 11.2 beta 3 solved the issue</p>


答:
Easiest way is to create a semi-transparent PNG and just use that as your background image for the div.

If you're using Photoshop (or similar tools) just create a 10px by 10px image that is all white -- then drag the opacity slider down to 50%. Save it as a PNG and you should be rockin'!

Using RGBA is also a possibility, but you're not just losing IE6 then -- there are still quite a few people using browsers that don't support the alpha scheme.

Title: How to make a div's background color translucent?

Body:
I only want the background color of white in my div to be translucent roughly 50%.  The content should be fully opaque.  What's the proper way to do this?  I imagined when I looked up the background CSS property, I'd find an opacity setting, but didn't.  Don't care about IE6.

UPDATE: solving with the rgba solution given below in conjunction with CSS3PIE's solution for getting rgba to work in IE browsers.


问:
"Please try running this command again as Root/Administrator" error when trying to install LESS
I'm trying to install LESS on my machine and have installed node already. However, when I enter "node install -g less" I get the following error and am not sure what to do?</p>

```<code>FPaulMAC:bin paul$ npm install -g less
npm ERR! Error: EACCES, unlink '/usr/local/lib/node_modules/less'
npm ERR!  { [Error: EACCES, unlink '/usr/local/lib/node_modules/less']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/less' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 13.3.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "less"
npm ERR! cwd /usr/local/bin
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! path /usr/local/lib/node_modules/less
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, unlink '/usr/local/lib/node_modules/less'
npm ERR! error rolling back Error: EACCES, unlink '/usr/local/lib/node_modules/less'
npm ERR! error rolling back  { [Error: EACCES, unlink '/usr/local/lib/node_modules/less']
npm ERR! error rolling back   errno: 3,
npm ERR! error rolling back   code: 'EACCES',
npm ERR! error rolling back   path: '/usr/local/lib/node_modules/less' }
npm ERR! not ok code 0
</code>```

答: I kept having this problem because windows was setting my node_modules folder to Readonly.  Make sure you uncheck this.

Body:
I'm trying to install LESS on my machine and have installed node already. However, when I enter "node install -g less" I get the following error and am not sure what to do?

FPaulMAC:bin paul$ npm install -g less
npm ERR! Error: EACCES, unlink '/usr/local/lib/node_modules/less'
npm ERR!  { [Error: EACCES, unlink '/usr/local/lib/node_modules/less']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/less' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 13.3.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "less"
npm ERR! cwd /usr/local/bin
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! path /usr/local/lib/node_modules/less
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, unlink '/usr/local/lib/node_modules/less'
npm ERR! error rolling back Error: EACCES, unlink '/usr/local/lib/node_modules/less'
npm ERR! error rolling back  { [Error: EACCES, unlink '/usr/local/lib/node_modules/less']
npm ERR! error rolling back   errno: 3,
npm ERR! error rolling back   code: 'EACCES',
npm ERR! error rolling back   path: '/usr/local/lib/node_modules/less' }
npm ERR! not ok code 0


问:
jQuery DataTables - Force the Empty Table message after AJAX Call
I have a jquery-datatables set up, and using a custom search filter that functions as the standard keyword filter and a custom Item ID search which uses an ajax call to ping the back end and return a value, if any and then use that value to search the table in a specific column.

```<code>$.ajax({
  url: 'the_url_to_lookup_itemID',
  data: {
    'engravingId': search(search is the value from the input field assigned to this variable)
  },
  dataType: 'jsonp',
  success: function(data) {
    console.log(data.assetId);
    var assetId = data.assetId;
    if (assetId != 0) {
      searchResults.columns(2).search(assetId).draw();
    } else {
      searchResults.search(assetId).draw();
    }
  }
});
</code>```

If the assetId equals "0" then the search just assumes its a keyword, since there is no record of the assetId existing. But instead of clearing out the table records and showing no results, there is no change.  I'm assuming because "0" isn't enough for the filter to operate, so how can I force it? I want the user to see some result, "No matching records found" or something like that.

How can I force my jquery-datatables to display "No matching records found" after this custom search has failed to produce any results?

I am NOT looking for a custom message when there are no results. I am just looking for a way to force the display of this "No matching records found" when I execute my Ajax call and that function generates no results.

答:
One way to force to display "No matching records found" message is by using the clear() and draw() methods.

If you need to change in runtime the message, you could use datatables.context[0].oLanguage.sEmptyTable attribute.

In your case is:

```<code>searchResults.context[0].oLanguage.sEmptyTable = "No matching records found...";
searchResults.clear().draw();
</code>```

Something like this:

$(function() {
  var dataSet = [
    ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
    ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
    ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
    ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"],
    ["Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000"],
    ["Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500"],
    ["Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900"],
    ["Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500"],
    ["Sonya Frost", "Software Engineer", "Edinburgh", "1667", "2008/12/13", "$103,600"],
    ["Jena Gaines", "Office Manager", "London", "3814", "2008/12/19", "$90,560"],
    ["Quinn Flynn", "Support Lead", "Edinburgh", "9497", "2013/03/03", "$342,000"],
    ["Charde Marshall", "Regional Director", "San Francisco", "6741", "2008/10/16", "$470,600"],
    ["Haley Kennedy", "Senior Marketing Designer", "London", "3597", "2012/12/18", "$313,500"],
    ["Tatyana Fitzpatrick", "Regional Director", "London", "1965", "2010/03/17", "$385,750"],
    ["Michael Silva", "Marketing Designer", "London", "1581", "2012/11/27", "$198,500"],
    ["Paul Byrd", "Chief Financial Officer (CFO)", "New York", "3059", "2010/06/09", "$725,000"],
    ["Gloria Little", "Systems Administrator", "New York", "1721", "2009/04/10", "$237,500"],
    ["Bradley Greer", "Software Engineer", "London", "2558", "2012/10/13", "$132,000"],
    ["Dai Rios", "Personnel Lead", "Edinburgh", "2290", "2012/09/26", "$217,500"],
    ["Jenette Caldwell", "Development Lead", "New York", "1937", "2011/09/03", "$345,000"],
    ["Yuri Berry", "Chief Marketing Officer (CMO)", "New York", "6154", "2009/06/25", "$675,000"],
    ["Caesar Vance", "Pre-Sales Support", "New York", "8330", "2011/12/12", "$106,450"],
    ["Doris Wilder", "Sales Assistant", "Sidney", "3023", "2010/09/20", "$85,600"],
    ["Angelica Ramos", "Chief Executive Officer (CEO)", "London", "5797", "2009/10/09", "$1,200,000"],
    ["Gavin Joyce", "Developer", "Edinburgh", "8822", "2010/12/22", "$92,575"],
    ["Jennifer Chang", "Regional Director", "Singapore", "9239", "2010/11/14", "$357,650"],
    ["Brenden Wagner", "Software Engineer", "San Francisco", "1314", "2011/06/07", "$206,850"],
    ["Fiona Green", "Chief Operating Officer (COO)", "San Francisco", "2947", "2010/03/11", "$850,000"],
    ["Shou Itou", "Regional Marketing", "Tokyo", "8899", "2011/08/14", "$163,000"],
    ["Michelle House", "Integration Specialist", "Sidney", "2769", "2011/06/02", "$95,400"],
    ["Suki Burks", "Developer", "London", "6832", "2009/10/22", "$114,500"],
    ["Prescott Bartlett", "Technical Author", "London", "3606", "2011/05/07", "$145,000"],
    ["Gavin Cortez", "Team Leader", "San Francisco", "2860", "2008/10/26", "$235,500"],
    ["Martena Mccray", "Post-Sales support", "Edinburgh", "8240", "2011/03/09", "$324,050"],
    ["Unity Butler", "Marketing Designer", "San Francisco", "5384", "2009/12/09", "$85,675"]
  ];

  var columnDefs = [{
    title: "Name"
  }, {
    title: "Position"
  }, {
    title: "Office"
  }, {
    title: "Extn."
  }, {
    title: "Start date"
  }, {
    title: "Salary"
  }];

  var searchResults;

  searchResults = $('#example').DataTable({
    "sPaginationType": "full_numbers",
    data: dataSet,
    columns: columnDefs,
    dom: 'Bfrtip', // Needs button container
    select: 'single',
    responsive: true,
    buttons: []
  });

  // Setting the required behaviour to this question.
  document.getElementById("btnSetEmptyResults").onclick = function() {
    searchResults.context[0].oLanguage.sEmptyTable = "No matching records found...";
    searchResults.clear().draw();
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table.dataTable tbody>tr.selected,
table.dataTable tbody>tr>.selected {
  background-color: #A2D3F6;
}</code>```

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.0.2/css/responsive.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.1.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">

  <button id="btnSetEmptyResults" class="dt-button" type="button">
    Set empty results
  </button>

```
</div>
</div>
</p>

<p><strong>Update:</strong></p>

<p>If you need to print back all the data, you need to use the <code>rows.add(data)</code> method where the <code>data</code> parameter is the previous data that you used to print in the <code>datatable</code> plugin initially. Then use the <code>.draw()</code> method again to render the table:</p>

```searchResults.rows.add(assetId).draw();
```

<p><strong>In this demo:</strong> After 2 seconds will print back all the data in the table after the cleaning the <code>datatable</code>.</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>$(function() {
  var dataSet = [
    ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
    ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
    ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
    ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"],
    ["Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000"],
    ["Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500"],
    ["Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900"],
    ["Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500"],
    ["Sonya Frost", "Software Engineer", "Edinburgh", "1667", "2008/12/13", "$103,600"],
    ["Jena Gaines", "Office Manager", "London", "3814", "2008/12/19", "$90,560"],
    ["Quinn Flynn", "Support Lead", "Edinburgh", "9497", "2013/03/03", "$342,000"],
    ["Charde Marshall", "Regional Director", "San Francisco", "6741", "2008/10/16", "$470,600"],
    ["Haley Kennedy", "Senior Marketing Designer", "London", "3597", "2012/12/18", "$313,500"],
    ["Tatyana Fitzpatrick", "Regional Director", "London", "1965", "2010/03/17", "$385,750"],
    ["Michael Silva", "Marketing Designer", "London", "1581", "2012/11/27", "$198,500"],
    ["Paul Byrd", "Chief Financial Officer (CFO)", "New York", "3059", "2010/06/09", "$725,000"],
    ["Gloria Little", "Systems Administrator", "New York", "1721", "2009/04/10", "$237,500"],
    ["Bradley Greer", "Software Engineer", "London", "2558", "2012/10/13", "$132,000"],
    ["Dai Rios", "Personnel Lead", "Edinburgh", "2290", "2012/09/26", "$217,500"],
    ["Jenette Caldwell", "Development Lead", "New York", "1937", "2011/09/03", "$345,000"],
    ["Yuri Berry", "Chief Marketing Officer (CMO)", "New York", "6154", "2009/06/25", "$675,000"],
    ["Caesar Vance", "Pre-Sales Support", "New York", "8330", "2011/12/12", "$106,450"],
    ["Doris Wilder", "Sales Assistant", "Sidney", "3023", "2010/09/20", "$85,600"],
    ["Angelica Ramos", "Chief Executive Officer (CEO)", "London", "5797", "2009/10/09", "$1,200,000"],
    ["Gavin Joyce", "Developer", "Edinburgh", "8822", "2010/12/22", "$92,575"],
    ["Jennifer Chang", "Regional Director", "Singapore", "9239", "2010/11/14", "$357,650"],
    ["Brenden Wagner", "Software Engineer", "San Francisco", "1314", "2011/06/07", "$206,850"],
    ["Fiona Green", "Chief Operating Officer (COO)", "San Francisco", "2947", "2010/03/11", "$850,000"],
    ["Shou Itou", "Regional Marketing", "Tokyo", "8899", "2011/08/14", "$163,000"],
    ["Michelle House", "Integration Specialist", "Sidney", "2769", "2011/06/02", "$95,400"],
    ["Suki Burks", "Developer", "London", "6832", "2009/10/22", "$114,500"],
    ["Prescott Bartlett", "Technical Author", "London", "3606", "2011/05/07", "$145,000"],
    ["Gavin Cortez", "Team Leader", "San Francisco", "2860", "2008/10/26", "$235,500"],
    ["Martena Mccray", "Post-Sales support", "Edinburgh", "8240", "2011/03/09", "$324,050"],
    ["Unity Butler", "Marketing Designer", "San Francisco", "5384", "2009/12/09", "$85,675"]
  ];

  var columnDefs = [{
    title: "Name"
  }, {
    title: "Position"
  }, {
    title: "Office"
  }, {
    title: "Extn."
  }, {
    title: "Start date"
  }, {
    title: "Salary"
  }];

  var searchResults;

  searchResults = $('#example').DataTable({
    "sPaginationType": "full_numbers",
    data: dataSet,
    columns: columnDefs,
    dom: 'Bfrtip', // Needs button container
    select: 'single',
    responsive: true,
    buttons: []
  });

  // Setting the required behaviour to this question.
  document.getElementById("btnSetEmptyResults").onclick = function() {
    searchResults.context[0].oLanguage.sEmptyTable = "No matching records found...";
    searchResults.clear().draw();

    // Get back all the data after 2 seconds.
    setTimeout(function() {
      searchResults.rows.add(dataSet).draw();
    }, 2000);
  };
});</code>```

table.dataTable tbody>tr.selected,
table.dataTable tbody>tr>.selected {
  background-color: #A2D3F6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.0.2/css/responsive.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.1.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.0.2/js/dataTables.responsive.min.js"></script>
<div class="container">
  <button id="btnSetEmptyResults" class="dt-button" type="button">
    Set empty results
  </button>
  <table cellpadding="0" cellspacing="0" border="0" class="dataTable table table-striped" id="example">
  </table>
</div></code>```

Body:
I have a jquery-datatables set up, and using a custom search filter that functions as the standard keyword filter and a custom Item ID search which uses an ajax call to ping the back end and return a value, if any and then use that value to search the table in a specific column.

$.ajax({
  url: 'the_url_to_lookup_itemID',
  data: {
    'engravingId': search(search is the value from the input field assigned to this variable)
  },
  dataType: 'jsonp',
  success: function(data) {
    console.log(data.assetId);
    var assetId = data.assetId;
    if (assetId != 0) {
      searchResults.columns(2).search(assetId).draw();
    } else {
      searchResults.search(assetId).draw();
    }
  }
});

If the assetId equals "0" then the search just assumes its a keyword, since there is no record of the assetId existing. But instead of clearing out the table records and showing no results, there is no change.  I'm assuming because "0" isn't enough for the filter to operate, so how can I force it? I want the user to see some result, "No matching records found" or something like that.

How can I force my jquery-datatables to display "No matching records found" after this custom search has failed to produce any results?

I am NOT looking for a custom message when there are no results. I am just looking for a way to force the display of this "No matching records found" when I execute my Ajax call and that function generates no results.

Body:
One way to force to display "No matching records found" message is by using the clear() and draw() methods.

If you need to change in runtime the message, you could use datatables.context[0].oLanguage.sEmptyTable attribute.

In your case is:

searchResults.context[0].oLanguage.sEmptyTable = "No matching records found...";
searchResults.clear().draw();

Something like this:

$(function() {
  var dataSet = [
    ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
    ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
    ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
    ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"],
    ["Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000"],
    ["Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500"],
    ["Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900"],
    ["Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500"],
    ["Sonya Frost", "Software Engineer", "Edinburgh", "1667", "2008/12/13", "$103,600"],
    ["Jena Gaines", "Office Manager", "London", "3814", "2008/12/19", "$90,560"],
    ["Quinn Flynn", "Support Lead", "Edinburgh", "9497", "2013/03/03", "$342,000"],
    ["Charde Marshall", "Regional Director", "San Francisco", "6741", "2008/10/16", "$470,600"],
    ["Haley Kennedy", "Senior Marketing Designer", "London", "3597", "2012/12/18", "$313,500"],
    ["Tatyana Fitzpatrick", "Regional Director", "London", "1965", "2010/03/17", "$385,750"],
    ["Michael Silva", "Marketing Designer", "London", "1581", "2012/11/27", "$198,500"],
    ["Paul Byrd", "Chief Financial Officer (CFO)", "New York", "3059", "2010/06/09", "$725,000"],
    ["Gloria Little", "Systems Administrator", "New York", "1721", "2009/04/10", "$237,500"],
    ["Bradley Greer", "Software Engineer", "London", "2558", "2012/10/13", "$132,000"],
    ["Dai Rios", "Personnel Lead", "Edinburgh", "2290", "2012/09/26", "$217,500"],
    ["Jenette Caldwell", "Development Lead", "New York", "1937", "2011/09/03", "$345,000"],
    ["Yuri Berry", "Chief Marketing Officer (CMO)", "New York", "6154", "2009/06/25", "$675,000"],
    ["Caesar Vance", "Pre-Sales Support", "New York", "8330", "2011/12/12", "$106,450"],
    ["Doris Wilder", "Sales Assistant", "Sidney", "3023", "2010/09/20", "$85,600"],
    ["Angelica Ramos", "Chief Executive Officer (CEO)", "London", "5797", "2009/10/09", "$1,200,000"],
    ["Gavin Joyce", "Developer", "Edinburgh", "8822", "2010/12/22", "$92,575"],
    ["Jennifer Chang", "Regional Director", "Singapore", "9239", "2010/11/14", "$357,650"],
    ["Brenden Wagner", "Software Engineer", "San Francisco", "1314", "2011/06/07", "$206,850"],
    ["Fiona Green", "Chief Operating Officer (COO)", "San Francisco", "2947", "2010/03/11", "$850,000"],
    ["Shou Itou", "Regional Marketing", "Tokyo", "8899", "2011/08/14", "$163,000"],
    ["Michelle House", "Integration Specialist", "Sidney", "2769", "2011/06/02", "$95,400"],
    ["Suki Burks", "Developer", "London", "6832", "2009/10/22", "$114,500"],
    ["Prescott Bartlett", "Technical Author", "London", "3606", "2011/05/07", "$145,000"],
    ["Gavin Cortez", "Team Leader", "San Francisco", "2860", "2008/10/26", "$235,500"],
    ["Martena Mccray", "Post-Sales support", "Edinburgh", "8240", "2011/03/09", "$324,050"],
    ["Unity Butler", "Marketing Designer", "San Francisco", "5384", "2009/12/09", "$85,675"]
  ];

  var columnDefs = [{
    title: "Name"
  }, {
    title: "Position"
  }, {
    title: "Office"
  }, {
    title: "Extn."
  }, {
    title: "Start date"
  }, {
    title: "Salary"
  }];

  var searchResults;

  searchResults = $('#example').DataTable({
    "sPaginationType": "full_numbers",
    data: dataSet,
    columns: columnDefs,
    dom: 'Bfrtip', // Needs button container
    select: 'single',
    responsive: true,
    buttons: []
  });

  // Setting the required behaviour to this question.
  document.getElementById("btnSetEmptyResults").onclick = function() {
    searchResults.context[0].oLanguage.sEmptyTable = "No matching records found...";
    searchResults.clear().draw();
  };
});

table.dataTable tbody>tr.selected,
table.dataTable tbody>tr>.selected {
  background-color: #A2D3F6;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.0.2/css/responsive.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.1.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.0.2/js/dataTables.responsive.min.js"></script>
<div class="container">
  <button id="btnSetEmptyResults" class="dt-button" type="button">
    Set empty results
  </button>
  <table cellpadding="0" cellspacing="0" border="0" class="dataTable table table-striped" id="example">
  </table>
</div>

Update:

If you need to print back all the data, you need to use the rows.add(data) method where the data parameter is the previous data that you used to print in the datatable plugin initially. Then use the .draw() method again to render the table:

searchResults.rows.add(assetId).draw();

In this demo: After 2 seconds will print back all the data in the table after the cleaning the datatable.

$(function() {
  var dataSet = [
    ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
    ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
    ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
    ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"],
    ["Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000"],
    ["Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500"],
    ["Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900"],
    ["Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500"],
    ["Sonya Frost", "Software Engineer", "Edinburgh", "1667", "2008/12/13", "$103,600"],
    ["Jena Gaines", "Office Manager", "London", "3814", "2008/12/19", "$90,560"],
    ["Quinn Flynn", "Support Lead", "Edinburgh", "9497", "2013/03/03", "$342,000"],
    ["Charde Marshall", "Regional Director", "San Francisco", "6741", "2008/10/16", "$470,600"],
    ["Haley Kennedy", "Senior Marketing Designer", "London", "3597", "2012/12/18", "$313,500"],
    ["Tatyana Fitzpatrick", "Regional Director", "London", "1965", "2010/03/17", "$385,750"],
    ["Michael Silva", "Marketing Designer", "London", "1581", "2012/11/27", "$198,500"],
    ["Paul Byrd", "Chief Financial Officer (CFO)", "New York", "3059", "2010/06/09", "$725,000"],
    ["Gloria Little", "Systems Administrator", "New York", "1721", "2009/04/10", "$237,500"],
    ["Bradley Greer", "Software Engineer", "London", "2558", "2012/10/13", "$132,000"],
    ["Dai Rios", "Personnel Lead", "Edinburgh", "2290", "2012/09/26", "$217,500"],
    ["Jenette Caldwell", "Development Lead", "New York", "1937", "2011/09/03", "$345,000"],
    ["Yuri Berry", "Chief Marketing Officer (CMO)", "New York", "6154", "2009/06/25", "$675,000"],
    ["Caesar Vance", "Pre-Sales Support", "New York", "8330", "2011/12/12", "$106,450"],
    ["Doris Wilder", "Sales Assistant", "Sidney", "3023", "2010/09/20", "$85,600"],
    ["Angelica Ramos", "Chief Executive Officer (CEO)", "London", "5797", "2009/10/09", "$1,200,000"],
    ["Gavin Joyce", "Developer", "Edinburgh", "8822", "2010/12/22", "$92,575"],
    ["Jennifer Chang", "Regional Director", "Singapore", "9239", "2010/11/14", "$357,650"],
    ["Brenden Wagner", "Software Engineer", "San Francisco", "1314", "2011/06/07", "$206,850"],
    ["Fiona Green", "Chief Operating Officer (COO)", "San Francisco", "2947", "2010/03/11", "$850,000"],
    ["Shou Itou", "Regional Marketing", "Tokyo", "8899", "2011/08/14", "$163,000"],
    ["Michelle House", "Integration Specialist", "Sidney", "2769", "2011/06/02", "$95,400"],
    ["Suki Burks", "Developer", "London", "6832", "2009/10/22", "$114,500"],
    ["Prescott Bartlett", "Technical Author", "London", "3606", "2011/05/07", "$145,000"],
    ["Gavin Cortez", "Team Leader", "San Francisco", "2860", "2008/10/26", "$235,500"],
    ["Martena Mccray", "Post-Sales support", "Edinburgh", "8240", "2011/03/09", "$324,050"],
    ["Unity Butler", "Marketing Designer", "San Francisco", "5384", "2009/12/09", "$85,675"]
  ];

  var columnDefs = [{
    title: "Name"
  }, {
    title: "Position"
  }, {
    title: "Office"
  }, {
    title: "Extn."
  }, {
    title: "Start date"
  }, {
    title: "Salary"
  }];

  var searchResults;

  searchResults = $('#example').DataTable({
    "sPaginationType": "full_numbers",
    data: dataSet,
    columns: columnDefs,
    dom: 'Bfrtip', // Needs button container
    select: 'single',
    responsive: true,
    buttons: []
  });

  // Setting the required behaviour to this question.
  document.getElementById("btnSetEmptyResults").onclick = function() {
    searchResults.context[0].oLanguage.sEmptyTable = "No matching records found...";
    searchResults.clear().draw();

    // Get back all the data after 2 seconds.
    setTimeout(function() {
      searchResults.rows.add(dataSet).draw();
    }, 2000);
  };
});

table.dataTable tbody>tr.selected,
table.dataTable tbody>tr>.selected {
  background-color: #A2D3F6;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.0.2/css/responsive.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.1.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.1.2/css/select.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.1.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.0.2/js/dataTables.responsive.min.js"></script>
<div class="container">
  <button id="btnSetEmptyResults" class="dt-button" type="button">
    Set empty results
  </button>
  <table cellpadding="0" cellspacing="0" border="0" class="dataTable table table-striped" id="example">
  </table>
</div>