问:
ios 11 sms app param does not work
```<code><html>
<body>
  <a href="sms:+24321&body=This%20is%20the%20body">Click Me!</a>
</body>
</html>
</code>```

When you click the link above, iOS successfully opens the native iOS Messages application. If the user previously had the iOS Messages app open in the background on their phone, then iOS properly passes in the query parameters contained in the link, e.g. to: (24321) and body: (This is the body), but if the user does NOT already have iOS Messages open, then iOS opens Messages, but does NOT open a message w/ to and body filled out.

This is not an issue on iOS 10, it seems to have been introduced in iOS 11.

答:
It is clearly an iOS 11 bug.

The same bug there is with the openURL, with this code, without the if state, we have the same results:

```<code>NSString *sms = @"sms:+1234567890&body=This is sms body.";
NSString *url = [sms stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)
{
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
</code>```

With a double call it firstly open the message app and then pass the right parameters.

With a double call it works but it is a BAD workaround!

The same should happens with a web code.

I can only advise you to report a bug to Apple at this link.

This answer is not for the bounty, I just wanted to share with you my test. ;)

Title: ios 11 sms app param does not work

Body:
  Click Me!

When you click the link above, iOS successfully opens the native iOS Messages application. If the user previously had the iOS Messages app open in the background on their phone, then iOS properly passes in the query parameters contained in the link, e.g. to: (24321) and body: (This is the body), but if the user does NOT already have iOS Messages open, then iOS opens Messages, but does NOT open a message w/ to and body filled out.

This is not an issue on iOS 10, it seems to have been introduced in iOS 11.

Body:
It is clearly an iOS 11 bug.

The same bug there is with the openURL, with this code, without the if state, we have the same results:

NSString *sms = @"sms:+1234567890&body=This is sms body.";
NSString *url = [sms stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)
{
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

With a double call it firstly open the message app and then pass the right parameters.

With a double call it works but it is a BAD workaround!

The same should happens with a web code.

I can only advise you to report a bug to Apple at this link.

This answer is not for the bounty, I just wanted to share with you my test. ;)


来源: stackexchange

问:
Bootstrap 4 grid-only css, using bootstrap media queries in my scss style
I'm pretty much new to Bootstrap 4 and Sass\SCSS,I wanted to use the new grid and style the rest of my website on my own using SCSS, so I downloaded bootstrap source, compiled bootstrap-grid.scss (which is only the grid plus some variables and mixins), now the question that pops in my mind is : How do I use bootstrap's media queries screen sizes with my own style? Is there a particular mixin/way to call the breakpoints? Or since I'm using the grid only I have to configure media queries myself?

My idea was that there probably would be a mixin that allows me to do for example :

```<code>.my_class {
  color: red;
  +mobile {
  color: blue;
  }
}
</code>```

Does bootstrap have something like this? I have to do it on my own? How do you proceed when working with the grid only?

答: Yep. There's many Sass options in Bootstrap 4. You can read about them in the docs.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty much new to Bootstrap 4 and Sass\SCSS,I wanted to use the new grid and style the rest of my website on my own using SCSS, so I downloaded bootstrap source, compiled bootstrap-grid.scss (which is only the grid plus some variables and mixins), now the question that pops in my mind is : How do I use bootstrap's media queries screen sizes with my own style? Is there a particular mixin/way to call the breakpoints? Or since I'm using the grid only I have to configure media queries myself?

My idea was that there probably would be a mixin that allows me to do for example :

.my_class {
  color: red;
  +mobile {
  color: blue;
  }
}

Does bootstrap have something like this? I have to do it on my own? How do you proceed when working with the grid only?


问:
(node:19502) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'indexOf' of undefined
I have integrated cucumber with nightwatch.js.

My package.json looks like:-

```<code>{
  "name": "learning-nightwatch",
  "version": "1.0.0",
  "description": "learning nightwatch",
  "license": "UNLICENSED",
  "scripts": {
    "nightwatch": "nightwatch",
    "start": "bin/start",
    "stop": "bin/stop",
    "test": "bin/test"
  },
  "dependencies": {
    "lodash": "^4.17.4",
    "minimist": "^1.2.0",
    "nightwatch": "^0.9.16",
    "cucumber": "^3.1.0",
    "nightwatch-cucumber": "^8.2.9"
  }
}
</code>```

nigtwatch config:-

```<code>{
    "src_folders": [null],
    "output_folder": "reports",
    "custom_commands_path": "",
    "custom_assertions_path": "",
    "page_objects_path": "./pageObjects",
    "globals_path": "",
    "test_settings": {
        "default": {
            "launch_url": "http://localhost:8083",
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "screenshots": {
                "enabled": true,
                "on_failure": true,
                "on_error": true,
                "path": "./screenshots"
            },
            "desiredCapabilities": {
                "marionette": true,
                "javascriptEnabled": true,
                "acceptSslCerts": true,
                "browserName": "chrome",
                "chromeOptions": {
                    "args": ["start-fullscreen"]
                }
            },
            "silent": true
        },
        "firefox": {
            "desiredCapabilities": {
                "browserName": "firefox",
                "args": ["-headless"]
            }
        }
    },
    "selenium": {
        "start_process": true,
        "server_path": "./bin/lib/selenium-server-standalone-3.7.1.jar",
        "log_path": "",
        "port": 4444,
        "cli_args": {
            "webdriver.chrome.driver": "./bin/lib/chromedriver",
            "webdriver.gecko.driver": "./bin/lib/geckodriver"
        }
    }
}
</code>```

When I run test cases using yarn nightwatch. It runs the test cases successfully but application never terminates with exit code 0and shows message below :

```<code>4 scenarios (4 passed)
8 steps (8 passed)
0m05.510s
(node:19502) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'indexOf' of undefined
(node:19502) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Anyone knows why I am getting this error?

答:
I have 3 suggestions:

Try to remove src_folders.

Try to follow http://mucsi96.github.io/nightwatch-cucumber/#getting-started

Check out https://github.com/mucsi96/nightwatch-cucumber-example

Body:
I have integrated cucumber with nightwatch.js.

My package.json looks like:-

{
  "name": "learning-nightwatch",
  "version": "1.0.0",
  "description": "learning nightwatch",
  "license": "UNLICENSED",
  "scripts": {
    "nightwatch": "nightwatch",
    "start": "bin/start",
    "stop": "bin/stop",
    "test": "bin/test"
  },
  "dependencies": {
    "lodash": "^4.17.4",
    "minimist": "^1.2.0",
    "nightwatch": "^0.9.16",
    "cucumber": "^3.1.0",
    "nightwatch-cucumber": "^8.2.9"
  }
}

nigtwatch config:-

{
    "src_folders": [null],
    "output_folder": "reports",
    "custom_commands_path": "",
    "custom_assertions_path": "",
    "page_objects_path": "./pageObjects",
    "globals_path": "",
    "test_settings": {
        "default": {
            "launch_url": "http://localhost:8083",
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "screenshots": {
                "enabled": true,
                "on_failure": true,
                "on_error": true,
                "path": "./screenshots"
            },
            "desiredCapabilities": {
                "marionette": true,
                "javascriptEnabled": true,
                "acceptSslCerts": true,
                "browserName": "chrome",
                "chromeOptions": {
                    "args": ["start-fullscreen"]
                }
            },
            "silent": true
        },
        "firefox": {
            "desiredCapabilities": {
                "browserName": "firefox",
                "args": ["-headless"]
            }
        }
    },
    "selenium": {
        "start_process": true,
        "server_path": "./bin/lib/selenium-server-standalone-3.7.1.jar",
        "log_path": "",
        "port": 4444,
        "cli_args": {
            "webdriver.chrome.driver": "./bin/lib/chromedriver",
            "webdriver.gecko.driver": "./bin/lib/geckodriver"
        }
    }
}

When I run test cases using yarn nightwatch. It runs the test cases successfully but application never terminates with exit code 0and shows message below :

4 scenarios (4 passed)
8 steps (8 passed)
0m05.510s
(node:19502) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'indexOf' of undefined
(node:19502) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Anyone knows why I am getting this error?


问:
Take the containing string array after split in Python
If I have some text like:

```<code> text= "  First sentence. Second sentence. Third sentence."
</code>```

And after this I split by '.':

```<code> new_split = text.split('.')
</code>```

I will receive: ['First sentence', Second sentence','Third sentence']

How could I print entire second sentence if I call it?

Like:

```<code>if 'second' in new_split : print (new_split[GET SECOND SENTENCE])
</code>```

I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.

答:
```<code>text= "  First sentence. Second sentence. Third sentence."

[print(i) for i in text.split('.') if "second" in i.lower()]
</code>```

which prints:

```<code> Second sentence
</code>```

Above is the shortest way I could think of doing it in terms of lines, but you just as easily do it with a for-loop rather than a list-comp:

```<code>for sentence in text.split('.'):
    if "second" in sentence.lower():
        print(sentence)
</code>```

Body:
If I have some text like:

 text= "  First sentence. Second sentence. Third sentence."

And after this I split by '.':

 new_split = text.split('.')

I will receive: ['First sentence', Second sentence','Third sentence']

How could I print entire second sentence if I call it?

Like:

if 'second' in new_split : print (new_split[GET SECOND SENTENCE])

I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.

Body:
text= "  First sentence. Second sentence. Third sentence."

[print(i) for i in text.split('.') if "second" in i.lower()]

which prints:

 Second sentence

Above is the shortest way I could think of doing it in terms of lines, but you just as easily do it with a for-loop rather than a list-comp:

for sentence in text.split('.'):
    if "second" in sentence.lower():
        print(sentence)


问:
Change background color but always get error that App has stopped
```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.
</code>```

This is what I get when I run the program and I don't know what to do.
I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.

```<code>package com.example.gia.applumini;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}
</code>```

答:
Another even simpler way to deal with this is by using the layout's XML code. Simply add the following attribute to your  tag:

```<code>android:background="#ff0000"
</code>```

Note that the color above is for red, you can modify the RGB values however you like.

Body:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.

This is what I get when I run the program and I don't know what to do.
I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.

package com.example.gia.applumini;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}

Body:
Another even simpler way to deal with this is by using the layout's XML code. Simply add the following attribute to your  tag:

android:background="#ff0000"

Note that the color above is for red, you can modify the RGB values however you like.


问:
How to deregister / unregister Firebase user when registered using Phone Auth
I have registered users using Firebase convenience FUIPhoneAuth. When I try to delete the user with:

```<code>[user deleteWithCompletion:^(NSError * _Nullable error) ..
</code>```

I get an error message saying the only recently authenticate users can be deleted.

```<code>"This operation is sensitive and requires recent authentication. Log in again before retrying this request."
</code>```

In order to deregister the user, I first need to re-authenticate the user which requires a FIRAuthCredential "credential" parameter:

```<code>[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {
</code>```

Firebase doc mentions that one should save FIRAuthCredential when a delegate gets called.(store it in NSUserDefaults)

```<code>[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput
                                    UIDelegate:nil
                                    completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
</code>```

I have used FUIPhoneAuth with signInWithPresentingViewController: and did not receive a FIRAuthCredential upon registration.
I am thinking that if I can get hold of the "FIRAuthCredential" I can re-use it
to deregister the user. But when using the FUIPhoneAuth this does not seem possible.
*How do I get hold of the FIRAuthCredential in order to deregister a user?*

Can one reuse the "FIRAuthCredential or does one need to do a complete re-authentication with a SMS before the user can be
deleted?

How does one deregister a user when registered using FUIPhoneAuth?

答:
I'm not sure where the docs mention saving the credential in NSUserDefaults, but generally you shouldn't store sensitive information there. If you must for some reason, it should be in keychain.

You must understand that authentication and verification are two very different things. Authentication occurs every time you sign into the app (generating the credentials/tokens, etc...). Verification, on the other hand, is optional and in most cases, should occur just once (per verification method) in a user's in-app lifetime.

For instance, when you register as a Facebook user, you verify your email only once, you may also verify your phone number with SMS just once, but you get authenticated each and every time you log in.

First Answer:
So, to answer your first question, what you need in order to delete a user is re-authentication, which is completely independent of verification. You may relate this to Facebook asking for your password (even though you're logged in) before deactivating your account or attempting any big changes.

Second Answer:
As of your second question, getting the users' credentials depends on what type of credential it is (do you use email/password? Google/Facebook/Twitter?). Each method has its own way of "recreating" the credential, so to speak.

Email/Password

```<code>FIRAuthCredential *credential = [FIREmailPasswordAuthProvider credentialWithEmail: email password: password];
</code>```

Facebook

```<code>FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken: fbTokenString];
</code>```

Google

```<code>FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken: token accessToken: accessToken];
</code>```

Twitter

```<code>FIRAuthCredential *credential = [FIRTwitterAuthProvider credentialWithToken: session.authToken secret: session.authTokenSecret];
</code>```

My answer here might be helpful in terms of prompting the user to re-enter the password in case you're using email/password credentials.

You can use the newly generated credentials to re-authenticate as you did in your post (here's the relevant documentation), then you can use deleteWithCompletion in the re-authentication completion-block.

Update

The link you provided states that you should store the "verification ID" in NSUserDefaults, not the auth credential. The verification ID and verification code (what's sent in the SMS) pair are used together to get auth credentials and then sign in. You don't have to store it, they just recommend that you do in case the app restarts upon switching to and from the Messages app. You can safely delete the verification ID after the user signs in.

As of your second comment, you can get the auth credentials by relaunching the verification process (this part of the link you mentioned; send an SMS, get the user input, then call credentialWithVerificationID). You should not save the credential locally as it's a security risk and it expires anyway. Only save the verification ID temporarily until the user enters the verification code and gets authenticated.

Body:
I have registered users using Firebase convenience FUIPhoneAuth. When I try to delete the user with:

[user deleteWithCompletion:^(NSError * _Nullable error) ..

I get an error message saying the only recently authenticate users can be deleted.

"This operation is sensitive and requires recent authentication. Log in again before retrying this request."

In order to deregister the user, I first need to re-authenticate the user which requires a FIRAuthCredential "credential" parameter:

[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {

Firebase doc mentions that one should save FIRAuthCredential when a delegate gets called.(store it in NSUserDefaults)

[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput
                                    UIDelegate:nil
                                    completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {

I have used FUIPhoneAuth with signInWithPresentingViewController: and did not receive a FIRAuthCredential upon registration.
I am thinking that if I can get hold of the "FIRAuthCredential" I can re-use it
to deregister the user. But when using the FUIPhoneAuth this does not seem possible.
*How do I get hold of the FIRAuthCredential in order to deregister a user?*

Can one reuse the "FIRAuthCredential or does one need to do a complete re-authentication with a SMS before the user can be
deleted?

How does one deregister a user when registered using FUIPhoneAuth?

Body:
I'm not sure where the docs mention saving the credential in NSUserDefaults, but generally you shouldn't store sensitive information there. If you must for some reason, it should be in keychain.

You must understand that authentication and verification are two very different things. Authentication occurs every time you sign into the app (generating the credentials/tokens, etc...). Verification, on the other hand, is optional and in most cases, should occur just once (per verification method) in a user's in-app lifetime.

For instance, when you register as a Facebook user, you verify your email only once, you may also verify your phone number with SMS just once, but you get authenticated each and every time you log in.

First Answer:
So, to answer your first question, what you need in order to delete a user is re-authentication, which is completely independent of verification. You may relate this to Facebook asking for your password (even though you're logged in) before deactivating your account or attempting any big changes.

Second Answer:
As of your second question, getting the users' credentials depends on what type of credential it is (do you use email/password? Google/Facebook/Twitter?). Each method has its own way of "recreating" the credential, so to speak.

Email/Password

FIRAuthCredential *credential = [FIREmailPasswordAuthProvider credentialWithEmail: email password: password];

Facebook

FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken: fbTokenString];

Google

FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken: token accessToken: accessToken];

Twitter

FIRAuthCredential *credential = [FIRTwitterAuthProvider credentialWithToken: session.authToken secret: session.authTokenSecret];

My answer here might be helpful in terms of prompting the user to re-enter the password in case you're using email/password credentials.

You can use the newly generated credentials to re-authenticate as you did in your post (here's the relevant documentation), then you can use deleteWithCompletion in the re-authentication completion-block.

Update

The link you provided states that you should store the "verification ID" in NSUserDefaults, not the auth credential. The verification ID and verification code (what's sent in the SMS) pair are used together to get auth credentials and then sign in. You don't have to store it, they just recommend that you do in case the app restarts upon switching to and from the Messages app. You can safely delete the verification ID after the user signs in.

As of your second comment, you can get the auth credentials by relaunching the verification process (this part of the link you mentioned; send an SMS, get the user input, then call credentialWithVerificationID). You should not save the credential locally as it's a security risk and it expires anyway. Only save the verification ID temporarily until the user enters the verification code and gets authenticated.


问:
Sharing session cookie across two named domains
I have a .net webapplication with the following domains:
www.domain.com
sub.domain.com
files.domain.com

When a user is logged on to domain.com or sub.domain.com, I'd like them to share session state (i.e. be logged into both domains at once). This is possible to do by setting the domain on the session coookie to be ".domain.com".
However, my problem is that the domain "files.domain.com" should not have session state due to security issues (xss attacks from user-made files hosted on that domain is an issue).

Is it possible in ASP.NET to use the same asp.net session id for these two domains, but not the third one?

Thanks in advance!

答:
Don't confuse session cookies and forms authentication cookies. ASP.NET Session cannot be shared between applications. As far as the forms authentication cookie is concerned, well it is just a simple cookie and the way cookies work is by setting the domain property.

One way I can think of to achieve this is to define special machineKeys in web.config for the two applications. This way users that authenticated on www.domain.com will be emitted a cookie which will be encrypted with the machinekeys of www.domain.com and because only sub.domain.com  has the same keys will be able to decrypt the cookie. The cookie will still be sent to files.domain.com but it won't be able to decrypt it and users won't be authenticated there.

ContentLicense: CC BY-SA 2.5


问:
SunPKCS11 provider in MacOS for Firefox
I managed to get the SunPKCS11 to work with Firefox ESR 52.0 under Windows, but I am unable to get it to load in MacOS. I've already tried several different configuration and directly loading it via PKCS11 but nothing worked, can anyone give me some pointer?

pkcs11.cfg configuration as follow:

```<code>name = FirefoxKeyStore
library = "/Applications/Firefox.app/Contents/MacOS/fixed-for-java-runtime/libsoftokn3.dylib"
attributes = compatibility
nssArgs = "configdir='/Users/helloworld/Library/Application Support/Firefox/Profiles/wasdwasd.default-1453211557245' certPrefix='' keyPrefix='' secmod='secmod.db' flags='readOnly' "
slot = 2
</code>```

Then in Java, I've tried to load it like this:

```<code>FileInputStream fis = new FileInputStream("pkcs11.cfg");
Provider provider = new SunPKCS11(fis);
Security.addProvider(provider);
</code>```

However this immediately gives me the following error:

```<code>sunpkcs11: Initializing PKCS#11 library /Applications/Firefox.app/Contents/MacOS/fixed-for-java-runtime/libsoftokn3.dylib
sunpkcs11: Multi-threaded initialization failed: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DEVICE_ERROR
Exception in thread "main" java.security.ProviderException: Initialization failed
at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:376)
at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:107)
</code>```

You maybe asking why do I load the .dylib from the weird folder, that's because I used install_name_tool in MacOS to change the @executable_path to @loader_path in order to get the library dependency to work (since I'm trying to run this in Eclipse rather than from Firefox itself).

I also tried to use the solution suggested here: How to finalize SunPKCS11 Provider after it is initialized? and it was a no-go either... I get the same error.

As well as trying various different configuration settings mentioned here: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11/Module_Specs#Softoken_Specific_Parameters

EDIT1

I tried the method mentioned by @FaithReaper but it still throw the same error. I tried changing the slot value to 0, 1 or -1 and result the same. It looks like there are problem loading the underlaying PKCS11 object.

```<code>Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DEVICE_ERROR
at sun.security.pkcs11.wrapper.PKCS11.C_Initialize(Native Method)
at sun.security.pkcs11.wrapper.PKCS11$SynchronizedPKCS11.C_Initialize(PKCS11.java:1545)
at sun.security.pkcs11.wrapper.PKCS11.getInstance(PKCS11.java:157)
at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:330)
</code>```

I dunno if this would help, but I ran the modutil on the FireFox profile and is dumping this info:

```<code>modutil -dbdir "/Users/eto/Library/Application Support/Firefox/Profiles/ew2g332o.default-1453211557245" -rawlist

library= name="NSS Internal PKCS #11 Module"
parameters="configdir=/Users/eto/Library/Application Support/Firefox/Profiles/ew2g332o.default-1453211557245 certPrefix= keyPrefix= secmod=secmod.db flags=readOnly "
NSS="Flags=internal,critical trustOrder=75 cipherOrder=100 slotParams=(1={slotFlags=[RSA,DSA,DH,RC2,RC4,DES,RANDOM,SHA1,MD5,MD2,SSL,TLS,AES,Camellia,SEED,SHA256,SHA512] askpw=any timeout=30})"
</code>```

Listing of PKCS #11 Modules

NSS Internal PKCS #11 Module
   uri: pkcs11:library-manufacturer=Mozilla%20Foundation;library-description=NSS%20Internal%20Crypto%20Services;library-version=3.33
  slots: 2 slots attached    status: loaded

slot: NSS Internal Cryptographic Services  token: NSS Generic Crypto
  Services    uri:
  pkcs11:token=NSS%20Generic%20Crypto%20Services;manufacturer=Mozilla%20Foundation;serial=0000000000000000;model=NSS%203

slot: NSS User Private Key and Certificate Services    token: NSS
  Certificate DB      uri:
  pkcs11:token=NSS%20Certificate%20DB;manufacturer=Mozilla%20Foundation;serial=0000000000000000;model=NSS%203

答:
The libraries provided by Firefox in Mac OS X might actually be completely broken or non-functional if execute outside of FireFox.

After trying many different combination of configuration and ways, I finally got it working by NOT using the libraries from Firefox...

Here is the step by step ways to get it to work:

Install homebrew in your Mac

Run brew install nss

Run brew install nspr

You may need to manually link them with brew link nss and brew link nspr

In the configuration file, you need to point it to your homebrew libsoftokn3.dylib, like so library = /usr/local/opt/nss/lib/libsoftokn3.dylib

Then your Java code should be able to load the Firefox keystore under Mac OS X... I've filed a bug here. The ticket contains a working sample code on how to instantiate the PKCS11, load the Firefox keystore and list the aliases from the store.

This was definitely a nightmare working with Firefox... but at least I got it working... Who would've thought the libraries they provided doesn't work (but it worked in Windows!)? :P

For completeness, I've included the sample code directly in this post as well:

```<code>import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.Collections;

public class Sample {

    private KeyStore load(String lib, String profile) throws Exception
    {
        String config = "library = " + lib + "\n" +
                "name = FirefoxKeyStore\n" +
                "attributes = compatibility\n" +
                "nssArgs = \"configDir='" + profile + "' certPrefix='' keyPrefix='' secmod='secmod.db' flags='readOnly,forceOpen,optimizeSpace' \"\n" +
                "slot = 2\n";

        ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
        Provider provider = new sun.security.pkcs11.SunPKCS11(bais);
        Security.addProvider(provider);

        return KeyStore.getInstance("PKCS11");
    }

    public static void main(String[] args) throws Exception {

        Sample s = new Sample();

        String profile = "/Users/blah/Library/Application Support/Firefox/Profiles/yougottachangethis";
        String[] libs = {
            //"/Applications/Firefox.app/Contents/MacOS/libsoftokn3.dylib",
            "/usr/local/opt/nss/lib/libsoftokn3.dylib"
        };

        for (String lib : libs) {
            System.out.println("TRYING >>> " + lib);
            try {
                KeyStore ks1 = s.load(lib, profile);

                ks1.load(null, null);
                for (String alias : Collections.list(ks1.aliases())) {
                    System.out.println(alias);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
</code>```

Here is the output of the otool from Mac (included for FaithReaper's comments):

```<code>otool -L libsoftokn3.dylib
libsoftokn3.dylib:
/usr/local/opt/nss/lib/libsoftokn3.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libsqlite3.dylib (compatibility version 9.0.0, current version 253.0.0)
/usr/local/Cellar/nss/3.34/lib/libnssutil3.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/nspr/lib/libplc4.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/nspr/lib/libplds4.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/nspr/lib/libnspr4.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)
</code>```

Title: SunPKCS11 provider in MacOS for Firefox

Body:
I managed to get the SunPKCS11 to work with Firefox ESR 52.0 under Windows, but I am unable to get it to load in MacOS. I've already tried several different configuration and directly loading it via PKCS11 but nothing worked, can anyone give me some pointer?

pkcs11.cfg configuration as follow:

name = FirefoxKeyStore
library = "/Applications/Firefox.app/Contents/MacOS/fixed-for-java-runtime/libsoftokn3.dylib"
attributes = compatibility
nssArgs = "configdir='/Users/helloworld/Library/Application Support/Firefox/Profiles/wasdwasd.default-1453211557245' certPrefix='' keyPrefix='' secmod='secmod.db' flags='readOnly' "
slot = 2

Then in Java, I've tried to load it like this:

FileInputStream fis = new FileInputStream("pkcs11.cfg");
Provider provider = new SunPKCS11(fis);
Security.addProvider(provider);

However this immediately gives me the following error:

sunpkcs11: Initializing PKCS#11 library /Applications/Firefox.app/Contents/MacOS/fixed-for-java-runtime/libsoftokn3.dylib
sunpkcs11: Multi-threaded initialization failed: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DEVICE_ERROR
Exception in thread "main" java.security.ProviderException: Initialization failed
at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:376)
at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:107)

You maybe asking why do I load the .dylib from the weird folder, that's because I used install_name_tool in MacOS to change the @executable_path to @loader_path in order to get the library dependency to work (since I'm trying to run this in Eclipse rather than from Firefox itself).

I also tried to use the solution suggested here: How to finalize SunPKCS11 Provider after it is initialized? and it was a no-go either... I get the same error.

As well as trying various different configuration settings mentioned here: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11/Module_Specs#Softoken_Specific_Parameters

EDIT1

I tried the method mentioned by @FaithReaper but it still throw the same error. I tried changing the slot value to 0, 1 or -1 and result the same. It looks like there are problem loading the underlaying PKCS11 object.

Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DEVICE_ERROR
at sun.security.pkcs11.wrapper.PKCS11.C_Initialize(Native Method)
at sun.security.pkcs11.wrapper.PKCS11$SynchronizedPKCS11.C_Initialize(PKCS11.java:1545)
at sun.security.pkcs11.wrapper.PKCS11.getInstance(PKCS11.java:157)
at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:330)

I dunno if this would help, but I ran the modutil on the FireFox profile and is dumping this info:

modutil -dbdir "/Users/eto/Library/Application Support/Firefox/Profiles/ew2g332o.default-1453211557245" -rawlist

library= name="NSS Internal PKCS #11 Module"
parameters="configdir=/Users/eto/Library/Application Support/Firefox/Profiles/ew2g332o.default-1453211557245 certPrefix= keyPrefix= secmod=secmod.db flags=readOnly "
NSS="Flags=internal,critical trustOrder=75 cipherOrder=100 slotParams=(1={slotFlags=[RSA,DSA,DH,RC2,RC4,DES,RANDOM,SHA1,MD5,MD2,SSL,TLS,AES,Camellia,SEED,SHA256,SHA512] askpw=any timeout=30})"

Listing of PKCS #11 Modules

NSS Internal PKCS #11 Module
   uri: pkcs11:library-manufacturer=Mozilla%20Foundation;library-description=NSS%20Internal%20Crypto%20Services;library-version=3.33
  slots: 2 slots attached    status: loaded

slot: NSS Internal Cryptographic Services  token: NSS Generic Crypto
  Services    uri:
  pkcs11:token=NSS%20Generic%20Crypto%20Services;manufacturer=Mozilla%20Foundation;serial=0000000000000000;model=NSS%203

slot: NSS User Private Key and Certificate Services    token: NSS
  Certificate DB      uri:
  pkcs11:token=NSS%20Certificate%20DB;manufacturer=Mozilla%20Foundation;serial=0000000000000000;model=NSS%203

Body:
The libraries provided by Firefox in Mac OS X might actually be completely broken or non-functional if execute outside of FireFox.

After trying many different combination of configuration and ways, I finally got it working by NOT using the libraries from Firefox...

Here is the step by step ways to get it to work:

Install homebrew in your Mac

Run brew install nss

Run brew install nspr

You may need to manually link them with brew link nss and brew link nspr

In the configuration file, you need to point it to your homebrew libsoftokn3.dylib, like so library = /usr/local/opt/nss/lib/libsoftokn3.dylib

Then your Java code should be able to load the Firefox keystore under Mac OS X... I've filed a bug here. The ticket contains a working sample code on how to instantiate the PKCS11, load the Firefox keystore and list the aliases from the store.

This was definitely a nightmare working with Firefox... but at least I got it working... Who would've thought the libraries they provided doesn't work (but it worked in Windows!)? :P

For completeness, I've included the sample code directly in this post as well:

import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.Collections;

public class Sample {

    private KeyStore load(String lib, String profile) throws Exception
    {
        String config = "library = " + lib + "\n" +
                "name = FirefoxKeyStore\n" +
                "attributes = compatibility\n" +
                "nssArgs = \"configDir='" + profile + "' certPrefix='' keyPrefix='' secmod='secmod.db' flags='readOnly,forceOpen,optimizeSpace' \"\n" +
                "slot = 2\n";

        ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
        Provider provider = new sun.security.pkcs11.SunPKCS11(bais);
        Security.addProvider(provider);

        return KeyStore.getInstance("PKCS11");
    }

    public static void main(String[] args) throws Exception {

        Sample s = new Sample();

        String profile = "/Users/blah/Library/Application Support/Firefox/Profiles/yougottachangethis";
        String[] libs = {
            //"/Applications/Firefox.app/Contents/MacOS/libsoftokn3.dylib",
            "/usr/local/opt/nss/lib/libsoftokn3.dylib"
        };

        for (String lib : libs) {
            System.out.println("TRYING >>> " + lib);
            try {
                KeyStore ks1 = s.load(lib, profile);

                ks1.load(null, null);
                for (String alias : Collections.list(ks1.aliases())) {
                    System.out.println(alias);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

Here is the output of the otool from Mac (included for FaithReaper's comments):

otool -L libsoftokn3.dylib
libsoftokn3.dylib:
/usr/local/opt/nss/lib/libsoftokn3.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libsqlite3.dylib (compatibility version 9.0.0, current version 253.0.0)
/usr/local/Cellar/nss/3.34/lib/libnssutil3.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/nspr/lib/libplc4.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/nspr/lib/libplds4.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/nspr/lib/libnspr4.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)


问:
Viewing a Text-Box after a Button Click PHP
I know this question has been asked before multiple times on StackOverFlow. I have implemented a method to generate a text box for Button click event. But my issue is text box is already visible before performing the clicking. I need to view the text-box when someone clicks the button. I'll put my coding down below.

Coding for the text-field

```<code> <div id="inputField" style="display:none;">
          <input type="text" id="textInput" value="" />
          </div>
</code>```

Coding for the Button click event

```<code><a href="" onclick="document.getElementById('inputField').style.display = 'block';">Click me</a>
</code>```

Just to make more sense, I'll attach a screenshot of my coding and the graphical view of the form.

I'm kindly requesting from everyone not to mark this question as duplicate. I did my best to fix this issue by my own. Though I'm a newbie to this field I couldn't make it up. Any help would be really appreciated. Thank you!

答:
Try the html with:

```<code><form method="post" action="?btnpressed=1">
    <a href="" name="btn">Click me</a>
</form>
</code>```

And in the php:

```<code>    <?php
    if(isset($_GET['btnpressed']{
        if(isset($_POST['btn']{ ?>
            <div id="inputField" style="display:none;">
                <input type="text" id="textInput" value="" />
            </div>
        <?php
        }
    }
    ?>
</code>```

I hope this helps...

Body:
I know this question has been asked before multiple times on StackOverFlow. I have implemented a method to generate a text box for Button click event. But my issue is text box is already visible before performing the clicking. I need to view the text-box when someone clicks the button. I'll put my coding down below.

Coding for the text-field

          <input type="text" id="textInput" value="" />

Coding for the Button click event

Click me

Just to make more sense, I'll attach a screenshot of my coding and the graphical view of the form.

I'm kindly requesting from everyone not to mark this question as duplicate. I did my best to fix this issue by my own. Though I'm a newbie to this field I couldn't make it up. Any help would be really appreciated. Thank you!

Body:
Try the html with:

<form method="post" action="?btnpressed=1">
    <a href="" name="btn">Click me</a>
</form>

And in the php:

    <?php
    if(isset($_GET['btnpressed']{
        if(isset($_POST['btn']{ ?>
            <div id="inputField" style="display:none;">
                <input type="text" id="textInput" value="" />
            </div>
        <?php
        }
    }
    ?>

I hope this helps...

ContentLicense: CC BY-SA 4.0


问:
A way to reduce run-time
I have a 2048x2048 image and I want to re-set the pixels values according to certain condition. The problem is that it takes houres (if not days) for the code to end. Is there a way to shorten the run-time?
This is the function:

```<code>function ProcImage = ProcessImage(X,length,width)
 for i=1:length
    for j=1:width
        if X(j,i)<=0.025*(max(max(X(:,:))))
            X(j,i)=0;
        else
            if X(j,i)>=0.95*(max(max(X(:,:))))
                X(j,i)=(max(max(X(:,:))));
            end
        end
    end
end
ProcImage=X(1:end,1:end);
</code>```

thanks in advance.

答:
If your image is a gray scale image that its values are in the range 0 to 255 here is a possible solution:</p>

```<code>m = max(X(:));
tbl = 0:255;
tbl(tbl<=0.025*m)=0;
tbl(tbl>=0.95*m)=m;
X = tbl(int16(X)+1);
</code>```

Title: A way to reduce run-time

Body:
I have a 2048x2048 image and I want to re-set the pixels values according to certain condition. The problem is that it takes houres (if not days) for the code to end. Is there a way to shorten the run-time?
This is the function:

function ProcImage = ProcessImage(X,length,width)
 for i=1:length
    for j=1:width
        if X(j,i)<=0.025*(max(max(X(:,:))))
            X(j,i)=0;
        else
            if X(j,i)>=0.95*(max(max(X(:,:))))
                X(j,i)=(max(max(X(:,:))));
            end
        end
    end
end
ProcImage=X(1:end,1:end);

thanks in advance.

Body:
If your image is a gray scale image that its values are in the range 0 to 255 here is a possible solution:

m = max(X(:));
tbl = 0:255;
tbl(tbl<=0.025*m)=0;
tbl(tbl>=0.95*m)=m;
X = tbl(int16(X)+1);


问:
Set an Integer value from one class to another
I have been trying to set an Integer value from one class to another like below, but i can't do this.

```<code>@interface ClassA : UIViewController {

}

@property(nonatomic, assign) int m_selrow;
+ (void)setRowSelected : (int)selecetedRow;

@end

@implementation ClassA

+ (void)setRowSelected : (int)selecetedRow {
    m_selrow = selecetedRow;

}
@end

//Accessing from different Class,

//Class B implementation:

[ClassA setRowSelected:indexPath.row];
</code>```

Problem is, it says "m_selrow is use of undeclared identifier from setRowSelected() method. How to properly use the variable and set it from another class.

答:
Interface should inherit from something, I changed it to NSObject

I also added static declartion to of member field to class A

After fixing those, it works smoothly.

Here are my changes:

```<code>@interface ClassA : NSObject{

}

@property(nonatomic, assign) int m_selrow;
+ (void)setRowSelected : (int)selecetedRow;

@end

@implementation ClassA
static int m_selrow;

+ (void)setRowSelected : (int)selecetedRow {
    m_selrow = selecetedRow;
    NSLog(@"============= > %d", m_selrow);

}
@end

[ClassA setRowSelected: 1];
</code>```

Body:
I have been trying to set an Integer value from one class to another like below, but i can't do this.

@interface ClassA : UIViewController {

}

@property(nonatomic, assign) int m_selrow;
+ (void)setRowSelected : (int)selecetedRow;

@end

@implementation ClassA

+ (void)setRowSelected : (int)selecetedRow {
    m_selrow = selecetedRow;

}
@end

//Accessing from different Class,

//Class B implementation:

[ClassA setRowSelected:indexPath.row];

Problem is, it says "m_selrow is use of undeclared identifier from setRowSelected() method. How to properly use the variable and set it from another class.

Body:
Interface should inherit from something, I changed it to NSObject

I also added static declartion to of member field to class A

After fixing those, it works smoothly.

Here are my changes:

@interface ClassA : NSObject{

}

@property(nonatomic, assign) int m_selrow;
+ (void)setRowSelected : (int)selecetedRow;

@end

@implementation ClassA
static int m_selrow;

+ (void)setRowSelected : (int)selecetedRow {
    m_selrow = selecetedRow;
    NSLog(@"============= > %d", m_selrow);

}
@end

[ClassA setRowSelected: 1];


问:
How would I parse an XML file into a list
List:

```<code>List<string> list = new List<string>();
</code>```

XML File:

```<code><memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>
</code>```

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

答:
You should use using System.Xml.Linq;</p>

```<code>using (FileStream fileStramWrite = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
 using (StreamReader streamReader = new StreamReader(fileStramWrite))
                    {
                        var xdoc = XDocument.Load(streamReader);
                        var xElement = xdoc.Element("memberlist");
                        var xElement2 = xElement.Element("member");
                        var name = xElement2.Element("name").Value;
                        var status = xElement2.Element("status").Value;
                    }
</code>```

Body:
List:

List<string> list = new List<string>();

XML File:

<memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

Body:
You should use using System.Xml.Linq;

using (FileStream fileStramWrite = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
 using (StreamReader streamReader = new StreamReader(fileStramWrite))
                    {
                        var xdoc = XDocument.Load(streamReader);
                        var xElement = xdoc.Element("memberlist");
                        var xElement2 = xElement.Element("member");
                        var name = xElement2.Element("name").Value;
                        var status = xElement2.Element("status").Value;
                    }


问:
Optimize query for intersection of ST_Buffer layer in PostGIS
I have two tables stored in PostGIS:
1. a multipolygon vector with about 590000 rows (layerA) and
2. a single multipart (1 row) vector layer (layerB)

and I want to find the area of the intersection between each polygon's buffer in layerA and layerB. My query so far is

```<code>SELECT ST_Area(ST_Intersection(a.geom, b.geom)) AS myarea, a.gid AS mygid FROM
(SELECT ST_Buffer(geom, 500) AS geom, gid FROM layerA) AS a,
layerB AS b
</code>```

So far, I can see my query working but I calculate that it needs 17 hours to be completed (with my PC). Is there another way to execute this query more efficiently and faster?

答:
You would probably get more answers to this at gis.stackexchange.com.

Therea are several things you can do.

You should make sure you get that first filtering of polygons actually intersecting with help of index.

Put a gist index on the table with many geometries and use st_dwithin(geom,500) instead of st_intersects on the buffered geometries. That is because the buffered geometries cannot use the index calculated on the unbuffered geometries.

Also, you say you have multi polygons. If there actually is more than 1 polygon in each multipolygon you might get a lot more speed if you first split the polygons to single polygons before building the index. That will make the.index doing a much bigger part of the job.

There is actually a function in postgis to split even single polygons into smaller pieces for the same reason.
ST_SubDivide

So first use ST_Dump to get single polygons:

```<code>CREATE table a_singles AS
SELECT id, (ST_Dump(geom)).geom geom FROM a;
</code>```

Then create index:

```<code>CREATE INDEX idx_a_s_geom
ON a_singles
USING gist(geom);
</code>```

At last the query, something like

```<code>SELECT ST_Area(ST_Intersection(ST_Buffer(a_s.geom,500), b.geom))
FROM a_singles AS a_s
INNER JOIN b
on ST_DWithin(a_s.geom,b.geom,500);
</code>```

If that still is slow you can start playing with ST_SubDivide.

One more thing. If the single multipolygon in table b contains many geometries, also split them and put an index also there.

It might be slow also after all those things. That depends on how many vertex points there is in the splitted polygons that actually intersect (and for st_dwithin also on how many vertexpoints there is in polygons with overlapping bounding boxes)

But now you don't have any index helping you so this should  make it quite a lot faster.

Body:
I have two tables stored in PostGIS:
1. a multipolygon vector with about 590000 rows (layerA) and
2. a single multipart (1 row) vector layer (layerB)

and I want to find the area of the intersection between each polygon's buffer in layerA and layerB. My query so far is

SELECT ST_Area(ST_Intersection(a.geom, b.geom)) AS myarea, a.gid AS mygid FROM
(SELECT ST_Buffer(geom, 500) AS geom, gid FROM layerA) AS a,
layerB AS b

So far, I can see my query working but I calculate that it needs 17 hours to be completed (with my PC). Is there another way to execute this query more efficiently and faster?

Body:
You would probably get more answers to this at gis.stackexchange.com.

Therea are several things you can do.

You should make sure you get that first filtering of polygons actually intersecting with help of index.

Put a gist index on the table with many geometries and use st_dwithin(geom,500) instead of st_intersects on the buffered geometries. That is because the buffered geometries cannot use the index calculated on the unbuffered geometries.

Also, you say you have multi polygons. If there actually is more than 1 polygon in each multipolygon you might get a lot more speed if you first split the polygons to single polygons before building the index. That will make the.index doing a much bigger part of the job.

There is actually a function in postgis to split even single polygons into smaller pieces for the same reason.
ST_SubDivide

So first use ST_Dump to get single polygons:

CREATE table a_singles AS
SELECT id, (ST_Dump(geom)).geom geom FROM a;

Then create index:

CREATE INDEX idx_a_s_geom
ON a_singles
USING gist(geom);

At last the query, something like

SELECT ST_Area(ST_Intersection(ST_Buffer(a_s.geom,500), b.geom))
FROM a_singles AS a_s
INNER JOIN b
on ST_DWithin(a_s.geom,b.geom,500);

If that still is slow you can start playing with ST_SubDivide.

One more thing. If the single multipolygon in table b contains many geometries, also split them and put an index also there.

It might be slow also after all those things. That depends on how many vertex points there is in the splitted polygons that actually intersect (and for st_dwithin also on how many vertexpoints there is in polygons with overlapping bounding boxes)

But now you don't have any index helping you so this should  make it quite a lot faster.


答:
To find the index of the first sentence in a list of sentences which is containing a given substring:

```<code>i = next(i for i, sentence in enumerate(sentences) if word in sentence)
</code>```

The same thing with simple Python:

```<code>for i, sentence in enumerate(sentences):
    if word in sentence:
        break
else:
    # the word is not in any of the sentences
</code>```

Title: Take the containing string array after split in Python

Body:
If I have some text like:

 text= "  First sentence. Second sentence. Third sentence."

And after this I split by '.':

 new_split = text.split('.')

I will receive: ['First sentence', Second sentence','Third sentence']

How could I print entire second sentence if I call it?

Like:

if 'second' in new_split : print (new_split[GET SECOND SENTENCE])

I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.

Body:
To find the index of the first sentence in a list of sentences which is containing a given substring:

i = next(i for i, sentence in enumerate(sentences) if word in sentence)

The same thing with simple Python:

for i, sentence in enumerate(sentences):
    if word in sentence:
        break
else:
    # the word is not in any of the sentences


问:
What happens to a running method if its object is deleted?
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

```<code>// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}
</code>```

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)

答: Deleting the object invalidates the this pointer. Creating a new object a probably (but not 100%) gives you a new pointer. But in the code above, the this pointer does not magically change to the new object. You have Undefined  Behaviour. </p>

Body:
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)


问:
Excel countif integer but exclude date value
I have a basic Excel file to log healthcare survey completed each week, identified by its Project ID, city, type of facility, date completed, and person assigned.

For the week of 10/02/17, I just want to count the number of projects completed that starts in the 17000s; ignore projects in the 1000s.

For example, week of 10/02/17, North zone, =COUNTIF(H3:L9,">17000") = 11. My expected result is 4 not 11 as I want to exclude the date values from the count. See image screenshot for clarification. Thanks

```<code>=COUNTIF(H3:L9,">17000")
</code>```

答:
simply edit your countif statement to exclude the rest of the cells.

=COUNTIF(H3:H9, ">17000")

Body:
I have a basic Excel file to log healthcare survey completed each week, identified by its Project ID, city, type of facility, date completed, and person assigned.

For the week of 10/02/17, I just want to count the number of projects completed that starts in the 17000s; ignore projects in the 1000s.

For example, week of 10/02/17, North zone, =COUNTIF(H3:L9,">17000") = 11. My expected result is 4 not 11 as I want to exclude the date values from the count. See image screenshot for clarification. Thanks

=COUNTIF(H3:L9,">17000")


问:
NoClassDefFoundError while starting up jetty Server
I am trying to host my webapp (spring) in jetty server. I copied my war file to the 'webapp' folder in the jetty server. I am not trying to embed the jetty server, but trying to host the app within the jetty (like tomcat).

I dint install jetty, I just downloaded the jetty7 zip and extracted to get the server.

I need to set this up in 3 linux machines. In One machine the server is starting up just fine.No issues.

But in the other two, when the Server is starting up it is showing the following error.

```
2013-04-24 18:52:59.540:INFO::started o.e.j.w.WebAppContext{/cpewebapp,file:/tmp/jetty-0.0.0.0-9080-cpewebapp.war-_cpewebapp-any-/webapp/},/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/cpewebapp.war
2013-04-24 18:52:59.648:WARN::FAILED spring: java.lang.NoClassDefFoundError: org/springframework/web/context/support/DefaultWebEnvironment
2013-04-24 18:52:59.648:WARN::FAILED o.e.j.w.WebAppContext{/cpewebapp,file:/tmp/jetty-0.0.0.0-9080-cpewebapp.war-_cpewebapp-any-/webapp/},/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/cpewebapp.war: java.lang.NoClassDefFoundError: org/springframework/web/context/support/DefaultWebEnvironment
2013-04-24 18:52:59.649:WARN::Unable to reach node goal: started
java.lang.NoClassDefFoundError: org/springframework/web/context/support/DefaultWebEnvironment
    at org.springframework.web.servlet.HttpServletBean.(HttpServletBean.java:90)
    at org.springframework.web.servlet.FrameworkServlet.(FrameworkServlet.java:96)
    at org.springframework.web.servlet.DispatcherServlet.(DispatcherServlet.java:128)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at org.eclipse.jetty.servlet.ServletContextHandler$Context.createServlet(ServletContextHandler.java:606)
    at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:748)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:426)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:763)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:245)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1158)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:587)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:436)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36)
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:180)
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:482)
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:137)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:50)
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:601)
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:531)
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:394)
    at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:329)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:114)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:543)
    at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:218)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:41)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:50)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:94)
    at org.eclipse.jetty.server.Server.doStart(Server.java:253)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1220)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1143)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.jetty.start.Main.invokeMain(Main.java:477)
    at org.eclipse.jetty.start.Main.start(Main.java:623)
    at org.eclipse.jetty.start.Main.parseCommandLine(Main.java:273)
    at org.eclipse.jetty.start.Main.main(Main.java:81)
Caused by:
java.lang.ClassNotFoundException: org.springframework.web.context.support.DefaultWebEnvironment
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:420)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:373)
    at org.springframework.web.servlet.HttpServletBean.(HttpServletBean.java:90)
    at org.springframework.web.servlet.FrameworkServlet.(FrameworkServlet.java:96)
    at org.springframework.web.servlet.DispatcherServlet.(DispatcherServlet.java:128)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at org.eclipse.jetty.servlet.ServletContextHandler$Context.createServlet(ServletContextHandler.java:606)
    at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:748)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:426)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:763)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:245)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1158)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:587)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:436)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36)
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:180)
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:482)
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:137)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:50)
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:601)
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:531)
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:394)
    at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:329)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:114)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:543)
    at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:218)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:41)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:50)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:94)
    at org.eclipse.jetty.server.Server.doStart(Server.java:253)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1220)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1143)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.jetty.start.Main.invokeMain(Main.java:477)
    at org.eclipse.jetty.start.Main.start(Main.java:623)
    at org.eclipse.jetty.start.Main.parseCommandLine(Main.java:273)
    at org.eclipse.jetty.start.Main.main(Main.java:81)
2013-04-24 18:52:59.654:INFO::Deployable added: /home/manooja/jetty-hightide-7.4.0.v20110414/webapps/root
2013-04-24 18:52:59.849:INFO::started o.e.j.w.WebAppContext{/,file:/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/root/},/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/root
2013-04-24 18:52:59.861:INFO::Deployment monitor /home/manooja/jetty-hightide-7.4.0.v20110414/contexts at interval 1
2013-04-24 18:52:59.950:INFO::Started SelectChannelConnector@0.0.0.0:9080 STARTING
```

Kindly note that the default port have been changed to 9080.

I have an inkling that it might be some configuration change, as it is working fine in one machine.
Could you please help me with a guidance to solve this?

java -jar start.jar --version

```

    Active Options: [Server, client, ext, jmx, jsp, resources, websocket]
    Version Information on 25 entries in the classpath.
    Note: order presented here is how they would appear on the classpath.
          changes to the OPTIONS=[option,option,...] command line option will be reflected here.
     0:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-xml-9.0.2.v20130417.jar
     1:  3.0.0.v201112011016 | ${jetty.home}/lib/servlet-api-3.0.jar
     2:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-http-9.0.2.v20130417.jar
     3:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-continuation-9.0.2.v20130417.jar
     4:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-server-9.0.2.v20130417.jar
     5:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-security-9.0.2.v20130417.jar
     6:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-servlet-9.0.2.v20130417.jar
     7:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-webapp-9.0.2.v20130417.jar
     8:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-deploy-9.0.2.v20130417.jar
     9:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-client-9.0.2.v20130417.jar
    10:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-jmx-9.0.2.v20130417.jar
    11:  2.2.0.v201303151357 | ${jetty.home}/lib/jsp/com.sun.el-2.2.0.v201303151357.jar
    12:  2.2.0.v201303151357 | ${jetty.home}/lib/jsp/javax.el-2.2.0.v201303151357.jar
    13:  1.2.0.v201105211821 | ${jetty.home}/lib/jsp/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar
    14:  2.2.0.v201112011158 | ${jetty.home}/lib/jsp/javax.servlet.jsp-2.2.0.v201112011158.jar
    15:  2.2.2.v201112011158 | ${jetty.home}/lib/jsp/org.apache.jasper.glassfish-2.2.2.v201112011158.jar
    16:  1.2.0.v201112081803 | ${jetty.home}/lib/jsp/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar
    17: 3.8.2.v20130121-145325 | ${jetty.home}/lib/jsp/org.eclipse.jdt.core-3.8.2.v20130121.jar
    18:                (dir) | ${jetty.home}/resources
    19:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-api-9.0.2.v20130417.jar
    20:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-common-9.0.2.v20130417.jar
    21:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-server-9.0.2.v20130417.jar
    22:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-servlet-9.0.2.v20130417.jar
    23:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-util-9.0.2.v20130417.jar
    24:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-io-9.0.2.v20130417.jar

```

dir ./WEB-INF/lib/

```<code>antlr-2.7.6.jar
aopalliance-1.0.jar
bcprov-jdk15on-148.jar
c3p0-0.9.1.jar
commons-collections-3.2.1.jar
commons-dbcp-1.3.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
commons-pool-1.5.4.jar
cpewebapp.jar
displaytag-1.2.jar
dom4j-1.6.1.jar
gson-1.6.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-core-3.6.4.Final.jar
hibernate-entitymanager-3.6.4.Final.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate-validator-4.2.0.Final.jar
jackson-core-asl-1.8.0.jar
jackson-mapper-asl-1.8.0.jar
javassist-3.12.0.GA.jar
json.jar
jta.jar
log4j-1.2.16.jar
servlet-2.3.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
spring-aop-3.1.0.RELEASE.jar
spring-asm-3.1.0.RELEASE.jar
spring-beans-3.1.0.RELEASE.jar
spring-context-3.1.0.RELEASE.jar
spring-context-support-3.1.0.RELEASE.jar
spring-core-3.1.0.RELEASE.jar
spring-expression-3.1.0.RELEASE.jar
spring-jdbc-3.1.0.RELEASE.jar
spring-ldap-core-1.3.0.RELEASE.jar
spring-ldap-core-tiger-1.3.0.RELEASE.jar
spring-orm-3.1.0.RELEASE.jar
spring-oxm-3.1.0.RELEASE.jar
spring-security-config-3.1.0.RELEASE.jar
spring-security-core-3.1.0.RELEASE.jar
spring-security-ldap-3.1.0.RELEASE.jar
spring-security-web-3.1.0.RELEASE.jar
spring-tx-3.1.0.RELEASE.jar
spring-web-3.1.0.RELEASE.jar
spring-webmvc-3.1.0.M1.jar
spring-web-servlet-3.1.0.RELEASE.jar
sqlite-jdbc-3.7.2.jar
velocity-1.6.2.jar
velocity-tools-view-2.0.jar
</code>```

答:
In the case you use directly jetty as Eclipse J2EE integrated server,
sometimes, it doesn't find some libraries (I don't understand why some are not found, by only a few), and throws exception of this kind (NoClassDefFound).

So you have to put in the project source (directory WEB-INF): your jars

restart the server

it put the jars in runtime WEB-INF:
Data\workspace.metadata.plugins\org.eclipse.wst.server.core\tmpX\MyApp\WEB-INF\lib

and it works.

Body:
I am trying to host my webapp (spring) in jetty server. I copied my war file to the 'webapp' folder in the jetty server. I am not trying to embed the jetty server, but trying to host the app within the jetty (like tomcat).

I dint install jetty, I just downloaded the jetty7 zip and extracted to get the server.

I need to set this up in 3 linux machines. In One machine the server is starting up just fine.No issues.

But in the other two, when the Server is starting up it is showing the following error.

2013-04-24 18:52:59.540:INFO::started o.e.j.w.WebAppContext{/cpewebapp,file:/tmp/jetty-0.0.0.0-9080-cpewebapp.war-_cpewebapp-any-/webapp/},/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/cpewebapp.war
2013-04-24 18:52:59.648:WARN::FAILED spring: java.lang.NoClassDefFoundError: org/springframework/web/context/support/DefaultWebEnvironment
2013-04-24 18:52:59.648:WARN::FAILED o.e.j.w.WebAppContext{/cpewebapp,file:/tmp/jetty-0.0.0.0-9080-cpewebapp.war-_cpewebapp-any-/webapp/},/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/cpewebapp.war: java.lang.NoClassDefFoundError: org/springframework/web/context/support/DefaultWebEnvironment
2013-04-24 18:52:59.649:WARN::Unable to reach node goal: started
java.lang.NoClassDefFoundError: org/springframework/web/context/support/DefaultWebEnvironment
    at org.springframework.web.servlet.HttpServletBean.(HttpServletBean.java:90)
    at org.springframework.web.servlet.FrameworkServlet.(FrameworkServlet.java:96)
    at org.springframework.web.servlet.DispatcherServlet.(DispatcherServlet.java:128)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at org.eclipse.jetty.servlet.ServletContextHandler$Context.createServlet(ServletContextHandler.java:606)
    at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:748)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:426)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:763)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:245)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1158)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:587)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:436)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36)
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:180)
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:482)
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:137)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:50)
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:601)
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:531)
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:394)
    at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:329)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:114)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:543)
    at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:218)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:41)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:50)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:94)
    at org.eclipse.jetty.server.Server.doStart(Server.java:253)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1220)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1143)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.jetty.start.Main.invokeMain(Main.java:477)
    at org.eclipse.jetty.start.Main.start(Main.java:623)
    at org.eclipse.jetty.start.Main.parseCommandLine(Main.java:273)
    at org.eclipse.jetty.start.Main.main(Main.java:81)
Caused by:
java.lang.ClassNotFoundException: org.springframework.web.context.support.DefaultWebEnvironment
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:420)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:373)
    at org.springframework.web.servlet.HttpServletBean.(HttpServletBean.java:90)
    at org.springframework.web.servlet.FrameworkServlet.(FrameworkServlet.java:96)
    at org.springframework.web.servlet.DispatcherServlet.(DispatcherServlet.java:128)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at org.eclipse.jetty.servlet.ServletContextHandler$Context.createServlet(ServletContextHandler.java:606)
    at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:748)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:426)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:763)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:245)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1158)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:587)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:436)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36)
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:180)
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:482)
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:137)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:50)
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:601)
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:531)
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:394)
    at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:329)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:114)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:543)
    at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:218)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:41)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:50)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:94)
    at org.eclipse.jetty.server.Server.doStart(Server.java:253)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:58)
    at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1220)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1143)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.eclipse.jetty.start.Main.invokeMain(Main.java:477)
    at org.eclipse.jetty.start.Main.start(Main.java:623)
    at org.eclipse.jetty.start.Main.parseCommandLine(Main.java:273)
    at org.eclipse.jetty.start.Main.main(Main.java:81)
2013-04-24 18:52:59.654:INFO::Deployable added: /home/manooja/jetty-hightide-7.4.0.v20110414/webapps/root
2013-04-24 18:52:59.849:INFO::started o.e.j.w.WebAppContext{/,file:/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/root/},/home/manooja/jetty-hightide-7.4.0.v20110414/webapps/root
2013-04-24 18:52:59.861:INFO::Deployment monitor /home/manooja/jetty-hightide-7.4.0.v20110414/contexts at interval 1
2013-04-24 18:52:59.950:INFO::Started SelectChannelConnector@0.0.0.0:9080 STARTING

Kindly note that the default port have been changed to 9080.

I have an inkling that it might be some configuration change, as it is working fine in one machine.
Could you please help me with a guidance to solve this?

java -jar start.jar --version

    Active Options: [Server, client, ext, jmx, jsp, resources, websocket]
    Version Information on 25 entries in the classpath.
    Note: order presented here is how they would appear on the classpath.
          changes to the OPTIONS=[option,option,...] command line option will be reflected here.
     0:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-xml-9.0.2.v20130417.jar
     1:  3.0.0.v201112011016 | ${jetty.home}/lib/servlet-api-3.0.jar
     2:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-http-9.0.2.v20130417.jar
     3:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-continuation-9.0.2.v20130417.jar
     4:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-server-9.0.2.v20130417.jar
     5:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-security-9.0.2.v20130417.jar
     6:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-servlet-9.0.2.v20130417.jar
     7:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-webapp-9.0.2.v20130417.jar
     8:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-deploy-9.0.2.v20130417.jar
     9:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-client-9.0.2.v20130417.jar
    10:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-jmx-9.0.2.v20130417.jar
    11:  2.2.0.v201303151357 | ${jetty.home}/lib/jsp/com.sun.el-2.2.0.v201303151357.jar
    12:  2.2.0.v201303151357 | ${jetty.home}/lib/jsp/javax.el-2.2.0.v201303151357.jar
    13:  1.2.0.v201105211821 | ${jetty.home}/lib/jsp/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar
    14:  2.2.0.v201112011158 | ${jetty.home}/lib/jsp/javax.servlet.jsp-2.2.0.v201112011158.jar
    15:  2.2.2.v201112011158 | ${jetty.home}/lib/jsp/org.apache.jasper.glassfish-2.2.2.v201112011158.jar
    16:  1.2.0.v201112081803 | ${jetty.home}/lib/jsp/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar
    17: 3.8.2.v20130121-145325 | ${jetty.home}/lib/jsp/org.eclipse.jdt.core-3.8.2.v20130121.jar
    18:                (dir) | ${jetty.home}/resources
    19:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-api-9.0.2.v20130417.jar
    20:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-common-9.0.2.v20130417.jar
    21:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-server-9.0.2.v20130417.jar
    22:      9.0.2.v20130417 | ${jetty.home}/lib/websocket/websocket-servlet-9.0.2.v20130417.jar
    23:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-util-9.0.2.v20130417.jar
    24:      9.0.2.v20130417 | ${jetty.home}/lib/jetty-io-9.0.2.v20130417.jar

dir ./WEB-INF/lib/

antlr-2.7.6.jar
aopalliance-1.0.jar
bcprov-jdk15on-148.jar
c3p0-0.9.1.jar
commons-collections-3.2.1.jar
commons-dbcp-1.3.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
commons-pool-1.5.4.jar
cpewebapp.jar
displaytag-1.2.jar
dom4j-1.6.1.jar
gson-1.6.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-core-3.6.4.Final.jar
hibernate-entitymanager-3.6.4.Final.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate-validator-4.2.0.Final.jar
jackson-core-asl-1.8.0.jar
jackson-mapper-asl-1.8.0.jar
javassist-3.12.0.GA.jar
json.jar
jta.jar
log4j-1.2.16.jar
servlet-2.3.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
spring-aop-3.1.0.RELEASE.jar
spring-asm-3.1.0.RELEASE.jar
spring-beans-3.1.0.RELEASE.jar
spring-context-3.1.0.RELEASE.jar
spring-context-support-3.1.0.RELEASE.jar
spring-core-3.1.0.RELEASE.jar
spring-expression-3.1.0.RELEASE.jar
spring-jdbc-3.1.0.RELEASE.jar
spring-ldap-core-1.3.0.RELEASE.jar
spring-ldap-core-tiger-1.3.0.RELEASE.jar
spring-orm-3.1.0.RELEASE.jar
spring-oxm-3.1.0.RELEASE.jar
spring-security-config-3.1.0.RELEASE.jar
spring-security-core-3.1.0.RELEASE.jar
spring-security-ldap-3.1.0.RELEASE.jar
spring-security-web-3.1.0.RELEASE.jar
spring-tx-3.1.0.RELEASE.jar
spring-web-3.1.0.RELEASE.jar
spring-webmvc-3.1.0.M1.jar
spring-web-servlet-3.1.0.RELEASE.jar
sqlite-jdbc-3.7.2.jar
velocity-1.6.2.jar
velocity-tools-view-2.0.jar


问:
How do I convert a string into an f-string?
I was reading this blog post on Python's new f-strings and they seem really neat.  However, I want to be able to load an f-string from a string or file.

I can't seem to find any string method or other function that does this.

From the example in the blog post:

```<code>name = 'Fred'
age = 42
f"My name is {name} and I am {age} years old"

'My name is Fred and I am 42 years old'
</code>```

But what if I had a string s?  I want to be able to eff-ify s, something like this:

```<code>name = 'Fred'
age = 42
s = "My name is {name} and I am {age} years old"
effify(s)
</code>```

It turns out I can already perform something similar to str.format and garner the performance pick up.  Namely:

```<code>format = lambda name, age: f"My name is {name} and I am {age} years old"
format('Ted', 12)

'My name is Ted and I am 12 years old'
</code>```

答:
But what if I had a string s? I want to be able to eff-ify s, something like this:

```<code>name = 'Fred'
age = 42
s = "My name is {name} and I am {age} years old"
effify(s)
</code>```

AFAIU, According to PEP 498 -- Literal String Interpolation, this isn't possible1. There's no way to programmatically create an f-string:

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.

1Unless of course, you'd be willing to use something like exec as @coldspeed mentioned. But at that point, the cons probably outweigh the pros.

Body:
I was reading this blog post on Python's new f-strings and they seem really neat.  However, I want to be able to load an f-string from a string or file.

I can't seem to find any string method or other function that does this.

From the example in the blog post:

name = 'Fred'
age = 42
f"My name is {name} and I am {age} years old"

'My name is Fred and I am 42 years old'

But what if I had a string s?  I want to be able to eff-ify s, something like this:

name = 'Fred'
age = 42
s = "My name is {name} and I am {age} years old"
effify(s)

It turns out I can already perform something similar to str.format and garner the performance pick up.  Namely:

format = lambda name, age: f"My name is {name} and I am {age} years old"
format('Ted', 12)

'My name is Ted and I am 12 years old'

Body:
But what if I had a string s? I want to be able to eff-ify s, something like this:

name = 'Fred'
age = 42
s = "My name is {name} and I am {age} years old"
effify(s)

AFAIU, According to PEP 498 -- Literal String Interpolation, this isn't possible1. There's no way to programmatically create an f-string:

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.

1Unless of course, you'd be willing to use something like exec as @coldspeed mentioned. But at that point, the cons probably outweigh the pros.


问:
comparing current time simTime.dbl() with a previously stored double value doesn't always give the correct answer... why?
double installedChannels[16][3] = {{1,868.1},{1,868.3},{1,868.5},{2,863.0}};

//and installedChannels[x][2] is dynamically changing with value of current time

if (installedChannels[i][2] <= simTime().dbl())
{
//do so and so. however sometime current simTime is equal to value stored in installedChannels[i][2]
//yet it never gets in this loop
}

答:
Did you check the comments for OMNeT's simtime dbl() function?

```<code>/**
 * Converts simulation time (in seconds) to a double. Note that conversion to
 * and from double may lose precision. We do not provide implicit conversion
 * to double as it would conflict with other overloaded operators, and would
 * cause ambiguities during compilation.
 */
</code>```

This loss of precision might be the case why comparisons against a value might not work.
If you want exact value comparisons, you need to use the simtime_t type (eventually the SimTime class).

Did you also check that your if-condition is actually checked at times where the entering into the loop is actually possible (does the if X == TRUE case actually occur)?

Body:
Did you check the comments for OMNeT's simtime dbl() function?

/**
 * Converts simulation time (in seconds) to a double. Note that conversion to
 * and from double may lose precision. We do not provide implicit conversion
 * to double as it would conflict with other overloaded operators, and would
 * cause ambiguities during compilation.
 */

This loss of precision might be the case why comparisons against a value might not work.
If you want exact value comparisons, you need to use the simtime_t type (eventually the SimTime class).

Did you also check that your if-condition is actually checked at times where the entering into the loop is actually possible (does the if X == TRUE case actually occur)?