问:
I want to know the versions that I need to use to run a java selenium code
When I ran a simple java selenium code to start faceboook application, I am getting error "Timed out waiting for driver server to start."

```<code>Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_211'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at newpackage.PractAuto.main(PractAuto.java:10)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:40026/status] to be available after 20002 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
    ... 9 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 10 more
</code>```

My Code:

```<code>package newpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class PractAuto {
    public static void main(String[] args) throws InterruptedException {
          System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
          WebDriver driver = new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.facebook.com/login/");
          Thread.sleep(5000);
          driver.findElement(By.name("email")).sendKeys("arunkumar3625@gmail.com");
          driver.findElement(By.name("pass")).sendKeys("Password");
          driver.findElement(By.id("loginbutton")).click();
          driver.findElement(By.name("mercurymessages")).click();
          driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();

    }
</code>```

Chrome browser is opening successfully but I'm getting the above error.

答:
Download latest chrome driver from https://www.seleniumhq.org/download/ and set property as :</p>

```<code>System.setProperty("webdriver.chrome.driver","location of latest chrome driver")
</code>```

Body:
When I ran a simple java selenium code to start faceboook application, I am getting error "Timed out waiting for driver server to start."

Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_211'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at newpackage.PractAuto.main(PractAuto.java:10)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:40026/status] to be available after 20002 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
    ... 9 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 10 more

My Code:

package newpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class PractAuto {
    public static void main(String[] args) throws InterruptedException {
          System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
          WebDriver driver = new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.facebook.com/login/");
          Thread.sleep(5000);
          driver.findElement(By.name("email")).sendKeys("arunkumar3625@gmail.com");
          driver.findElement(By.name("pass")).sendKeys("Password");
          driver.findElement(By.id("loginbutton")).click();
          driver.findElement(By.name("mercurymessages")).click();
          driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();

    }

Chrome browser is opening successfully but I'm getting the above error.

Body:
Download latest chrome driver from https://www.seleniumhq.org/download/ and set property as :

System.setProperty("webdriver.chrome.driver","location of latest chrome driver")


来源: stackexchange

问:
PHP strstr - The reverse method
I'm looking to get the same exact results as php strstr command (while it set to true) but in reverse order.

I know that I can simply reverse the string and use strstr and then reverse it again

but I was wonder if there is any internal php command for the task.

```<code><?php

$myString = 'We don\'t need no education';

echo strstr($myString, ' ', true);

/*
 * output :
 * We
 *
 * I'm expecting to get :
 * education
 *
 */

exit;

?>
</code>```

Very Simple !

答:
using str :</p>

```<code>$basename = strrev(substr(strchr(strrev($postfile_name),'.'),1));
//test.php will return test

$ext = strrchr( $postfile_name, '.' );
//test.php will return .php
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP strstr - The reverse method

Body:
I'm looking to get the same exact results as php strstr command (while it set to true) but in reverse order.

I know that I can simply reverse the string and use strstr and then reverse it again

but I was wonder if there is any internal php command for the task.

<?php

$myString = 'We don\'t need no education';

echo strstr($myString, ' ', true);

/*
 * output :
 * We
 *
 * I'm expecting to get :
 * education
 *
 */

exit;

?>

Very Simple !

Body:
using str :

$basename = strrev(substr(strchr(strrev($postfile_name),'.'),1));
//test.php will return test

$ext = strrchr( $postfile_name, '.' );
//test.php will return .php

ContentLicense: CC BY-SA 4.0


问:
Many to Many Relationship - how to query all children
I am using flask-sqlalchemy to implement many to many relationship. Tried many options but unable to query all children for a parent.

```<code>class Participant(db.Model):
    __tablename__='participant'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)
    name = db.Column(db.String(120), unique=False)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship("User")

    @staticmethod
    def get_by_user(user):
        return Participant.query.filter_by(user=user).first()

    def __repr__(self):
        return "(Participant '{}')".format(self.email)

    competitions = db.relationship("CompetitionParticipant", back_populates="participant")

class Competition(db.Model):
    __tablename__='competition'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)

    name=db.Column(db.String(100),unique=True)
    description=db.Column(db.String(255),unique=True)
    # type=db.Column(db.String(50))#Team,Individual,Practice,etc.
    start_date=db.Column(db.DateTime)
    end_date=db.Column(db.DateTime)
    result_date=db.Column(db.DateTime)

    participants = db.relationship('CompetitionParticipant', back_populates='competition')

    def __repr__(self):
        return "(Competition '{}')".format(self.name)

class CompetitionParticipant(db.Model):
    __tablename__='competition_participant'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)
    participant_id=db.Column(db.Integer, db.ForeignKey('participant.id'))
    competition_id=db.Column(db.Integer, db.ForeignKey('competition.id'))

    competition=db.relationship("Competition",back_populates="participants")
    participant=db.relationship("Participant",back_populates="competitions")

    def __repr__(self):
        return "(competition_id, participant_id '{},{}')".format(self.competition_id,self.participant_id)
</code>```

In this many to many relationship example how will I query all the competitions a participant is enrolled in?

I have tried following:

```<code>participant.competitions # returns relationship object
</code>```

everything else I tried was syntax error. What is right ORM way to extract all competitions a participant is enrolled in?

答:
Shouldn't you be able to do something like this if you wanted to find out about the participant with id=1:</p>

```<code>participant = Participant.query.get(1)
for item in participant.competitions:
       print(item.name)
</code>```

Body:
I am using flask-sqlalchemy to implement many to many relationship. Tried many options but unable to query all children for a parent.

class Participant(db.Model):
    __tablename__='participant'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)
    name = db.Column(db.String(120), unique=False)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship("User")

    @staticmethod
    def get_by_user(user):
        return Participant.query.filter_by(user=user).first()

    def __repr__(self):
        return "(Participant '{}')".format(self.email)

    competitions = db.relationship("CompetitionParticipant", back_populates="participant")

class Competition(db.Model):
    __tablename__='competition'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)

    name=db.Column(db.String(100),unique=True)
    description=db.Column(db.String(255),unique=True)
    # type=db.Column(db.String(50))#Team,Individual,Practice,etc.
    start_date=db.Column(db.DateTime)
    end_date=db.Column(db.DateTime)
    result_date=db.Column(db.DateTime)

    participants = db.relationship('CompetitionParticipant', back_populates='competition')

    def __repr__(self):
        return "(Competition '{}')".format(self.name)

class CompetitionParticipant(db.Model):
    __tablename__='competition_participant'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)
    participant_id=db.Column(db.Integer, db.ForeignKey('participant.id'))
    competition_id=db.Column(db.Integer, db.ForeignKey('competition.id'))

    competition=db.relationship("Competition",back_populates="participants")
    participant=db.relationship("Participant",back_populates="competitions")

    def __repr__(self):
        return "(competition_id, participant_id '{},{}')".format(self.competition_id,self.participant_id)

In this many to many relationship example how will I query all the competitions a participant is enrolled in?

I have tried following:

participant.competitions # returns relationship object

everything else I tried was syntax error. What is right ORM way to extract all competitions a participant is enrolled in?

Body:
Shouldn't you be able to do something like this if you wanted to find out about the participant with id=1:

participant = Participant.query.get(1)
for item in participant.competitions:
       print(item.name)


问:
Evaluate postfix using a stack in C++
```<code>#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);

    int operand1, operand2, result,number;
    stack<char>operation;

    stringstream temp;

    int i=0;
    while (i < input.length())
    {
        if (isdigit(input[i]))
        {
            operation.push(input[i]);
        }
        else
        {
            operand2 = operation.top();
            temp << operation.top();
            operation.pop();

            operand1 = operation.top();
            temp << operation.top();
            operation.pop();

            switch(operand1,operand2)
            {
                case '+': result=operand1 + operand2;
                break;

                case '-': result=operand1 - operand2;
                break;

                case '*': result=operand1 * operand2;
                break;

                case '/': result=operand1 / operand2;
                break;
            }
            operation.push(result);
        }
        i++;
    }
    cout << "The result is: "<<temp.str()<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return 0;
}
</code>```

I've changed the code and managed to obtain the "pop" value, but the operation didn't work.

答:
There are many things wrong with the code, starting with parsing of the input expression. The actual crash is most probably due to the fact that if you input something like "12+" you will push '1' and '2' into the stack (note: characters 1 and 2, not values 1 and 2!!!) and then try to extract two operands and an operator that you never inserted into the stack.

On parsing the input, you are reading character by character, and only using the first digit, the parsing is not able to handle spaces or any other separator... Try to break the problem in two: parsing and processing. The problem of parsing can be tackled by not using the actual values read, but just printing them (or storing in some form and then printing the whole read expression), and can be a first step. Ensure that the parser is able to deal with common expressions like "1 2 +", "10 20 +", "1 2+", " 1 2 + " (note the different positions of spaces) in a robust way. And that it fails gracefully to parse expressions like " +", "1 +", "1 2 ++"... You can never trust user input, they will make mistakes and that should not bring your program to its knees.

Once you are sure that you are able to parse the input, start on the actual algorithm. Make it robust against invalid user inputs that you might have not been able to tackle before, like "10 0 /" and do the actual processing.

Learn to use the debugger, it will help you understand when things go south what are the reasons. The debugger would take less than one second to point at the specific problem in your code above, it will not tell you why it died, but it will show you how it died and what the state of the program was there. If my hunch is correct, then it will point you at the operation.top() instruction as the culprit, and you will be able to see that you were trying to extract more elements than were inserted. Execute a part of your program step by step to understand what it is actually doing, and you will notice that when you read "12+" you are actually storing two seemingly unrelated integers into the stack (the ASCII values of '1' and '2'...

Title: Evaluate postfix using a stack in C++

Body:
#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);

    int operand1, operand2, result,number;
    stack<char>operation;

    stringstream temp;

    int i=0;
    while (i < input.length())
    {
        if (isdigit(input[i]))
        {
            operation.push(input[i]);
        }
        else
        {
            operand2 = operation.top();
            temp << operation.top();
            operation.pop();

            operand1 = operation.top();
            temp << operation.top();
            operation.pop();

            switch(operand1,operand2)
            {
                case '+': result=operand1 + operand2;
                break;

                case '-': result=operand1 - operand2;
                break;

                case '*': result=operand1 * operand2;
                break;

                case '/': result=operand1 / operand2;
                break;
            }
            operation.push(result);
        }
        i++;
    }
    cout << "The result is: "<<temp.str()<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return 0;
}

I've changed the code and managed to obtain the "pop" value, but the operation didn't work.


问:
React-native google signin gives Developer Error
I am trying Google login using React-native-google-signin plugin but it gives me a Developer_Error.I have done exctly same as mention in its document.here is my code ans steps.

1.Installed react-native-google-signin plugin using npm i react-native-google-signin.
2.Then have linked it with react-native link react-native-google-signin
3.After that i did setup of build.gradle file as they mention it in the documents.

```<code>    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
        googlePlayServicesAuthVersion = "15.0.1"
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:3.2.1'
    }
    allprojects {
        repositories {
                mavenLocal()
                google()
                maven {url "https://maven.google.com"}
                jcenter()
                maven {
                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                url "$rootDir/../node_modules/react-native/android"
                }
                maven {
                    url 'https://maven.google.com/'
                    name 'Google'
                }
        }
    }
</code>```

4.Updated android/app/build.gradle,

```<code>    dependencies {

        implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
        implementation project(':react-native-fbsdk')
        compile project(':react-native-vector-icons')
        compile project(':react-native-fused-location')
        compile project(':react-native-fs')
        compile project(':react-native-image-resizer')
        compile project(':react-native-geocoder')
        compile project(':react-native-device-info')
        compile project(':react-native-image-picker')
        compile fileTree(dir: "libs", include: ["*.jar"])
        compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
        compile "com.facebook.react:react-native:+"  // From node_modules
        implementation project(":react-native-google-signin")
        compile (project(':react-native-maps')){
            exclude group: "com.google.android.gms"
        }
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.google.android.gms:play-services-maps:15.0.1'
        implementation 'com.google.android.gms:play-services-location:15.0.1'
        implementation 'com.google.android.gms:play-services-base:15.0.1'

    }

    task copyDownloadableDepsToLibs(type: Copy) {
        from configurations.compile
        into 'libs'
    }
    apply plugin: 'com.google.gms.google-services'
</code>```

5.Then generate SHA1 key using android studion debug.keystore and generate google-services.json file in firebase.

6.Then setting up login.js page like this.

```<code>    async componentDidMount() {
        this._configureGoogleSignIn();

    }
    _configureGoogleSignIn() {
        GoogleSignin.configure({
            webClientId: '775060548127-5nfj43q15l75va9pfav2jettkha7hm2a.apps.googleusercontent.com',// my clientID
            offlineAccess: false
        });
    }
    async GoogleSignin() {
    try {
        await GoogleSignin.hasPlayServices();
        const userInfo = await GoogleSignin.signIn();
        // this.setState({ userInfo, error: null });
        Alert.alert("success:" + JSON.stringify(userInfo));

    } catch (error) {
        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            // sign in was cancelled
            Alert.alert('cancelled');
        } else if (error.code === statusCodes.IN_PROGRESS) {
            // operation in progress already
            Alert.alert('in progress');
        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            Alert.alert('play services not available or outdated');
        } else {
            Alert.alert('Something went wrong', error.toString());
            this.setState({
                error,
            });
        }
    }
}
</code>```

These are my details so please someone help me on this i cannot find the appropriate solution online.and yes my SHA1 and clientID is correct i have cheked it already.

答:
I had this problem too and trawled through many answers saying check your client Id and key hash, both of which I was positive were right.

The thing that got it working for me was I opened OAuth identities in the project management console (not Firebase) at https://console.cloud.google.com/apis/credentials and added an Android Oauth client Id with the correct signature (I did not have one of these there prior for some reason). Redownload the GoogleServices json file.

I also needed to set the webClientId to the "client_type": 3 Oauth client ID. It then worked.

Body:
I am trying Google login using React-native-google-signin plugin but it gives me a Developer_Error.I have done exctly same as mention in its document.here is my code ans steps.

1.Installed react-native-google-signin plugin using npm i react-native-google-signin.
2.Then have linked it with react-native link react-native-google-signin
3.After that i did setup of build.gradle file as they mention it in the documents.

    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
        googlePlayServicesAuthVersion = "15.0.1"
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:3.2.1'
    }
    allprojects {
        repositories {
                mavenLocal()
                google()
                maven {url "https://maven.google.com"}
                jcenter()
                maven {
                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                url "$rootDir/../node_modules/react-native/android"
                }
                maven {
                    url 'https://maven.google.com/'
                    name 'Google'
                }
        }
    }

4.Updated android/app/build.gradle,

    dependencies {

        implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
        implementation project(':react-native-fbsdk')
        compile project(':react-native-vector-icons')
        compile project(':react-native-fused-location')
        compile project(':react-native-fs')
        compile project(':react-native-image-resizer')
        compile project(':react-native-geocoder')
        compile project(':react-native-device-info')
        compile project(':react-native-image-picker')
        compile fileTree(dir: "libs", include: ["*.jar"])
        compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
        compile "com.facebook.react:react-native:+"  // From node_modules
        implementation project(":react-native-google-signin")
        compile (project(':react-native-maps')){
            exclude group: "com.google.android.gms"
        }
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.google.android.gms:play-services-maps:15.0.1'
        implementation 'com.google.android.gms:play-services-location:15.0.1'
        implementation 'com.google.android.gms:play-services-base:15.0.1'

    }

    task copyDownloadableDepsToLibs(type: Copy) {
        from configurations.compile
        into 'libs'
    }
    apply plugin: 'com.google.gms.google-services'

5.Then generate SHA1 key using android studion debug.keystore and generate google-services.json file in firebase.

6.Then setting up login.js page like this.

    async componentDidMount() {
        this._configureGoogleSignIn();

    }
    _configureGoogleSignIn() {
        GoogleSignin.configure({
            webClientId: '775060548127-5nfj43q15l75va9pfav2jettkha7hm2a.apps.googleusercontent.com',// my clientID
            offlineAccess: false
        });
    }
    async GoogleSignin() {
    try {
        await GoogleSignin.hasPlayServices();
        const userInfo = await GoogleSignin.signIn();
        // this.setState({ userInfo, error: null });
        Alert.alert("success:" + JSON.stringify(userInfo));

    } catch (error) {
        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            // sign in was cancelled
            Alert.alert('cancelled');
        } else if (error.code === statusCodes.IN_PROGRESS) {
            // operation in progress already
            Alert.alert('in progress');
        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            Alert.alert('play services not available or outdated');
        } else {
            Alert.alert('Something went wrong', error.toString());
            this.setState({
                error,
            });
        }
    }
}

These are my details so please someone help me on this i cannot find the appropriate solution online.and yes my SHA1 and clientID is correct i have cheked it already.


问:
Milliseconds in Lap Time Average dropping the Zero in Tenths place
I am using code I found on this site to average lap times in MM:SS.mmm (Averaging Times using Javascript)

It works great until the result has a zero in the tenths place. For example, the result should be 01:00.096 however, the zero is dropped and the answer is 01:00.96

I have simplified the input of 'times' to highlight the problem.

I have looked at different formatting issues, tried converting the strings to numbers and I've looked at the offsetify function thinking it was somehow interpreting the milliseconds incorrectly.

I am a novice at JavaScript with no formal training but enjoy hobby-programming.  I have learned a lot from the examples on this site for use in my own little apps.

```<code>var times = ['01:00.096'];
var date = 0
var result = '';

function offsetify(t)
{
    return t < 10 ? '0' + t : t;
}

for(var x = 0; x < times.length; x++ ) {
    var tarr = times[x].split(':');
    date += new Date(0, 0, 0, 0, tarr[0], tarr[1].split('.')[0], tarr[1].split('.')[1]).getTime();
}
var avg = new Date(date/times.length);
result = offsetify(avg.getMinutes()) + ':' + offsetify(avg.getSeconds()) + '.' + offsetify(avg.getMilliseconds());
</code>```

答:
The reason you see the 0 dropping is because in the offsetify function you have

```<code>return t < 10 ? '0' + t : t;
</code>```

and you are passing it the value 96, which is not less than 10, so the function returns 96.

If you are able to find a datetime-formatting library like date-fns or moment, and you should use one, then great! Let the library do the work for you.

If you would like the practice, which is great for learning, use

```<code>s.padStart(3, '0')
</code>```

for milliseconds, and

```<code>s.padStart(2, '0')
</code>```

for minutes. For example, for your milliseconds:

```<code>> "5".padStart(3, "0")
'005'
> "55".padStart(3, "0")
'055'
> "383".padStart(3, "0")
'383'
</code>```

Body:
I am using code I found on this site to average lap times in MM:SS.mmm (Averaging Times using Javascript)

It works great until the result has a zero in the tenths place. For example, the result should be 01:00.096 however, the zero is dropped and the answer is 01:00.96

I have simplified the input of 'times' to highlight the problem.

I have looked at different formatting issues, tried converting the strings to numbers and I've looked at the offsetify function thinking it was somehow interpreting the milliseconds incorrectly.

I am a novice at JavaScript with no formal training but enjoy hobby-programming.  I have learned a lot from the examples on this site for use in my own little apps.

var times = ['01:00.096'];
var date = 0
var result = '';

function offsetify(t)
{
    return t < 10 ? '0' + t : t;
}

for(var x = 0; x < times.length; x++ ) {
    var tarr = times[x].split(':');
    date += new Date(0, 0, 0, 0, tarr[0], tarr[1].split('.')[0], tarr[1].split('.')[1]).getTime();
}
var avg = new Date(date/times.length);
result = offsetify(avg.getMinutes()) + ':' + offsetify(avg.getSeconds()) + '.' + offsetify(avg.getMilliseconds());

Body:
The reason you see the 0 dropping is because in the offsetify function you have

return t < 10 ? '0' + t : t;

and you are passing it the value 96, which is not less than 10, so the function returns 96.

If you are able to find a datetime-formatting library like date-fns or moment, and you should use one, then great! Let the library do the work for you.

If you would like the practice, which is great for learning, use

s.padStart(3, '0')

for milliseconds, and

s.padStart(2, '0')

for minutes. For example, for your milliseconds:

> "5".padStart(3, "0")
'005'
> "55".padStart(3, "0")
'055'
> "383".padStart(3, "0")
'383'


问:
How to show warning message when back button is pressed in fragments
I want application to show warning message when user press back button and if user select Yes it will go back. And i am in navigation graph fragment.

I have searched many time in stack Overflow and tried:

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Save Or Not");
    builder.setMessage("Do you want to save this? ");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            /*Go back:-I dont know how*/
        }
    });
    builder.setNegativeButton("Discard",null);
    builder.show();
}
</code>```

But it is showing giver error:
Method does not override method from its superclass

Edit:
I want to set onBackPressedListener(Mobiles back button) in Navigation graphs fragment

答:
```<code>builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                   //Replace Your Own Action Like Adding Toast etc and Also SuperOnbackprssed or any overriden method
                    dialog.cancel();

                }
            });
</code>```

Body:
I want application to show warning message when user press back button and if user select Yes it will go back. And i am in navigation graph fragment.

I have searched many time in stack Overflow and tried:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Save Or Not");
    builder.setMessage("Do you want to save this? ");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            /*Go back:-I dont know how*/
        }
    });
    builder.setNegativeButton("Discard",null);
    builder.show();
}

But it is showing giver error:
Method does not override method from its superclass

Edit:
I want to set onBackPressedListener(Mobiles back button) in Navigation graphs fragment


问:
How to unit test to check the format of a datetime?
My android app gives the option to select a date and a time and then it is formatted to a string with the format "MM/DD/YYYY HH:mm". This string is then stored in the database.

I am trying to create a unit test that tests that the date and time are stored in the correct format but I am struggling to find the correct method to do so. I have tried this

```<code>@Test
public void testDateTimeFormat() {
    DateActivity dateActivity = new DateActivity();
    Calendar currentDateTime = Calendar.getInstance();
    Assert.assertEquals( dateActivity.showDateTime(currentDateTime), "MM/DD/YYYY HH:mm");
</code>```

The method showDateTime is fed the current date and time and it should return it in the correct format. I tried using assert equals to compare these two to show that it is in the correct format but it doesn't seem to compare it properly, it just says that they are not the same, it isn't detecting the formatting of the MM/DD/YYYY HH:mm. Not sure how I can construct this test properly

答:
I hope this will work for you.

Create the below method in your activity.

```<code>public boolean checkDateFormat(String s) {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/YYYY HH:MM");
        Date date1 = new Date(s);
        s = formatter.format(date1);
        Date date = new Date();

        String strDate = formatter.format(date);
        System.out.println(strDate);
        System.out.println(s);

        if (s.equals(strDate)) {
            return true;
        } else {
            return false;
        }
    }
</code>```

and unit test code is given below

```<code> @Test
    public void isDateFormat() throws Exception {
        assertEquals(new MainActivity().checkDateFormat("27/05/2019 10:06"),true);
    }
</code>```

If you provided string is matched then test will pass and if not then it will fail.

assertEquals(new MainActivity().checkDateFormat("28/05/2019 10:06"),true);

test: Fail

assertEquals(new MainActivity().checkDateFormat("05/27/2019 10:06"),true);

test: True

Body:
My android app gives the option to select a date and a time and then it is formatted to a string with the format "MM/DD/YYYY HH:mm". This string is then stored in the database.

I am trying to create a unit test that tests that the date and time are stored in the correct format but I am struggling to find the correct method to do so. I have tried this

@Test
public void testDateTimeFormat() {
    DateActivity dateActivity = new DateActivity();
    Calendar currentDateTime = Calendar.getInstance();
    Assert.assertEquals( dateActivity.showDateTime(currentDateTime), "MM/DD/YYYY HH:mm");

The method showDateTime is fed the current date and time and it should return it in the correct format. I tried using assert equals to compare these two to show that it is in the correct format but it doesn't seem to compare it properly, it just says that they are not the same, it isn't detecting the formatting of the MM/DD/YYYY HH:mm. Not sure how I can construct this test properly

Body:
I hope this will work for you.

Create the below method in your activity.

public boolean checkDateFormat(String s) {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/YYYY HH:MM");
        Date date1 = new Date(s);
        s = formatter.format(date1);
        Date date = new Date();

        String strDate = formatter.format(date);
        System.out.println(strDate);
        System.out.println(s);

        if (s.equals(strDate)) {
            return true;
        } else {
            return false;
        }
    }

and unit test code is given below

 @Test
    public void isDateFormat() throws Exception {
        assertEquals(new MainActivity().checkDateFormat("27/05/2019 10:06"),true);
    }

If you provided string is matched then test will pass and if not then it will fail.

assertEquals(new MainActivity().checkDateFormat("28/05/2019 10:06"),true);

test: Fail

assertEquals(new MainActivity().checkDateFormat("05/27/2019 10:06"),true);

test: True


问:
Python program calculates change
the program calculates change of stock of coins. Then it request for the price of an item to be purchased. If a price is input, it will prompt for dollars in payment and print the change  of coins.

I have tried the following code below:

```<code>quarters = 10
dimes = 10
nickels = 10
pennies = 10

quarters_spent = 0
dimes_spent = 0
nickels_spent = 0
pennies_spent = 0

print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(quarters, dimes, nickels, pennies))
in_str = input("Enter the purchase price (xx.xx) or 'q' to quit: ")
while in_str.lower() != 'q':
    dollar_str, cents_str = in_str.split(".")

in_int = int(float(in_str)*100)

if in_int < 0:
    print("Error: purchase price must be non-negative.")
    in_str = input("\nEnter the purchase price (xx.xx) or 'q' to quit: ")
if in_int > 0:
    payment = input("\nInput dollars paid: ")
    payment_int = int(float(payment)*100)

if payment_int < in_int:
    print("Error: print again.")
    payment = input("\nInput dollars paid: ")
    payment_int = int(float(payment)*100)
    change = payment_int - in_int

if change == 0:
    print("No change.")

while change >= 25 and quarters > 0:
    change -= 25
    quarters_spent += 1
    quarters -= 1

while change >= 10 and dimes > 0:
    change -= 10
    dimes_spent += 1
    dimes -= 1

while change >= 5 and nickels > 0:
    change -= 5
    nickels_spent += 1
    nickels -= 1

while change >= 1 and pennies > 0:
    change -= 1
    pennies_spent += 1
    pennies -= 1

if quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
    print("Error: ran out of coins.")
    quit()

print("\nCollect Payment Below:")
  if quarters > 0:
    print(quarters_spent, "quarters")
if dimes > 0:
    print(dimes_spent, "dimes")
if nickels > 0:
    print(nickels_spent, "nickels")
if pennies > 0:
    print(pennies_spent, "pennies")

print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(quarters, dimes, nickels, pennies))

in_str = input("\nEnter the purchase price (xx.xx) or 'q' to quit: ")
</code>```

Inputs:
1.5
2
q
I expected the Output:
8 q, 10 d, 10 n, and 10 p

The actual result:
The program does not run, it asked for "Enter the purchase price (xx.xx) or 'q' to quit:" and then nothing happens. The program does not runs at all after asking the phrase.

答:
if the input is not Q or q your loop will be infinite:

```<code>while in_str.lower() != 'q':
    dollar_str, cents_str = in_str.split(".")
</code>```

fix: also allow the other acceptable input or re-request input within the loop.

Title: Python program calculates change

Body:
the program calculates change of stock of coins. Then it request for the price of an item to be purchased. If a price is input, it will prompt for dollars in payment and print the change  of coins.

I have tried the following code below:

quarters = 10
dimes = 10
nickels = 10
pennies = 10

quarters_spent = 0
dimes_spent = 0
nickels_spent = 0
pennies_spent = 0

print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(quarters, dimes, nickels, pennies))
in_str = input("Enter the purchase price (xx.xx) or 'q' to quit: ")
while in_str.lower() != 'q':
    dollar_str, cents_str = in_str.split(".")

in_int = int(float(in_str)*100)

if in_int < 0:
    print("Error: purchase price must be non-negative.")
    in_str = input("\nEnter the purchase price (xx.xx) or 'q' to quit: ")
if in_int > 0:
    payment = input("\nInput dollars paid: ")
    payment_int = int(float(payment)*100)

if payment_int < in_int:
    print("Error: print again.")
    payment = input("\nInput dollars paid: ")
    payment_int = int(float(payment)*100)
    change = payment_int - in_int

if change == 0:
    print("No change.")

while change >= 25 and quarters > 0:
    change -= 25
    quarters_spent += 1
    quarters -= 1

while change >= 10 and dimes > 0:
    change -= 10
    dimes_spent += 1
    dimes -= 1

while change >= 5 and nickels > 0:
    change -= 5
    nickels_spent += 1
    nickels -= 1

while change >= 1 and pennies > 0:
    change -= 1
    pennies_spent += 1
    pennies -= 1

if quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
    print("Error: ran out of coins.")
    quit()

print("\nCollect Payment Below:")
  if quarters > 0:
    print(quarters_spent, "quarters")
if dimes > 0:
    print(dimes_spent, "dimes")
if nickels > 0:
    print(nickels_spent, "nickels")
if pennies > 0:
    print(pennies_spent, "pennies")

print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(quarters, dimes, nickels, pennies))

in_str = input("\nEnter the purchase price (xx.xx) or 'q' to quit: ")

Inputs:
1.5
2
q
I expected the Output:
8 q, 10 d, 10 n, and 10 p

The actual result:
The program does not run, it asked for "Enter the purchase price (xx.xx) or 'q' to quit:" and then nothing happens. The program does not runs at all after asking the phrase.

Body:
if the input is not Q or q your loop will be infinite:

while in_str.lower() != 'q':
    dollar_str, cents_str = in_str.split(".")

fix: also allow the other acceptable input or re-request input within the loop.


问:
Execution flow when using task.Wait in c#
I have a sample code as below which has logic to cancel task beyond 30 mins.

Method1 calls Method2 and Method3 which takes 15 mins and 10 mins to complete respectively.I have given a buffer of 5 mins and set the timeout limit for over all execution as 30 mins.

```<code>public class Program
{
    static void Main()
    {
        Program p = new Program();
        var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(0.5));
        var token = tokenSource.Token;
        var task = Task.Factory.StartNew(() => {
            p.Method1(token);
        }, token);

        try
        {
            task.Wait();
        }
        catch (AggregateException e)
        {
            Console.WriteLine("Method1 did not finish within 1 mins :" + DateTime.Now);
        }
        finally
        {
            tokenSource.Dispose();
        }
        Console.ReadLine();
    }
    public bool Method1(CancellationToken token)
    {
        Console.WriteLine("Inside Method1 :" + DateTime.Now);
        Method2(token);
        return true;
    }
    public bool Method2(CancellationToken token)
    {
        try
        {
            token.ThrowIfCancellationRequested();

            Console.WriteLine("Inside Method2 begin :" + DateTime.Now);
            Thread.Sleep(60000); // In the actual code , this line is replaced with the line which executes for more than 1 min.To replicate it, I just made the Thread to sleep.
            if (token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
            }
            Console.WriteLine("Inside Method2 end :" + DateTime.Now);
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in Method2");
            return false;

        }
    }
}
</code>```

Now the problem I'm facing is, the execution order in which the methods are executed is different from what I exepected when the overall execution is taking more than 30 mins.Say suppose Method 2 execution is taking more time to finish.

Expectation :

Inside Method1

    Inside Method2

  Exception in Method2

  Method1 did not finish within 30 mins

Reality :

Inside Method1

  Inside Method2

   Exception in Method2

What changes needs to be done to make the execution flow as expected. Is it even possible?

In this sample I have given only example of Method2. In reality there are 3-4 methods which performs some typical operations. Either one of them can take time to execute. So putting timeout only for Method2 doesn't solve the problem.

EDIT2

I have removed the old code and replaced with what was suggested in the answers to avoid any confusion. Here what I have done is made the thread is sleep for 1 min, where as the timeout is just 30 seconds. Here what is happening is, when the execution comes at Thread.Sleep, it is waiting for 60 seconds and then throwing an exception. I want it to throw exception as soon as the 30 seconds is up.

答:
The code in Method2 continues to execute even after your timeout fires - there's nothing that automatically stops it or causes it to throw an exception. What you want to do is called cancellation: you want the timeout to activate a signal that Method2 can occasionally check so that it can wrap up what it is doing or throw an exception if the timeout fires.

Instead of supplying a timeout to Wait, create a timeout-based CancellationTokenSource with new CancellationTokenSource(TimeSpan.FromMinutes(30)) and pass its token down into all of the methods running in the task. Those methods can then pass the token into any async methods they call and/or use the methods/properties on the token to see if the timeout has fired. See here.

Body:
I have a sample code as below which has logic to cancel task beyond 30 mins.

Method1 calls Method2 and Method3 which takes 15 mins and 10 mins to complete respectively.I have given a buffer of 5 mins and set the timeout limit for over all execution as 30 mins.

public class Program
{
    static void Main()
    {
        Program p = new Program();
        var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(0.5));
        var token = tokenSource.Token;
        var task = Task.Factory.StartNew(() => {
            p.Method1(token);
        }, token);

        try
        {
            task.Wait();
        }
        catch (AggregateException e)
        {
            Console.WriteLine("Method1 did not finish within 1 mins :" + DateTime.Now);
        }
        finally
        {
            tokenSource.Dispose();
        }
        Console.ReadLine();
    }
    public bool Method1(CancellationToken token)
    {
        Console.WriteLine("Inside Method1 :" + DateTime.Now);
        Method2(token);
        return true;
    }
    public bool Method2(CancellationToken token)
    {
        try
        {
            token.ThrowIfCancellationRequested();

            Console.WriteLine("Inside Method2 begin :" + DateTime.Now);
            Thread.Sleep(60000); // In the actual code , this line is replaced with the line which executes for more than 1 min.To replicate it, I just made the Thread to sleep.
            if (token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
            }
            Console.WriteLine("Inside Method2 end :" + DateTime.Now);
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in Method2");
            return false;

        }
    }
}

Now the problem I'm facing is, the execution order in which the methods are executed is different from what I exepected when the overall execution is taking more than 30 mins.Say suppose Method 2 execution is taking more time to finish.

Expectation :

Inside Method1

    Inside Method2

  Exception in Method2

  Method1 did not finish within 30 mins

Reality :

Inside Method1

  Inside Method2

   Exception in Method2

What changes needs to be done to make the execution flow as expected. Is it even possible?

In this sample I have given only example of Method2. In reality there are 3-4 methods which performs some typical operations. Either one of them can take time to execute. So putting timeout only for Method2 doesn't solve the problem.

EDIT2

I have removed the old code and replaced with what was suggested in the answers to avoid any confusion. Here what I have done is made the thread is sleep for 1 min, where as the timeout is just 30 seconds. Here what is happening is, when the execution comes at Thread.Sleep, it is waiting for 60 seconds and then throwing an exception. I want it to throw exception as soon as the 30 seconds is up.


问:
Swift: Keep mouse pointer from leaving window
I have a Mac SpriteKit / swift app (a game) where I need to keep the cursor within a window. or at least give some warning when it leaves the game window.

I already have a tracking area set up and am using the mouse to move a game paddle. But when the cursor moves outside the window, the paddle stops working.

```<code> let options = [ .mouseMoved,
                .activeAlways,
                .mouseEnteredAndExited] as NSTrackingArea.Options
let tracker = NSTrackingArea(rect:frame, options: options, owner:view, userInfo: nil)
view.addTrackingArea(tracker)
</code>```

The mouse entered and exited functions don't seem to fire

```<code>override func mouseExited(with event: NSEvent) {
   // NSCursor.unhide()
    print("_____________________EXIT")
   //Never fires

  }

  override func mouseEntered(with event: NSEvent) {
 //   NSCursor.hide()
    print("_____________________ENTER")
 // never fires

  }
</code>```

Any ideas ? Thanks

答:
I think you would be happier with a different solution: hide the cursor and disconnect mouse movement from the cursor position.

You can hide and show the pointer using CGDisplayHideCursor and CGDisplayShowCursor.

You can disconnect mouse movement from the cursor position (and reconnect it) using CGAssociateMouseAndMouseCursorPosition. When you receive mouseMoved and mouseDragged events while the mouse is disconnected from the cursor, you can read the mouse movement out of the deltaX and deltaY fields of the events.

Body:
I have a Mac SpriteKit / swift app (a game) where I need to keep the cursor within a window. or at least give some warning when it leaves the game window.

I already have a tracking area set up and am using the mouse to move a game paddle. But when the cursor moves outside the window, the paddle stops working.

 let options = [ .mouseMoved,
                .activeAlways,
                .mouseEnteredAndExited] as NSTrackingArea.Options
let tracker = NSTrackingArea(rect:frame, options: options, owner:view, userInfo: nil)
view.addTrackingArea(tracker)

The mouse entered and exited functions don't seem to fire

override func mouseExited(with event: NSEvent) {
   // NSCursor.unhide()
    print("_____________________EXIT")
   //Never fires

  }

  override func mouseEntered(with event: NSEvent) {
 //   NSCursor.hide()
    print("_____________________ENTER")
 // never fires

  }

Any ideas ? Thanks


问:
Will full memory barriers around std::shared_ptr's use_count() make it a reliable counter?
I'm implementing a thread-safe "lazy-synchronized" Set as a linked list of nodes connected by shared_ptr's. The algorithm is from "The Art of Multiprocessor Programming". I'm adding an is_empty() function that needs to be linearizable with the existing functions: contains(), add(), remove(). In the code below, you can see  remove  is a 2 step process. First it "lazy" marks the node by setting marked = nullptr, then it physically moves the linked list next pointers.

Modified classes to support is_empty()

template <class T>
class LazySet : public Set<T> {
    public:
      LazySet ();
      bool contains (const T&) const;
      bool is_empty ()         const;
      bool add      (const T&);
      bool remove   (const T&);
    private:
      bool validate(const std::shared_ptr<Node>&, const std::shared_ptr<Node>&);
      class Node;
      std::shared_ptr<Node> head;
      std::shared_ptr<bool> counter; //note: type is unimportant, will never change true/fase
};

template <class T>
class LazySet<T>::Node {
    public:
      Node ();
      Node (const T&);
      T key;
      std::shared_ptr<bool> marked; //assume initialized to = LazySet.counter
                                    // nullptr means it's marked; otherwise unmarked
      std::shared_ptr<Node> next;
      std::mutex mtx;
};
```

<p>Relevant modified methods to support is_empty</p>

<pre class="lang-cpp prettyprint-override"><code>template <class T>
bool LazySet<T>::remove(const T& k) {
    std::shared_ptr<Node> pred;
    std::shared_ptr<Node> curr;
    while (true) {
        pred = head;
        curr = atomic_load(&(head->next));
        //Find window where key should be in sorted list
        while ((curr) && (curr->key < k)) {
            pred = atomic_load(&curr);
            curr = atomic_load(&(curr->next));
        }
        //Aquire locks on the window, left to right locking prevents deadlock
        (pred->mtx).lock();
        if (curr) { //only lock if not nullptr
            (curr->mtx).lock();
        }
        //Ensure window didn't change before locking, and then remove
        if (validate(pred, curr)) {
            if (!curr) { //key doesn't exist, do nothing
                //## unimportant ##
            } else { //key exists, remove it
                atomic_store(&(curr->marked), nullptr); //logical "lazy" remove
                atomic_store(&(pred->next), curr->next) //physically remove
                (curr->mtx).unlock();
                (pred->mtx).unlock();
                return true;
            }
        } else {
            //## unlock and loop again ##
        }
    }
}

template <class T>
bool LazySet<T>::contains(const T& k) const {
    std::shared_ptr<Node> curr;
    curr = atomic_load(&(head->next));
    //Find window where key should be in sorted list
    while ((curr) && (curr->key < k)) {
        curr = atomic_load(&(curr->next));
    }
    //Check if key exists in window
    if (curr) {
        if (curr->key == k) { //key exists, unless marked
            return (atomic_load(&(curr->marked)) != nullptr);
        } else { //doesn't exist
            return false;
        }
    } else { //doesn't exist
        return false;
    }
}
</code>```

Node.marked was originally a plain bool, and LazySet.counter didn't exist. The choice to make them shared_ptrs was to be able to be able to atomically modify both a counter on the number of nodes and the lazy removal mark on the nodes. Modifying both simultaneously in remove() is necessary for is_empty() to be linearizable with contains(). (It can't be a separate bool mark and int counter without a double wide CAS or something.) I hope to implement the counter with shared_ptr's  use_count() function, but in multithreaded contexts it's only an approximation due to relaxed_memory_order.

I know standalone fences are usually bad practice, and I'm not too familiar with using them. But if I implemented is_empty like below, would the fences ensure it's no longer an approximation, but an exact value for a reliable counter?

template <class T>
bool LazySet<T>::is_empty() const {
    // ## SOME FULL MEMORY BARRIER
    if (counter.use_count() == 1) {
        // ## SOME FULL MEMORY BARRIER
        return true
    }
    // ## SOME FULL MEMORY BARRIER
    return false
}
```

I only ask because LWG Issue 2776 says:

We can't make  use_count()  reliable without adding substantially more fencing.

答:
Relaxed memory order isn't the problem here. use_count is not "reliable" because, by the time the value has been returned, it may have changed. There is no data race on getting the value itself, but there's nothing preventing that value from being modified before any conditional statement based on that value.

So you can't do anything with it which relies on its value still being meaningful (with the exception that, if you're still holding a shared_ptr instance, then the use count won't go to 0). The only way to make it reliable is to prevent it from being changed. So you'd need to have a mutex.

And that mutex would have to lock, not just around the use_count call and usage, but also every time you hand out one of these shared_ptrs that you're getting the use_count from.

Body:
I'm implementing a thread-safe "lazy-synchronized" Set as a linked list of nodes connected by shared_ptr's. The algorithm is from "The Art of Multiprocessor Programming". I'm adding an is_empty() function that needs to be linearizable with the existing functions: contains(), add(), remove(). In the code below, you can see  remove  is a 2 step process. First it "lazy" marks the node by setting marked = nullptr, then it physically moves the linked list next pointers.

Modified classes to support is_empty()

template <class T>
class LazySet : public Set<T> {
    public:
      LazySet ();
      bool contains (const T&) const;
      bool is_empty ()         const;
      bool add      (const T&);
      bool remove   (const T&);
    private:
      bool validate(const std::shared_ptr<Node>&, const std::shared_ptr<Node>&);
      class Node;
      std::shared_ptr<Node> head;
      std::shared_ptr<bool> counter; //note: type is unimportant, will never change true/fase
};

template <class T>
class LazySet<T>::Node {
    public:
      Node ();
      Node (const T&);
      T key;
      std::shared_ptr<bool> marked; //assume initialized to = LazySet.counter
                                    // nullptr means it's marked; otherwise unmarked
      std::shared_ptr<Node> next;
      std::mutex mtx;
};

Relevant modified methods to support is_empty

template <class T>
bool LazySet<T>::remove(const T& k) {
    std::shared_ptr<Node> pred;
    std::shared_ptr<Node> curr;
    while (true) {
        pred = head;
        curr = atomic_load(&(head->next));
        //Find window where key should be in sorted list
        while ((curr) && (curr->key < k)) {
            pred = atomic_load(&curr);
            curr = atomic_load(&(curr->next));
        }
        //Aquire locks on the window, left to right locking prevents deadlock
        (pred->mtx).lock();
        if (curr) { //only lock if not nullptr
            (curr->mtx).lock();
        }
        //Ensure window didn't change before locking, and then remove
        if (validate(pred, curr)) {
            if (!curr) { //key doesn't exist, do nothing
                //## unimportant ##
            } else { //key exists, remove it
                atomic_store(&(curr->marked), nullptr); //logical "lazy" remove
                atomic_store(&(pred->next), curr->next) //physically remove
                (curr->mtx).unlock();
                (pred->mtx).unlock();
                return true;
            }
        } else {
            //## unlock and loop again ##
        }
    }
}

template <class T>
bool LazySet<T>::contains(const T& k) const {
    std::shared_ptr<Node> curr;
    curr = atomic_load(&(head->next));
    //Find window where key should be in sorted list
    while ((curr) && (curr->key < k)) {
        curr = atomic_load(&(curr->next));
    }
    //Check if key exists in window
    if (curr) {
        if (curr->key == k) { //key exists, unless marked
            return (atomic_load(&(curr->marked)) != nullptr);
        } else { //doesn't exist
            return false;
        }
    } else { //doesn't exist
        return false;
    }
}

Node.marked was originally a plain bool, and LazySet.counter didn't exist. The choice to make them shared_ptrs was to be able to be able to atomically modify both a counter on the number of nodes and the lazy removal mark on the nodes. Modifying both simultaneously in remove() is necessary for is_empty() to be linearizable with contains(). (It can't be a separate bool mark and int counter without a double wide CAS or something.) I hope to implement the counter with shared_ptr's  use_count() function, but in multithreaded contexts it's only an approximation due to relaxed_memory_order.

I know standalone fences are usually bad practice, and I'm not too familiar with using them. But if I implemented is_empty like below, would the fences ensure it's no longer an approximation, but an exact value for a reliable counter?

template <class T>
bool LazySet<T>::is_empty() const {
    // ## SOME FULL MEMORY BARRIER
    if (counter.use_count() == 1) {
        // ## SOME FULL MEMORY BARRIER
        return true
    }
    // ## SOME FULL MEMORY BARRIER
    return false
}

I only ask because LWG Issue 2776 says:

We can't make  use_count()  reliable without adding substantially more fencing.


问:
Creating custom ErrorWebExceptionHandler fails
I am trying to create my own ErrorWebExceptionHandler in Spring Boot 2 by extending the default one but my application fails to start with the following message:

```<code>Caused by: java.lang.IllegalArgumentException: Property 'messageWriters' is required
at org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler.afterPropertiesSet(AbstractErrorWebExceptionHandler.java:214) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]
</code>```

My handler (Kotlin code):

```<code>@Component
@Order(-2)
class SampleErrorWebExceptionHandler(
    errorAttributes: ErrorAttributes?,
    resourceProperties: ResourceProperties?,
    errorProperties: ErrorProperties?,
    applicationContext: ApplicationContext?
) : DefaultErrorWebExceptionHandler(errorAttributes, resourceProperties, errorProperties, applicationContext) {

    override fun logError(request: ServerRequest, errorStatus: HttpStatus) {
        // do something
    }
}
</code>```

What could be the cause?

答:
Please try to add  dependency of ServerCodecConfigurer in your constructor

GlobalErrorWebExceptionHandler(
  ErrorAttributes errorAttributes,
  ResourceProperties resourceProperties,
  ApplicationContext applicationContext,
  ServerCodecConfigurer configurer
) {
    super(errorAttributes, resourceProperties, applicationContext);
    this.setMessageWriters(configurer.getWriters());
}
```

Body:
I am trying to create my own ErrorWebExceptionHandler in Spring Boot 2 by extending the default one but my application fails to start with the following message:

Caused by: java.lang.IllegalArgumentException: Property 'messageWriters' is required
at org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler.afterPropertiesSet(AbstractErrorWebExceptionHandler.java:214) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]

My handler (Kotlin code):

@Component
@Order(-2)
class SampleErrorWebExceptionHandler(
    errorAttributes: ErrorAttributes?,
    resourceProperties: ResourceProperties?,
    errorProperties: ErrorProperties?,
    applicationContext: ApplicationContext?
) : DefaultErrorWebExceptionHandler(errorAttributes, resourceProperties, errorProperties, applicationContext) {

    override fun logError(request: ServerRequest, errorStatus: HttpStatus) {
        // do something
    }
}

What could be the cause?


问:
BigDecimal request get Parameter (String cannot be be converted in BigDecimal)
i have a problem with my college project, is about a hotel.

idhabitacion is BigDecimal and i need use request.getParameter to use variable hb and call hb.getTipoh

i tried with this code but i think is stupid

```<code>java.math.BigDecimal idhabitacion = BigDecimal.valueOf(Double.parseDouble(request.getParameter("idhabitacion")));
</code>```

dont show me error but doesnt work

```<code>java.math.BigDecimal idhabitacion = request.getParameter("idhabitacion");
Habitacion hb = new ControladorHabitacion().getHabitacion(idhabitacion);
</code>```

the error is String cannot be converted in BigDecimal

答:
I think, somehow request.getParameter("idhabitacion") is coming as a string.

if so, Can you try with a BigDecimal constructor, which has a String argument. Something like

```<code>BigDecimal idhabitacion = new BigDecimal(request.getParameter("idhabitacion"));
</code>```

Body:
i have a problem with my college project, is about a hotel.

idhabitacion is BigDecimal and i need use request.getParameter to use variable hb and call hb.getTipoh

i tried with this code but i think is stupid

java.math.BigDecimal idhabitacion = BigDecimal.valueOf(Double.parseDouble(request.getParameter("idhabitacion")));

dont show me error but doesnt work

java.math.BigDecimal idhabitacion = request.getParameter("idhabitacion");
Habitacion hb = new ControladorHabitacion().getHabitacion(idhabitacion);

the error is String cannot be converted in BigDecimal

Body:
I think, somehow request.getParameter("idhabitacion") is coming as a string.

if so, Can you try with a BigDecimal constructor, which has a String argument. Something like

BigDecimal idhabitacion = new BigDecimal(request.getParameter("idhabitacion"));


问:
HikariCP not closing connections on close() (Connection Leak)
I'm using HikariCP 3.3.1 and PostgreSQL. But I've a problem with closing my connections, in Hikari config I set maximum pool size to 15 and minimum idle connection to 5, but after a few minutes of work with database I've found out connections don't closes, they stack more and more (almost 100 Idle connections right now).

My Connector class:

Connector.java

```<code>public class Connector implements IConnector {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;

static {
    config.setDriverClassName(org.postgresql.Driver.class.getName());
    config.setJdbcUrl("jdbc:postgresql://localhost:5432/vskDB");
    config.setUsername("postgres");
    config.setPassword("root");
    config.setMinimumIdle(5);
    config.setMaximumPoolSize(15);
    config.setConnectionTimeout(20000);
    config.setIdleTimeout(300000);
    ds = new HikariDataSource(config);
}

public Connection getConnection() {
    log.info("getConnection() invoked");
    try {
        return ds.getConnection();
    } catch (SQLException e) {
        log.error("Can't get connection from DataSource.");
        log.error(e.getMessage());
        System.out.println(e.getMessage());
    }
    return null;
}

Connector() {
}
}
</code>```

And here's my DAO class (simplified):
UserDAO.java

```<code>public class UserDatabaseDAO implements UserDAO {
    private Connector connector = new Connector();
    private Connection dbConnection;

    @Override
    public void removeUser(Long id) {
        try {
            dbConnection = connector.getConnection();
            if (dbConnection == null)
                throw new ConnectException();

            PreparedStatement preparedStatement = dbConnection.prepareStatement("DELETE FROM users WHERE user_id = ?");
            preparedStatement.setLong(1, id);
            preparedStatement.execute();

        } catch (SQLException | ConnectException e) {
            log.error("Can't remove user from database");
            log.error(e.getMessage());
            System.out.print(e.getMessage());
        } finally {
            try {
                dbConnection.close();
            } catch (SQLException e) {
                log.error("Can't close connection");
                log.error(e.getMessage());
                System.out.print(e.getMessage());
            }
        }
    }
}
</code>```

Here I've found an issue with some facts about Hikari:

You must call close() on the connection instance that HikariCP gives you

Maybe my dbConnection.close() wont work because it's just a copy of Connection which Hikari gives me in getConnection() method.

答:
You forgot to close also PreparedStatement

```<code>try {
       if (preparedStatement != null) {
            preparedStatement.close();
       }
       if (dbConnection != null) {
            dbConnection.close();
       }
</code>```

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.

Body:
I'm using HikariCP 3.3.1 and PostgreSQL. But I've a problem with closing my connections, in Hikari config I set maximum pool size to 15 and minimum idle connection to 5, but after a few minutes of work with database I've found out connections don't closes, they stack more and more (almost 100 Idle connections right now).

My Connector class:

Connector.java

public class Connector implements IConnector {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;

static {
    config.setDriverClassName(org.postgresql.Driver.class.getName());
    config.setJdbcUrl("jdbc:postgresql://localhost:5432/vskDB");
    config.setUsername("postgres");
    config.setPassword("root");
    config.setMinimumIdle(5);
    config.setMaximumPoolSize(15);
    config.setConnectionTimeout(20000);
    config.setIdleTimeout(300000);
    ds = new HikariDataSource(config);
}

public Connection getConnection() {
    log.info("getConnection() invoked");
    try {
        return ds.getConnection();
    } catch (SQLException e) {
        log.error("Can't get connection from DataSource.");
        log.error(e.getMessage());
        System.out.println(e.getMessage());
    }
    return null;
}

Connector() {
}
}

And here's my DAO class (simplified):
UserDAO.java

public class UserDatabaseDAO implements UserDAO {
    private Connector connector = new Connector();
    private Connection dbConnection;

    @Override
    public void removeUser(Long id) {
        try {
            dbConnection = connector.getConnection();
            if (dbConnection == null)
                throw new ConnectException();

            PreparedStatement preparedStatement = dbConnection.prepareStatement("DELETE FROM users WHERE user_id = ?");
            preparedStatement.setLong(1, id);
            preparedStatement.execute();

        } catch (SQLException | ConnectException e) {
            log.error("Can't remove user from database");
            log.error(e.getMessage());
            System.out.print(e.getMessage());
        } finally {
            try {
                dbConnection.close();
            } catch (SQLException e) {
                log.error("Can't close connection");
                log.error(e.getMessage());
                System.out.print(e.getMessage());
            }
        }
    }
}

Here I've found an issue with some facts about Hikari:

You must call close() on the connection instance that HikariCP gives you

Maybe my dbConnection.close() wont work because it's just a copy of Connection which Hikari gives me in getConnection() method.

Body:
You forgot to close also PreparedStatement

try {
       if (preparedStatement != null) {
            preparedStatement.close();
       }
       if (dbConnection != null) {
            dbConnection.close();
       }

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.


问:
in python how do I convert a single digit number into a double digits string?
So say i have

a = 5

i want to print it as a string '05'

ContentLicense: CC BY-SA 2.5

Body:
Branching off of Mohommad's answer:

str_years = [x for x in range(24)]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

#Or, if you're starting with ints:
int_years = [int(x) for x in str_years]

#Formatted here
form_years = ["%02d" % x for x in int_years]

print(form_years)
#['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']


问:
ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:
While trying to add a PrimeNG table I broke my build here: https://github.com/BillyCharter87/Tech-O-Dex-UI/tree/BrokeIt

I recall updating my package.json from TypeScript 2.3.4 to 2.4.0 and it broke due to (I think) the fact that I was using Headers and Http for my POST call. I tried setting it back to 2.3.4 to no avail. I have fixed what I could by adding in:

```<code>import { HttpClient, HttpHeaders } from "@angular/common/http";
</code>```

but still running into the Error I have now for the HttpClient. I have tried importing HttpClient into the providers like so: providers: [HttpClient] for my app.module.ts.

The full error is as follows:

```<code>AppComponent.html:9 ERROR Error: StaticInjectorError(AppModule)[HttpClient -> HttpHandler]:
StaticInjectorError(Platform: core)[HttpClient -> HttpHandler]:
NullInjectorError: No provider for HttpHandler!
</code>```

答:
There are two possible reasons
1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.

```<code>import { HttpClientModule } from '@angular/common/http';
</code>```

If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.

import { HttpModule } from '@angular/http'

By default, this is not available in the angular then you need to install @angular/http

If you wish you can use both HttpClientModule and HttpModule in your project.

Body:
While trying to add a PrimeNG table I broke my build here: https://github.com/BillyCharter87/Tech-O-Dex-UI/tree/BrokeIt

I recall updating my package.json from TypeScript 2.3.4 to 2.4.0 and it broke due to (I think) the fact that I was using Headers and Http for my POST call. I tried setting it back to 2.3.4 to no avail. I have fixed what I could by adding in:

import { HttpClient, HttpHeaders } from "@angular/common/http";

but still running into the Error I have now for the HttpClient. I have tried importing HttpClient into the providers like so: providers: [HttpClient] for my app.module.ts.

The full error is as follows:

AppComponent.html:9 ERROR Error: StaticInjectorError(AppModule)[HttpClient -> HttpHandler]:
StaticInjectorError(Platform: core)[HttpClient -> HttpHandler]:
NullInjectorError: No provider for HttpHandler!

Body:
There are two possible reasons
1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.

import { HttpClientModule } from '@angular/common/http';

If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.

import { HttpModule } from '@angular/http'

By default, this is not available in the angular then you need to install @angular/http

If you wish you can use both HttpClientModule and HttpModule in your project.


问:
How can I get the yesterday's data and show it to my form today?
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

```<code>Andy Shrob
Paula Guinto
Mylene Miles
</code>```

Attendance (TODAY)

```<code>Paula Guinto
Mylene Miles
</code>```

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

```<code>mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)
</code>```

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

答:
Use Date related functions in the WHERE condition:

e.g

```<code>WHERE ??? = DATE_SUB(NOW(), INTERVAL 1 DAY)
</code>```

For further reference, see here.

Body:
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

Andy Shrob
Paula Guinto
Mylene Miles

Attendance (TODAY)

Paula Guinto
Mylene Miles

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

Body:
Use Date related functions in the WHERE condition:

e.g

WHERE ??? = DATE_SUB(NOW(), INTERVAL 1 DAY)

For further reference, see here.


问:
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
I am trying to load an image into imageView through Glide. But the image is not loaded - I get an error.
I'm using the following code

```<code>GlideApp.with(context)
    .load(itemData.getThumbnailUri())
    .placeholder(R.mipmap.koya_logo_white)
    .error(R.mipmap.ic_image_loading_error)
    .into(itemBinding.cover);
</code>```

Logs

```<code>lide: Load failed for https://s3.amazonaws.com/koya-dev-videos/kindness/8da807aa-1e1e-413d-bf9b-5bb084646593/medialibrary/9456621508/videos/1eb78337-d569-41bd-95ad-153d9098de03.png with size [1080x1080]
</code>```

```<code>class com.bumptech.glide.load.engine.GlideException: Failed to load resource
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Failed LoadPath{StringUri->Object->Drawable}, LOCAL, DataCacheKey{sourceKey=https://s3.amazonaws.com/koya-dev-videos/kindness/8da807aa-1e1e-413d-bf9b-5bb084646593/medialibrary/9456621508/videos/1eb78337-d569-41bd-95ad-153d9098de03.png, signature=EmptySignature}
Cause (1 of 2): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{StringUri->Drawable->Drawable}
Cause (2 of 2): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{StringUri->Bitmap->Drawable}
</code>```

答:
The solution works for me:

    1. Update build.gradle(Module: app)

```<code>    implementation "com.github.bumptech.glide:glide:4.7.1"
        kapt "com.github.bumptech.glide:compiler:4.7.1"
        implementation "com.squareup.okhttp3:okhttp:3.14.0"
        implementation ('com.github.bumptech.glide:okhttp3-integration:4.7.1'){
            exclude group: 'glide-parent'
        }
</code>```

Set timeout for glide

```<code> @GlideModule
    class MyAppGlideModule : AppGlideModule() {
        override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
            val client = OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build()
            val factory = OkHttpUrlLoader.Factory(client)
            glide.registry.replace(GlideUrl::class.java, InputStream::class.java, factory)
        }
    }
</code>```

Body:
I am trying to load an image into imageView through Glide. But the image is not loaded - I get an error.
I'm using the following code

GlideApp.with(context)
    .load(itemData.getThumbnailUri())
    .placeholder(R.mipmap.koya_logo_white)
    .error(R.mipmap.ic_image_loading_error)
    .into(itemBinding.cover);

Logs

lide: Load failed for https://s3.amazonaws.com/koya-dev-videos/kindness/8da807aa-1e1e-413d-bf9b-5bb084646593/medialibrary/9456621508/videos/1eb78337-d569-41bd-95ad-153d9098de03.png with size [1080x1080]

class com.bumptech.glide.load.engine.GlideException: Failed to load resource
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Failed LoadPath{StringUri->Object->Drawable}, LOCAL, DataCacheKey{sourceKey=https://s3.amazonaws.com/koya-dev-videos/kindness/8da807aa-1e1e-413d-bf9b-5bb084646593/medialibrary/9456621508/videos/1eb78337-d569-41bd-95ad-153d9098de03.png, signature=EmptySignature}
Cause (1 of 2): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{StringUri->Drawable->Drawable}
Cause (2 of 2): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{StringUri->Bitmap->Drawable}

Body:
The solution works for me:

    1. Update build.gradle(Module: app)

    implementation "com.github.bumptech.glide:glide:4.7.1"
        kapt "com.github.bumptech.glide:compiler:4.7.1"
        implementation "com.squareup.okhttp3:okhttp:3.14.0"
        implementation ('com.github.bumptech.glide:okhttp3-integration:4.7.1'){
            exclude group: 'glide-parent'
        }

Set timeout for glide

 @GlideModule
    class MyAppGlideModule : AppGlideModule() {
        override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
            val client = OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build()
            val factory = OkHttpUrlLoader.Factory(client)
            glide.registry.replace(GlideUrl::class.java, InputStream::class.java, factory)
        }
    }


问:
How to fix "Cannot read property 'trim' of undefined" error in node
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

```<code>import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

</code>```

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

```<code>>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

</code>```

How can I fix this error ?

答:
Just check is str is actually empty in isEmpty
Add if(!str) return true to it.
It will look like this:

```<code>const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    if(!str) return true;
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}
</code>```

Body:
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

How can I fix this error ?

Body:
Just check is str is actually empty in isEmpty
Add if(!str) return true to it.
It will look like this:

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    if(!str) return true;
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}


问:
How to install ipython notebook locally?
I would like to use ipython notebook. When I type ipython notebook in the command line, I get:

```<code>Could not start notebook. Please install ipython-notebook
</code>```

The problem is that I do not have root privileges on the system (I use Ubuntu). I think that there is a work around with virtual environment but I do not know how exactly to use it. Could anybody please help me with that? What sequence of the command should I execute to be able to use ipython notebook in my browser?

答:
Now Ubuntu wants to not support Python note book. You just need to install Jupyter notebook instead of python notebook where you can access Python also. Below is the command for installation of Jupyter notebook.</p>

```<code>sudo apt-get install Jupyter-notebook
</code>```

Body:
I would like to use ipython notebook. When I type ipython notebook in the command line, I get:

Could not start notebook. Please install ipython-notebook

The problem is that I do not have root privileges on the system (I use Ubuntu). I think that there is a work around with virtual environment but I do not know how exactly to use it. Could anybody please help me with that? What sequence of the command should I execute to be able to use ipython notebook in my browser?

Body:
Now Ubuntu wants to not support Python note book. You just need to install Jupyter notebook instead of python notebook where you can access Python also. Below is the command for installation of Jupyter notebook.

sudo apt-get install Jupyter-notebook


问:
can I use generic services in domain service with different business or not?
I have problem in create generic domain service or not??
I have "BaseEntity" that inherit any entity from it and has been every moment set value when update or insert method called  in repository .my domain service layer that implements every entity business. my problem is what I have to do when I have one business that implement in every Services in domain service.can I use generic class and interface to manage BaseEntity and then change business for example for Update method override base update method or I used for every entity one service class with one interface with separate business???</p>

答:
For the most part I would advise against any generic base classes for your domain.  If you have a hierarchy of classes it may be that you have a more technical/framework domain but even there you should favour composition over inheritance.

I would not, for instance, use a BaseEntity as I find it superfluous.  The closes you could come is perhaps something like an IRepository<T> with a T Get(Guid id) and a void Save(T instance) method but you would have to think exactly where you would use something like this.  You could make your roles explicit by following the single responsibility principle and go with IRepositoryGet and IRepositorySave.  However, these type of interfaces are only useful where you have some broad commonality between the objects and that typically doesn't happen.  You may find that some lookup data seems to fit into this space but even there you may rather want to design a common repository as opposed to individual repositories for each type.

What you most definitely want to avoid is to have a coarse-grained interface and then have various NotImplementedExceptions thrown.  When you find that you are doing that rather split the interfaces into more fine-grained versions and implement only the desired interfaces.  In this way you can use safe casting to ensure that the interface is implemented before making a call to the method.


问:
Set HTML img attribute to Angular binding
Inside the HTML class for my Angular component, I have an image displaying with:

```<code><div class="row" id="work">
  <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12" id="">
      <img class="img-fluid" width="100%" [height]="height" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
  </div>
</div>
</code>```

In my typescript file for the component, I have a height variable being set to "100" on init.

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}
</code>```

On page load, the image height is equal to the default images height, it it not reading/using my height variable. Probably something silly, but not sure what.

EDIT:

"img-fluid" was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself from Typescript.

答:
try like this </p>

```<code><img class="img-fluid" width="100%" height="{{height}}" src="assets/images/logo.png" alt="">
</code>```

Body:
Inside the HTML class for my Angular component, I have an image displaying with:

In my typescript file for the component, I have a height variable being set to "100" on init.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}

On page load, the image height is equal to the default images height, it it not reading/using my height variable. Probably something silly, but not sure what.

EDIT:

"img-fluid" was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself from Typescript.

Body:
try like this

<img class="img-fluid" width="100%" height="{{height}}" src="assets/images/logo.png" alt="">


问:
uasort() ? - sorting posts from a bank account
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

```<code>date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)
</code>```

btw. the date field is an UNIX timestamp

```<code>array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )
</code>```

答:
```<code>$key = 'accum_amount';

function sortme($a, $b)
{
    global $key;
    if ($a[$key] == $b[$key]) {
        return 0;
    }
    return ($a[$key] < $b[$key]) ? -1 : 1;
}

usort($array, "sortme");
</code>```

perhaps this should help. Bad thing, have to define global variable. Complete code!!!

```<code>$array = array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    );

$key = 'accum_amount';

function sortme($a, $b)
{
    global $key;
    if ($a[$key] == $b[$key]) {
        return 0;
    }
    return ($a[$key] < $b[$key]) ? -1 : 1;
}

usort($array, "sortme");

echo "```";
print_r($array);
echo "```";
</code>```

Body:
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)

btw. the date field is an UNIX timestamp

array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )

Body:
$key = 'accum_amount';

function sortme($a, $b)
{
    global $key;
    if ($a[$key] == $b[$key]) {
        return 0;
    }
    return ($a[$key] < $b[$key]) ? -1 : 1;
}

usort($array, "sortme");

perhaps this should help. Bad thing, have to define global variable. Complete code!!!

$array = array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    );

$key = 'accum_amount';

function sortme($a, $b)
{
    global $key;
    if ($a[$key] == $b[$key]) {
        return 0;
    }
    return ($a[$key] < $b[$key]) ? -1 : 1;
}

usort($array, "sortme");

echo "<pre>";
print_r($array);
echo "</pre>";