问:
Python 3.7 - Fast way to concatenate strings and write them to disk
Is there a better implementation for:

```<code>file = open("./myFile.txt","w+")
for doc in allDocuments: #around 35 million documents
    file.write(str(doc.number)+"\r\n")
f.close()
</code>```

Currently this implementation is taking 20sec per file

答:
The I/O isn't really the problem, nor can you do anything useful about it: the file object and the operating system will both be doing some form of buffering. What you can do something about is the number of method calls you make.

```<code>with open("./myFile.txt", "w", newline='\r\n') as f:
    f.writelines(f'{doc.number}\n' for doc in allDocuments)
</code>```

The writelines method takes an iterable of strings to write to the file.  (The documentation says "list", but it seems to be speaking of lists, not lists; a generator expression seems to work as well.) The generator expression produces each line on demand for writelines.

Here's a test:

```<code>import random

def allDocuments():
    for i in range(35_000_000):
        yield random.randint(0, 100)

with open("tmp.txt", "w", newline='\r\n') as f:
    f.writelines(f'{doc}\n' for doc in allDocuments())
</code>```

It completed in 75 seconds (most of that due to the repeated calls to random.randint), using less than 6MB of memory. (Replacing the call to random.randint with a constant value dropped the running time to under 30 seconds.)

Body:
Is there a better implementation for:

file = open("./myFile.txt","w+")
for doc in allDocuments: #around 35 million documents
    file.write(str(doc.number)+"\r\n")
f.close()

Currently this implementation is taking 20sec per file

Body:
The I/O isn't really the problem, nor can you do anything useful about it: the file object and the operating system will both be doing some form of buffering. What you can do something about is the number of method calls you make.

with open("./myFile.txt", "w", newline='\r\n') as f:
    f.writelines(f'{doc.number}\n' for doc in allDocuments)

The writelines method takes an iterable of strings to write to the file.  (The documentation says "list", but it seems to be speaking of lists, not lists; a generator expression seems to work as well.) The generator expression produces each line on demand for writelines.

Here's a test:

import random

def allDocuments():
    for i in range(35_000_000):
        yield random.randint(0, 100)

with open("tmp.txt", "w", newline='\r\n') as f:
    f.writelines(f'{doc}\n' for doc in allDocuments())

It completed in 75 seconds (most of that due to the repeated calls to random.randint), using less than 6MB of memory. (Replacing the call to random.randint with a constant value dropped the running time to under 30 seconds.)


来源: stackexchange

问:
Replace Null Values in <String, String[]> TreeMap
I have a tree map of the form: < String, String[] >

There are values inside of my String[] that are null. When writing my results to a file, using the below code, I'm getting:

```<code>java.lang.NullPointerException
</code>```

My current code for writing to my file is below, I'm trying to replace the nulls with an empty string.

```<code>        new File(outFolder).mkdir();
        File dir = new File(outFolder);
        //get the file we're writing to
        File outFile = new File(dir, "javaoutput.txt");

        //create a writer
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(outFile), "utf-8"))) {
            for (Map.Entry<String, String[]> entry : allResults.entrySet()) {
                writer.write(entry.getKey() + " "+ Arrays.toString(entry.getValue()).replace(null, ""));
                writer.newLine();

            }
</code>```

Any thoughts?

答:
Your issue arises from this method call: replace(null,"");

Check the implementation of replace()

The first parameter it takes is a CharSequence and the first thing it does with this char sequence is call toString() on it.

This is going to throw a NullPointerException every time.

Arrays.toString() however will replace null values with "null" so change your call to replace to be: replace("null", "");

ContentLicense: CC BY-SA 4.0

Body:
I have a tree map of the form: < String, String[] >

There are values inside of my String[] that are null. When writing my results to a file, using the below code, I'm getting:

java.lang.NullPointerException

My current code for writing to my file is below, I'm trying to replace the nulls with an empty string.

        new File(outFolder).mkdir();
        File dir = new File(outFolder);
        //get the file we're writing to
        File outFile = new File(dir, "javaoutput.txt");

        //create a writer
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(outFile), "utf-8"))) {
            for (Map.Entry<String, String[]> entry : allResults.entrySet()) {
                writer.write(entry.getKey() + " "+ Arrays.toString(entry.getValue()).replace(null, ""));
                writer.newLine();

            }

Any thoughts?


问:
How the count the number of whitespaces between the first and second word in Java
I have a string that looks like the following:

```<code>Here    is a test
</code>```

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

```<code>int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}
</code>```

答:
```<code>int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    } else if ( spaceCount > 0 ) {
          break;
    }
}
</code>```

This assumes that there are no spaces before the first worid.

Body:
I have a string that looks like the following:

Here    is a test

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

Body:
int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    } else if ( spaceCount > 0 ) {
          break;
    }
}

This assumes that there are no spaces before the first worid.


问:
Prevent selecting more than X elements
I'm using jQuery to allow a user to select 3 time blocks and no more.

Once they've selected the 3 blocks, I'd like to prevent them from selecting more.

I am however, not having too much luck with it.

My current code can be found here : https://jsfiddle.net/1q8mzbwv/

I am trying an increment value of selected_num and adding a return false, but it's not preventing the selection.

I'd also like to try do this in reverse, where the user can click the selected item and the count changes too.

jQuery code :

```<code>var selected_num = 0;

$('.time-block').click(function()
{
var id = $(this).data('id');
var chosen_time = $(this).data('time');

$(this).addClass('-chosen');

$('.time-selected-block').eq(selected_num).html(chosen_time);

if(selected_num == "3")
{
    return false;
}
else
{
    selected_num++;
}

console.log(selected_num);
})
</code>```

Thanks

答:
In addition to the solution that was provided to you, here are some explanations:

Your problems are these:

1) This statement

```<code>$(this).addClass('-chosen');
</code>```

appears before your evaluation.
Thus, the class is added before the condition had the chance to be evaluated.

2) Your condition is working but is problematic:

```<code>selected_num == "3"
</code>```

First, you want to prevent addition if more than 2 are selected:
If by any chance, 4 would be selected, it would permit to add a 5th etc.

Second,you are comparing selected_num that is an integer with a string.
This string is converted to an integer by the engine thus it's not a big deal but these type of conversion shouldn't be made if not intentional and useful.

3) As you have seen in the solution of Yevgen Gorbunkov, you should use "toggleClass" to add or delete the class in a shorter snippet.

Title: Prevent selecting more than X elements

Body:
I'm using jQuery to allow a user to select 3 time blocks and no more.

Once they've selected the 3 blocks, I'd like to prevent them from selecting more.

I am however, not having too much luck with it.

My current code can be found here : https://jsfiddle.net/1q8mzbwv/

I am trying an increment value of selected_num and adding a return false, but it's not preventing the selection.

I'd also like to try do this in reverse, where the user can click the selected item and the count changes too.

jQuery code :

var selected_num = 0;

$('.time-block').click(function()
{
var id = $(this).data('id');
var chosen_time = $(this).data('time');

$(this).addClass('-chosen');

$('.time-selected-block').eq(selected_num).html(chosen_time);

if(selected_num == "3")
{
    return false;
}
else
{
    selected_num++;
}

console.log(selected_num);
})

Thanks

Body:
In addition to the solution that was provided to you, here are some explanations:

Your problems are these:

1) This statement

$(this).addClass('-chosen');

appears before your evaluation.
Thus, the class is added before the condition had the chance to be evaluated.

2) Your condition is working but is problematic:

selected_num == "3"

First, you want to prevent addition if more than 2 are selected:
If by any chance, 4 would be selected, it would permit to add a 5th etc.

Second,you are comparing selected_num that is an integer with a string.
This string is converted to an integer by the engine thus it's not a big deal but these type of conversion shouldn't be made if not intentional and useful.

3) As you have seen in the solution of Yevgen Gorbunkov, you should use "toggleClass" to add or delete the class in a shorter snippet.


问:
Unable to convert varchar to date
I am trying to convert a function (varchar) to date, but get the below error message.

Error

Failed to convert date and / or time from string.

Script

```<code>DECLARE @MyDate date

SET @MyDate = CONVERT(date, dbo.GETMINDATE(0123), 103)

SELECT @MyDate
</code>```

The function itself returns a varchar date like so - '01 Apr 2010 08:00:00.000'.

The SQL Server host is in French settings, so perhaps it's a regional setting issue.

答:
If you are stuck with this and can't change this to fix the function to return the correct datatype then you can use PARSE to specify a static culture (so completely unaffected by the locale of the server and the default settings of its users).

```<code>SELECT PARSE('01 Apr 2010 08:00:00.000' AS date USING 'en-US')
</code>```

Obviously replace the string literal with your function call. As you are casting to date in the question I have used the same, this will truncate the time portion.

Use datetime or datetime2 if that was not the intention.

Title: Unable to convert varchar to date

Body:
I am trying to convert a function (varchar) to date, but get the below error message.

Error

Failed to convert date and / or time from string.

Script

DECLARE @MyDate date

SET @MyDate = CONVERT(date, dbo.GETMINDATE(0123), 103)

SELECT @MyDate

The function itself returns a varchar date like so - '01 Apr 2010 08:00:00.000'.

The SQL Server host is in French settings, so perhaps it's a regional setting issue.

Body:
If you are stuck with this and can't change this to fix the function to return the correct datatype then you can use PARSE to specify a static culture (so completely unaffected by the locale of the server and the default settings of its users).

SELECT PARSE('01 Apr 2010 08:00:00.000' AS date USING 'en-US')

Obviously replace the string literal with your function call. As you are casting to date in the question I have used the same, this will truncate the time portion.

Use datetime or datetime2 if that was not the intention.


问:
Is any way to change control's background color without `BackColor` property?
There are some properties for Controls, that needs System.Drawing.dll to be used, i.e.:

```<code>control.Size =  new System.Drawing.Size(10, 20);
</code>```

however, that goal can be achieved without with other workaround (not needed System.Drawing), i.e.:

```<code>control.Width = 10;
control.Height= 20;
</code>```

My question is, can we change control's background color ( .BackColor, which requires System.Drawing)  with some workarounds like that? (so, not needed System.Drawing)?

答:
No - The dependency on System.Drawing is for the Color value itself and there are no shortcut properties to, for example, set the component values like you can with Size.

If you don't want to include System.Drawing inline just add a using directive:

```<code>using System.Drawing;

...

    control.BackColor = Color.Blue;  // Color will be found in System.Drawing via the "using"
</code>```

Body:
There are some properties for Controls, that needs System.Drawing.dll to be used, i.e.:

control.Size =  new System.Drawing.Size(10, 20);

however, that goal can be achieved without with other workaround (not needed System.Drawing), i.e.:

control.Width = 10;
control.Height= 20;

My question is, can we change control's background color ( .BackColor, which requires System.Drawing)  with some workarounds like that? (so, not needed System.Drawing)?

Body:
No - The dependency on System.Drawing is for the Color value itself and there are no shortcut properties to, for example, set the component values like you can with Size.

If you don't want to include System.Drawing inline just add a using directive:

using System.Drawing;

...

    control.BackColor = Color.Blue;  // Color will be found in System.Drawing via the "using"


问:
How to apply bold and italics to an NSMutableAttributedString range?
I've been trying to apply combinations of NSFontAttributes to NSMutableAttributedString's lately and I simply can't find a thorough explanation on how to do it without removing other attributes.

I've searched a bunch, and found this question pertaining to how to do it with HTML, and then this question about how to find where text has been bolded or italicized, but nothing on how to actually do it.

Currently, I try to format stings as follows:

Italics:
[mutableAttributedString addAttribute: NSFontAttributeName value:[fontAttributes valueForKey:CXItalicsFontAttributeName] range:r];

Bold: [mutableAttributedString addAttribute:NSFontAttributeName value:[fontAttributes valueForKey:CXBoldFontAttributeName] range:r];

Where the constants CXItalicsFontAttributeName and CXBoldAttributeName extract the following two values from a dictionary respectfully:

```<code>UIFont *italicsFont = [UIFont fontWithName:@"Avenir-BookOblique" size:14.0f];
UIFont *boldFont = [UIFont fontWithName:@"Avenir-Heavy" size:14.0f];
</code>```

I know this mustn't be the right way to go about formatting, as the NSAttributedString standard attributes don't include a ItalicsFontAttribute or BoldFontAttribute, but I can't find the properly way to do this. Can anyone assist me?

答:
Details

Swift 5.1, Xcode 11.3.1

Solution

```<code>extension UIFont {
    class func systemFont(ofSize fontSize: CGFloat, symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        return UIFont.systemFont(ofSize: fontSize).including(symbolicTraits: symbolicTraits)
    }

    func including(symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        var _symbolicTraits = self.fontDescriptor.symbolicTraits
        _symbolicTraits.update(with: symbolicTraits)
        return withOnly(symbolicTraits: _symbolicTraits)
    }

    func excluding(symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        var _symbolicTraits = self.fontDescriptor.symbolicTraits
        _symbolicTraits.remove(symbolicTraits)
        return withOnly(symbolicTraits: _symbolicTraits)
    }

    func withOnly(symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        guard let fontDescriptor = fontDescriptor.withSymbolicTraits(symbolicTraits) else { return nil }
        return .init(descriptor: fontDescriptor, size: pointSize)
    }
}
</code>```

Usage

```<code>font = UIFont.italicSystemFont(ofSize: 15).including(symbolicTraits: .traitBold)
font = UIFont.systemFont(ofSize: 15, symbolicTraits: [.traitBold, .traitItalic])
font = font.excluding(symbolicTraits: [.traitBold]
font = font.withOnly(symbolicTraits: [])
</code>```

Full sample

Do not forget to paste the solution code here.

```<code>import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addLabel(origin: .init(x: 20, y: 20), font: .systemFont(ofSize: 15, symbolicTraits: [.traitBold, .traitItalic]))
        addLabel(origin: .init(x: 20, y: 40), font: UIFont.italicSystemFont(ofSize: 15).including(symbolicTraits: .traitBold))
        guard let font = UIFont.systemFont(ofSize: 15, symbolicTraits: [.traitBold, .traitItalic]) else { return }
        addLabel(origin: .init(x: 20, y: 60), font: font.excluding(symbolicTraits: [.traitBold]))
        addLabel(origin: .init(x: 20, y: 80), font: font.withOnly(symbolicTraits: []))
    }

    private func addLabel(origin: CGPoint, font: UIFont?) {
        guard let font = font else { return }
        let label = UILabel(frame: .init(origin: origin, size: .init(width: 200, height: 40)))
        label.attributedText = NSAttributedString(string: "Hello World!", attributes: [.font: font, .foregroundColor: UIColor.black ])
        view.addSubview(label)
    }
}
</code>```

Result

Body:
I've been trying to apply combinations of NSFontAttributes to NSMutableAttributedString's lately and I simply can't find a thorough explanation on how to do it without removing other attributes.

I've searched a bunch, and found this question pertaining to how to do it with HTML, and then this question about how to find where text has been bolded or italicized, but nothing on how to actually do it.

Currently, I try to format stings as follows:

Italics:
[mutableAttributedString addAttribute: NSFontAttributeName value:[fontAttributes valueForKey:CXItalicsFontAttributeName] range:r];

Bold: [mutableAttributedString addAttribute:NSFontAttributeName value:[fontAttributes valueForKey:CXBoldFontAttributeName] range:r];

Where the constants CXItalicsFontAttributeName and CXBoldAttributeName extract the following two values from a dictionary respectfully:

UIFont *italicsFont = [UIFont fontWithName:@"Avenir-BookOblique" size:14.0f];
UIFont *boldFont = [UIFont fontWithName:@"Avenir-Heavy" size:14.0f];

I know this mustn't be the right way to go about formatting, as the NSAttributedString standard attributes don't include a ItalicsFontAttribute or BoldFontAttribute, but I can't find the properly way to do this. Can anyone assist me?

Body:
Details

Swift 5.1, Xcode 11.3.1

Solution

extension UIFont {
    class func systemFont(ofSize fontSize: CGFloat, symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        return UIFont.systemFont(ofSize: fontSize).including(symbolicTraits: symbolicTraits)
    }

    func including(symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        var _symbolicTraits = self.fontDescriptor.symbolicTraits
        _symbolicTraits.update(with: symbolicTraits)
        return withOnly(symbolicTraits: _symbolicTraits)
    }

    func excluding(symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        var _symbolicTraits = self.fontDescriptor.symbolicTraits
        _symbolicTraits.remove(symbolicTraits)
        return withOnly(symbolicTraits: _symbolicTraits)
    }

    func withOnly(symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
        guard let fontDescriptor = fontDescriptor.withSymbolicTraits(symbolicTraits) else { return nil }
        return .init(descriptor: fontDescriptor, size: pointSize)
    }
}

Usage

font = UIFont.italicSystemFont(ofSize: 15).including(symbolicTraits: .traitBold)
font = UIFont.systemFont(ofSize: 15, symbolicTraits: [.traitBold, .traitItalic])
font = font.excluding(symbolicTraits: [.traitBold]
font = font.withOnly(symbolicTraits: [])

Full sample

Do not forget to paste the solution code here.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addLabel(origin: .init(x: 20, y: 20), font: .systemFont(ofSize: 15, symbolicTraits: [.traitBold, .traitItalic]))
        addLabel(origin: .init(x: 20, y: 40), font: UIFont.italicSystemFont(ofSize: 15).including(symbolicTraits: .traitBold))
        guard let font = UIFont.systemFont(ofSize: 15, symbolicTraits: [.traitBold, .traitItalic]) else { return }
        addLabel(origin: .init(x: 20, y: 60), font: font.excluding(symbolicTraits: [.traitBold]))
        addLabel(origin: .init(x: 20, y: 80), font: font.withOnly(symbolicTraits: []))
    }

    private func addLabel(origin: CGPoint, font: UIFont?) {
        guard let font = font else { return }
        let label = UILabel(frame: .init(origin: origin, size: .init(width: 200, height: 40)))
        label.attributedText = NSAttributedString(string: "Hello World!", attributes: [.font: font, .foregroundColor: UIColor.black ])
        view.addSubview(label)
    }
}

Result


问:
Git pre-commit hook is not running on Windows
I'm just starting to look into Git hooks, but I can't seem to get them to run.

I set up a local repository, so there is now a '.git' directory in my project folder. I have added a '.cmd' file into the C:/path/to/my/project/.git/hooks directory named 'pre-commit.cmd'. Here is the contents of this file:

```<code>echo "HOOK RUNNING"
echo. 2>C:/path/to/my/project/.git/hooks/EmptyFile.txt
</code>```

This should echo the text "HOOK RUNNING" and create an empty text file in that directory. However, if I commit changes through my IDE (NetBeans) or use Git Bash to commit, neither of them seem to run my pre-commit hook, as no file is created.

My understanding is that all you have to do to get a hook to run is add an executable with the name of the hook (as I have done). Am I doing something wrong?

Note: This is on a Windows 7 PC.

答:
If it helps anyone:

I was getting the following error:

error: cannot spawn .git/hooks/pre-commit: No error

It turned out that in my pre-commit file I did not have 'newline' character after last exit command:

```<code>#!/bin/sh
# From gist at https://gist.github.com/chadmaughan/5889802

# Stash any unstaged changes
git stash -q --keep-index

# Run the tests with the Gradle wrapper
./gradlew test --daemon

# Store the last exit code in a variable
RESULT=$?

# Unstash the unstashed changes
git stash pop -q

# Return the './gradlew test' exit code
exit $RESULT
# << must have a newline after the above command >>
</code>```

I was running a Gradle project on Windows and Gradle commands in the Cmder shell and cmd.

Body:
I'm just starting to look into Git hooks, but I can't seem to get them to run.

I set up a local repository, so there is now a '.git' directory in my project folder. I have added a '.cmd' file into the C:/path/to/my/project/.git/hooks directory named 'pre-commit.cmd'. Here is the contents of this file:

echo "HOOK RUNNING"
echo. 2>C:/path/to/my/project/.git/hooks/EmptyFile.txt

This should echo the text "HOOK RUNNING" and create an empty text file in that directory. However, if I commit changes through my IDE (NetBeans) or use Git Bash to commit, neither of them seem to run my pre-commit hook, as no file is created.

My understanding is that all you have to do to get a hook to run is add an executable with the name of the hook (as I have done). Am I doing something wrong?

Note: This is on a Windows 7 PC.

Body:
If it helps anyone:

I was getting the following error:

error: cannot spawn .git/hooks/pre-commit: No error

It turned out that in my pre-commit file I did not have 'newline' character after last exit command:

#!/bin/sh
# From gist at https://gist.github.com/chadmaughan/5889802

# Stash any unstaged changes
git stash -q --keep-index

# Run the tests with the Gradle wrapper
./gradlew test --daemon

# Store the last exit code in a variable
RESULT=$?

# Unstash the unstashed changes
git stash pop -q

# Return the './gradlew test' exit code
exit $RESULT
# << must have a newline after the above command >>

I was running a Gradle project on Windows and Gradle commands in the Cmder shell and cmd.


问:
User Data Not Saving To Firebase (Username, first name, Last Name)
I am trying to store data in my Firebase database but the app crashes when I call the function saveUserToFirebaseDatabase(). The performRegister() function works fine which stores the email and password using FirebaseAuth but when I call performRegister() then saveUserToFirebaseDatabase() right under it, the performRegister() doesn't execute all the way though. performRegister() is suppose to make a log.d tag which tells the uid and that it successfully stored the email and password. It does that but when I call saveUserToFirebaseDatabase() under performRegister() in the onCreate function, it doesn't log the uid like it did without the saveUserToFirebaseDatabase(). Instead the performRegister() Log displays the username and passowrd then skips to the saveUserToFirebaseDatabase() which logs display the username, first name, and last name from the previous activities the user had to enter when signing up for the account. Then it crashes. Here is my code. I want to be able to call performRegister() then saveUserToFirebaseDatabase() to save the user's email and password using FirebaseAuth then save the user's other information in the database using saveUserToFirebaseDatabase().</p>

```<code>class Password_Activity : AppCompatActivity() {

    lateinit var editPasswordText: EditText
    lateinit var editConfirmPasswordText: EditText
    lateinit var btnOpenActivity: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_password)

        editPasswordText = findViewById(R.id.edit_password)
        editConfirmPasswordText = findViewById(R.id.edit_confirm_password)
        btnOpenActivity = findViewById(R.id.password_continue_btn)

//        btnOpenActivity.isEnabled=false

        val textWatcher = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                var passwordinput: String = editPasswordText.text.toString().trim()
                var confirmpasswordinput: String = editConfirmPasswordText.text.toString().trim()
                btnOpenActivity.isEnabled = passwordinput.isNotEmpty() && confirmpasswordinput.isNotEmpty()

            }
        }

        editPasswordText.addTextChangedListener(textWatcher)
        editConfirmPasswordText.addTextChangedListener(textWatcher)

//        var intent = intent
//        val username = intent.getStringExtra("username")
//        val firstname = intent.getStringExtra("firstname")
//        val lastname = intent.getStringExtra("lastname")
//        val emailaddress = intent.getStringExtra("emailaddress")

        val btnOpenActivity: Button = findViewById(R.id.password_continue_btn)
        btnOpenActivity.setOnClickListener {

            performRegister()
            saveUserToFirebaseDatabase()

//            val intent = Intent(this, Main2Activity_welcome_after_signup_dashboard::class.java)
//            startActivity(intent)
//            overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left)
        }
    }
// Save user's email and password
    private fun performRegister(){
        var intent = intent
        val email = intent.getStringExtra("email")
        val password = editPasswordText.text.toString().trim()

        if (email.isEmpty() && password.isEmpty()) {
            Toast.makeText(this, "Please enter email and password", Toast.LENGTH_SHORT).show()
            return
        }

        Log.d("SignUpActivity","Email is "+ email)
        Log.d("SignUpActivity","Password is $password")

        // Initialize Firebase Auth
        FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener {
                if (!it.isSuccessful) {
                    Log.d("SignUp", "Account creation unsuccessful")
                    return@addOnCompleteListener
                }

                //else if successful
                Log.d("SignUp", "Successfully created user with uid: ${it.result?.user?.uid}")
            }
            .addOnFailureListener {
                Log.d("SignUp", "Failed to create user: ${it.message}")
            }

    }
// Save user's username, first name, and last name to database
    private fun saveUserToFirebaseDatabase(){
        var intent = intent
        val username = intent.getStringExtra("username")
        val firstname = intent.getStringExtra("firstname")
        val lastname = intent.getStringExtra("lastname")
        Log.d("Signup","Storing user information in password activity: $username, $firstname, $lastname")

        val uid = FirebaseAuth.getInstance().uid ?: ""
        val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")

        val user = User(uid, username, firstname, lastname)
        ref.setValue(user)
            .addOnSuccessListener {
                Log.d("Signup","We saved the user to Firebase Database")
            }
            .addOnFailureListener {
                Log.d("Signup", "Failed to save user to Firebase Database")
                return@addOnFailureListener
            }

    }

//Animation for back button
    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right)
    }
}

data class User(val uid: String, val username: String, val firstname: String, val lastname: String)
</code>```

答:
Your performRegister call happens aysnc in the background. This is why saveUserToFirebaseDatabase is getting called before it completes. Instead, just call it when performRegister is complete in the onCompleteListener.

Change this:

```<code>btnOpenActivity.setOnClickListener {
    performRegister()
    saveUserToFirebaseDatabase()
}
</code>```

To:

```<code>btnOpenActivity.setOnClickListener {
    performRegister()
}
</code>```

and add saveUserToFirebaseDatabase() to:

```<code>      .addOnCompleteListener {
                if (!it.isSuccessful) {
                    Log.d("SignUp", "Account creation unsuccessful")
                    return@addOnCompleteListener
                }

                //else if successful
                saveUserToFirebaseDatabase()
                Log.d("SignUp", "Successfully created user with uid: ${it.result?.user?.uid}")
            }
</code>```

Body:
I am trying to store data in my Firebase database but the app crashes when I call the function saveUserToFirebaseDatabase(). The performRegister() function works fine which stores the email and password using FirebaseAuth but when I call performRegister() then saveUserToFirebaseDatabase() right under it, the performRegister() doesn't execute all the way though. performRegister() is suppose to make a log.d tag which tells the uid and that it successfully stored the email and password. It does that but when I call saveUserToFirebaseDatabase() under performRegister() in the onCreate function, it doesn't log the uid like it did without the saveUserToFirebaseDatabase(). Instead the performRegister() Log displays the username and passowrd then skips to the saveUserToFirebaseDatabase() which logs display the username, first name, and last name from the previous activities the user had to enter when signing up for the account. Then it crashes. Here is my code. I want to be able to call performRegister() then saveUserToFirebaseDatabase() to save the user's email and password using FirebaseAuth then save the user's other information in the database using saveUserToFirebaseDatabase().

class Password_Activity : AppCompatActivity() {

    lateinit var editPasswordText: EditText
    lateinit var editConfirmPasswordText: EditText
    lateinit var btnOpenActivity: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_password)

        editPasswordText = findViewById(R.id.edit_password)
        editConfirmPasswordText = findViewById(R.id.edit_confirm_password)
        btnOpenActivity = findViewById(R.id.password_continue_btn)

//        btnOpenActivity.isEnabled=false

        val textWatcher = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                var passwordinput: String = editPasswordText.text.toString().trim()
                var confirmpasswordinput: String = editConfirmPasswordText.text.toString().trim()
                btnOpenActivity.isEnabled = passwordinput.isNotEmpty() && confirmpasswordinput.isNotEmpty()

            }
        }

        editPasswordText.addTextChangedListener(textWatcher)
        editConfirmPasswordText.addTextChangedListener(textWatcher)

//        var intent = intent
//        val username = intent.getStringExtra("username")
//        val firstname = intent.getStringExtra("firstname")
//        val lastname = intent.getStringExtra("lastname")
//        val emailaddress = intent.getStringExtra("emailaddress")

        val btnOpenActivity: Button = findViewById(R.id.password_continue_btn)
        btnOpenActivity.setOnClickListener {

            performRegister()
            saveUserToFirebaseDatabase()

//            val intent = Intent(this, Main2Activity_welcome_after_signup_dashboard::class.java)
//            startActivity(intent)
//            overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left)
        }
    }
// Save user's email and password
    private fun performRegister(){
        var intent = intent
        val email = intent.getStringExtra("email")
        val password = editPasswordText.text.toString().trim()

        if (email.isEmpty() && password.isEmpty()) {
            Toast.makeText(this, "Please enter email and password", Toast.LENGTH_SHORT).show()
            return
        }

        Log.d("SignUpActivity","Email is "+ email)
        Log.d("SignUpActivity","Password is $password")

        // Initialize Firebase Auth
        FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener {
                if (!it.isSuccessful) {
                    Log.d("SignUp", "Account creation unsuccessful")
                    return@addOnCompleteListener
                }

                //else if successful
                Log.d("SignUp", "Successfully created user with uid: ${it.result?.user?.uid}")
            }
            .addOnFailureListener {
                Log.d("SignUp", "Failed to create user: ${it.message}")
            }

    }
// Save user's username, first name, and last name to database
    private fun saveUserToFirebaseDatabase(){
        var intent = intent
        val username = intent.getStringExtra("username")
        val firstname = intent.getStringExtra("firstname")
        val lastname = intent.getStringExtra("lastname")
        Log.d("Signup","Storing user information in password activity: $username, $firstname, $lastname")

        val uid = FirebaseAuth.getInstance().uid ?: ""
        val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")

        val user = User(uid, username, firstname, lastname)
        ref.setValue(user)
            .addOnSuccessListener {
                Log.d("Signup","We saved the user to Firebase Database")
            }
            .addOnFailureListener {
                Log.d("Signup", "Failed to save user to Firebase Database")
                return@addOnFailureListener
            }

    }

//Animation for back button
    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right)
    }
}

data class User(val uid: String, val username: String, val firstname: String, val lastname: String)

Body:
Your performRegister call happens aysnc in the background. This is why saveUserToFirebaseDatabase is getting called before it completes. Instead, just call it when performRegister is complete in the onCompleteListener.

Change this:

btnOpenActivity.setOnClickListener {
    performRegister()
    saveUserToFirebaseDatabase()
}

To:

btnOpenActivity.setOnClickListener {
    performRegister()
}

and add saveUserToFirebaseDatabase() to:

      .addOnCompleteListener {
                if (!it.isSuccessful) {
                    Log.d("SignUp", "Account creation unsuccessful")
                    return@addOnCompleteListener
                }

                //else if successful
                saveUserToFirebaseDatabase()
                Log.d("SignUp", "Successfully created user with uid: ${it.result?.user?.uid}")
            }


问:
iterate an array of object and separe comparing dates in es6
I need to make a function to iterate an array of x objects then compare the date inside the objects and separate in different arrays so I can show separately in the HTML, this is my object:

[{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]
```

<p>I want something like this:</p>

```obj1 = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141}]

obj2 = [{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]
```

<p>my code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// global variables
json = [{
  "id": 1,
  "date": "2020-02-06",
  "value": 131
}, {
  "id": 2,
  "date": "2020-02-06",
  "value": 135
}, {
  "id": 3,
  "date": "2020-02-06",
  "value": 141
}, {
  "id": 4,
  "date": "2020-02-05",
  "value": 151
}, {
  "id": 6,
  "date": "2020-02-05",
  "value": 155
}];
obj1 = [];
obj2 = [];

for (const x of json) {
  if (x.date != x.date) {
    obj1.push(x)
  } else {
    obj2.push(x)
  }
}

console.log(obj1);
console.log(obj2);</code>```

in result always the items push into the obj1..

any help is welcome.

答:
You could goup by date and get an array of arrays.

var data = [{ id: 1, date: "2020-02-06", value: 131 }, { id: 2, date: "2020-02-06", value: 135 }, { id: 3, date: "2020-02-06", value: 141 }, { id: 4, date: "2020-02-05", value: 151 }, { id: 6, date: "2020-02-05", value: 155 }],
    grouped = data.reduce((r, o) => {
        var group = r.find(([{ date }]) => date === o.date);
        if (!group) r.push(group = []);
        group.push(o);
        return r;
    }, []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I need to make a function to iterate an array of x objects then compare the date inside the objects and separate in different arrays so I can show separately in the HTML, this is my object:

[{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]

I want something like this:

obj1 = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141}]

obj2 = [{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]

my code:

// global variables
json = [{
  "id": 1,
  "date": "2020-02-06",
  "value": 131
}, {
  "id": 2,
  "date": "2020-02-06",
  "value": 135
}, {
  "id": 3,
  "date": "2020-02-06",
  "value": 141
}, {
  "id": 4,
  "date": "2020-02-05",
  "value": 151
}, {
  "id": 6,
  "date": "2020-02-05",
  "value": 155
}];
obj1 = [];
obj2 = [];

for (const x of json) {
  if (x.date != x.date) {
    obj1.push(x)
  } else {
    obj2.push(x)
  }
}

console.log(obj1);
console.log(obj2);

in result always the items push into the obj1..

any help is welcome.

Body:
You could goup by date and get an array of arrays.

var data = [{ id: 1, date: "2020-02-06", value: 131 }, { id: 2, date: "2020-02-06", value: 135 }, { id: 3, date: "2020-02-06", value: 141 }, { id: 4, date: "2020-02-05", value: 151 }, { id: 6, date: "2020-02-05", value: 155 }],
    grouped = data.reduce((r, o) => {
        var group = r.find(([{ date }]) => date === o.date);
        if (!group) r.push(group = []);
        group.push(o);
        return r;
    }, []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


答:
The typical solution for this is to group them by the key and push them to an array. Below is an example using Array reduce and Object.values to get it down to the two arrays.

var items = [
  {"id":1,"date":"2020-02-06","value":131},
  {"id":2,"date":"2020-02-06","value":135},
  {"id":3,"date":"2020-02-06","value":141},
  {"id":4,"date":"2020-02-05","value":151},
  {"id":6,"date":"2020-02-05","value":155}
]

var dateGroups = items.reduce( function (dates, item) {
  dates[item.date] = dates[item.date] || []
  dates[item.date].push(item)
  return dates
}, {})

var results = Object.values(dateGroups)

console.log(results)```

Title: iterate an array of object and separe comparing dates in es6


问:
MySQL / MariaDB LOAD DATA INFILE with CSV without an id column (primary key) and trying to auto increment via the DBMS does not recognize SET command
I have created a table that has the following definition:

```<code>CREATE TABLE vacayhome.photo (
  id INT NOT NULL AUTO_INCREMENT,
  url_path CHAR NOT NULL,
  caption CHAR NOT NULL,
  space_type CHAR NOT NULL,
  is_main BOOLEAN NOT NULL,
  listing_id INT NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (listing_id) REFERENCES listing (id)
    ON UPDATE RESTRICT
);
</code>```

The data I'm trying to insert to this table has the following form:

```<code>url_path,caption,space_type,is_main,listing_id
JFK/015ec48e93480.jpg,An interior designer dream,,true,10000000
JFK/9184bd57e9f80.jpg,"Ready for you, YASS",,false,10000000
BCN/5ccd9b138c76.jpg,"Stay -- you're welcome",,false,10000001
BCN/5fbb3a5ac2b30.jpg,Warm sunlight throughout,,false,10000001
</code>```

And this is my LOAD DATA statement into the empty table from the MariaDB and MySQL documentation:

```<code>ALTER TABLE photo DISABLE KEYS;
BEGIN;
LOAD DATA INFILE '/path/to/photos.csv' INTO TABLE photo
  FIELDS
    OPTIONALLY ENCLOSED BY '"'
    TERMINATED BY ','
  LINES
    TERMINATED BY '\n'
  IGNORE 1 ROWS (url_path,caption,space_type,is_main,listing_id);
  SET id=NULL;
COMMIT;
ALTER TABLE photo ENABLE KEYS;
</code>```

The OPTIONALLY ENCLOSED BY is being used for the CHAR columns that have a comma in the text, and the IGNORE 1 ROWS is used to ignore the header row.

When I try to load the data, I get the following error:

```<code>ERROR 1193 (HY000) at line 33: Unknown system variable 'id'
</code>```

I've also tried adding SET id = NULL from answers in other StackOverflow posts like this one. What am I doing wrong?

答:
Have you tried putting the path in quotes?

As shown below...

```<code>url_path,caption,space_type,is_main,listing_id
"JFK/9184bd57e9f80.jpg","Ready for you, YASS",,false,10000000
</code>```

Body:
I have created a table that has the following definition:

CREATE TABLE vacayhome.photo (
  id INT NOT NULL AUTO_INCREMENT,
  url_path CHAR NOT NULL,
  caption CHAR NOT NULL,
  space_type CHAR NOT NULL,
  is_main BOOLEAN NOT NULL,
  listing_id INT NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (listing_id) REFERENCES listing (id)
    ON UPDATE RESTRICT
);

The data I'm trying to insert to this table has the following form:

url_path,caption,space_type,is_main,listing_id
JFK/015ec48e93480.jpg,An interior designer dream,,true,10000000
JFK/9184bd57e9f80.jpg,"Ready for you, YASS",,false,10000000
BCN/5ccd9b138c76.jpg,"Stay -- you're welcome",,false,10000001
BCN/5fbb3a5ac2b30.jpg,Warm sunlight throughout,,false,10000001

And this is my LOAD DATA statement into the empty table from the MariaDB and MySQL documentation:

ALTER TABLE photo DISABLE KEYS;
BEGIN;
LOAD DATA INFILE '/path/to/photos.csv' INTO TABLE photo
  FIELDS
    OPTIONALLY ENCLOSED BY '"'
    TERMINATED BY ','
  LINES
    TERMINATED BY '\n'
  IGNORE 1 ROWS (url_path,caption,space_type,is_main,listing_id);
  SET id=NULL;
COMMIT;
ALTER TABLE photo ENABLE KEYS;

The OPTIONALLY ENCLOSED BY is being used for the CHAR columns that have a comma in the text, and the IGNORE 1 ROWS is used to ignore the header row.

When I try to load the data, I get the following error:

ERROR 1193 (HY000) at line 33: Unknown system variable 'id'

I've also tried adding SET id = NULL from answers in other StackOverflow posts like this one. What am I doing wrong?

Body:
Have you tried putting the path in quotes?

As shown below...

url_path,caption,space_type,is_main,listing_id
"JFK/9184bd57e9f80.jpg","Ready for you, YASS",,false,10000000


问:
Regular expression troubles, escaped quotes
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

```<code>"Hello\" World" "Hello Universe" Hi
</code>```

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

```<code>public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}
</code>```

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind

答:
If you decide you want to forego regex, and do parsing instead, there are a couple of options.  If you are willing to have just a double quote or a single quote (but not both) as your quote, then you can use StreamTokenizer to solve this easily:

```<code>public static List<String> tokenize(String s) throws IOException {
    List<String> opts = new ArrayList<String>();
    StreamTokenizer st = new StreamTokenizer(new StringReader(s));
    st.quoteChar('\"');
    while (st.nextToken() != StreamTokenizer.TT_EOF) {
        opts.add(st.sval);
    }

    return opts;
}
</code>```

If you must support both quotes, here is a naive implementation that should work (caveat that a string like '"blah \" blah"blah' will yield something like 'blah " blahblah'. If that isn't OK, you will need to make some changes):

```<code>   public static List<String> splitSSV(String in) throws IOException {
        ArrayList<String> out = new ArrayList<String>();

        StringReader r = new StringReader(in);
        StringBuilder b = new StringBuilder();
        int inQuote = -1;
        boolean escape = false;
        int c;
        // read each character
        while ((c = r.read()) != -1) {
            if (escape) {  // if the previous char is escape, add the current char
                b.append((char)c);
                escape = false;
                continue;
            }
            switch (c) {
            case '\\':   // deal with escape char
                escape = true;
                break;
            case '\"':
            case '\'':  // deal with quote chars
                if (c == '\"' || c == '\'') {
                    if (inQuote == -1) {  // not in a quote
                        inQuote = c;  // now we are
                    } else {
                        inQuote = -1;  // we were in a quote and now we aren't
                    }
                }
                break;
            case ' ':
                if (inQuote == -1) {  // if we aren't in a quote, then add token to list
                    out.add(b.toString());
                    b.setLength(0);
                } else {
                    b.append((char)c); // else append space to current token
                }
                break;
            default:
                b.append((char)c);  // append all other chars to current token
            }
        }
        if (b.length() > 0) {
            out.add(b.toString()); // add final token to list
        }
        return out;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

"Hello\" World" "Hello Universe" Hi

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind

Body:
If you decide you want to forego regex, and do parsing instead, there are a couple of options.  If you are willing to have just a double quote or a single quote (but not both) as your quote, then you can use StreamTokenizer to solve this easily:

public static List<String> tokenize(String s) throws IOException {
    List<String> opts = new ArrayList<String>();
    StreamTokenizer st = new StreamTokenizer(new StringReader(s));
    st.quoteChar('\"');
    while (st.nextToken() != StreamTokenizer.TT_EOF) {
        opts.add(st.sval);
    }

    return opts;
}

If you must support both quotes, here is a naive implementation that should work (caveat that a string like '"blah \" blah"blah' will yield something like 'blah " blahblah'. If that isn't OK, you will need to make some changes):

   public static List<String> splitSSV(String in) throws IOException {
        ArrayList<String> out = new ArrayList<String>();

        StringReader r = new StringReader(in);
        StringBuilder b = new StringBuilder();
        int inQuote = -1;
        boolean escape = false;
        int c;
        // read each character
        while ((c = r.read()) != -1) {
            if (escape) {  // if the previous char is escape, add the current char
                b.append((char)c);
                escape = false;
                continue;
            }
            switch (c) {
            case '\\':   // deal with escape char
                escape = true;
                break;
            case '\"':
            case '\'':  // deal with quote chars
                if (c == '\"' || c == '\'') {
                    if (inQuote == -1) {  // not in a quote
                        inQuote = c;  // now we are
                    } else {
                        inQuote = -1;  // we were in a quote and now we aren't
                    }
                }
                break;
            case ' ':
                if (inQuote == -1) {  // if we aren't in a quote, then add token to list
                    out.add(b.toString());
                    b.setLength(0);
                } else {
                    b.append((char)c); // else append space to current token
                }
                break;
            default:
                b.append((char)c);  // append all other chars to current token
            }
        }
        if (b.length() > 0) {
            out.add(b.toString()); // add final token to list
        }
        return out;
    }


问:
How to select columns where value is not zero
How do you select columns where the value is not zero?

If I have 3 columns

```<code>column1|column2|column3
-------+-------+-------
   0   |   50  |   99
</code>```

I want the query to show only columns that have values > 0

so that the result will be

```<code>column2|column3
-------+-------
   50  |   99
</code>```

I have tried this:

```<code>SELECT * FROM `table1` WHERE `column1` != '0'
</code>```

答:
Would a json string containing the columns work for your purposes?

```<code>SELECT CONCAT(COALESCE(CASE WHEN column1 > 0 THEN JSON_OBJECT('column1', column1) END, ''),
              COALESCE(CASE WHEN column2 > 0 THEN JSON_OBJECT('column2', column2) END, ''),
              COALESCE(CASE WHEN column3 > 0 THEN JSON_OBJECT('column3', column3) END, '')
             )
FROM table1;
</code>```

This will return a json string only containing the columns that are > 0. So using your example this would return {"column2": 50}{"column3": 99}

Body:
How do you select columns where the value is not zero?

If I have 3 columns

column1|column2|column3
-------+-------+-------
   0   |   50  |   99

I want the query to show only columns that have values > 0

so that the result will be

column2|column3
-------+-------
   50  |   99

I have tried this:

SELECT * FROM `table1` WHERE `column1` != '0'

Body:
Would a json string containing the columns work for your purposes?

SELECT CONCAT(COALESCE(CASE WHEN column1 > 0 THEN JSON_OBJECT('column1', column1) END, ''),
              COALESCE(CASE WHEN column2 > 0 THEN JSON_OBJECT('column2', column2) END, ''),
              COALESCE(CASE WHEN column3 > 0 THEN JSON_OBJECT('column3', column3) END, '')
             )
FROM table1;

This will return a json string only containing the columns that are > 0. So using your example this would return {"column2": 50}{"column3": 99}


问:
template function pointers and lambdas
Hi I'm trying to sort out an issue with the following code:

```<code>template<typename... Args>
using Func = void (*)(Args... args);

template<typename... Args>
void do_test(Func<Args&...> f, Args&... args) {
    for (int i = 0; i != 100; i++)
      f(args...);
}

int main(){
    int x = 0;
    do_test(Func<int&>([](int &y) { y++; }), x);  // OK

    // Error - mismatched types 'void (*)(Args& ...)' and 'main()::<lambda(int&)>'
    do_test([](int &y) { y++; }, x);

    return x;
}
</code>```

https://godbolt.org/z/UaXxFJ

Can anyone explain why it is necessary to wrap the lambda in Func<int&>( )? Is there a way to avoid it? - because if the argument list is non-trivial it becomes quite tedious having to list out the argument types twice.

The goal here is to make a visitor pattern that the compiler can optimize away. I'm using it for an image processing algorithm where I want to reuse the code of the outer loops, with various bits of inner code. The Args are being used as something similar to a lambda capture, except using traditional function pointers so that the compiler can optimize them away - which it seems not to be able to do with std::function<>

答:
You can just allow the function to take any type, whether function pointer or lambda:

```<code>template<typename F, typename... Args>
void do_test(F f, Args&... args) {
    for (int i = 0; i != 100; i++)
      f(args...);
}
</code>```

Depending on your use case, consider taking f by-const-reference or forwarding reference (i.e. F&&), as well.

You should also consider changing the way you take the args function parameters. Usually in such a situation you would take them by forwarding reference, meaning Args&&... args instead of Args&... args. Otherwise you won't be able to call the function with rvalues arguments.

Or if you have some specific reason to accept only this one specific function pointer type, you can make the first function parameter a non-deduced context, given that the template arguments can already be deduced from the other function parameters:

```<code>template<typename... Args>
void do_test(std::type_identity_t<Func<Args&...>> f, Args&... args) {
    for (int i = 0; i != 100; i++)
      f(args...);
}
</code>```

std::type_identity_t is a C++20 feature, but can be easily implemented:

```<code>template<typename T>
struct type_identity {
    using type = T;
};

template<typename T>
using type_identity_t = typename type_identity<T>::type;
</code>```

Everything left to the scope resolution operator :: in type_identity<T>::type is a non-deduced context and so the first function parameter will not be used to deduce the Args, which in turn means that implicit conversions will be considered (e.g. the lambda to function pointer conversion).

Alternatively, as mentioned by @FrançoisAndrieux in the question comments, you can use the lambda + trick to convert the lambda to a function pointer at the call site:

```<code>do_test(+[](int &y) { y++; }, x);
</code>```

Also note that taking a function pointer of this specific type means that the function can only be called with functions that have exactly this type. For example args is always deduced to a reference type, so any possible function than may be used with this one must take only reference parameters. This is usually not what you want. Usually you want the loose behavior of std::function<R(Args...)>, which can be constructed from any function object that is callable with the specified Args and returns something that can be implicitly converted to R.

Title: template function pointers and lambdas

Body:
Hi I'm trying to sort out an issue with the following code:

template<typename... Args>
using Func = void (*)(Args... args);

template<typename... Args>
void do_test(Func<Args&...> f, Args&... args) {
    for (int i = 0; i != 100; i++)
      f(args...);
}

int main(){
    int x = 0;
    do_test(Func<int&>([](int &y) { y++; }), x);  // OK

    // Error - mismatched types 'void (*)(Args& ...)' and 'main()::<lambda(int&)>'
    do_test([](int &y) { y++; }, x);

    return x;
}

https://godbolt.org/z/UaXxFJ

Can anyone explain why it is necessary to wrap the lambda in Func<int&>( )? Is there a way to avoid it? - because if the argument list is non-trivial it becomes quite tedious having to list out the argument types twice.

The goal here is to make a visitor pattern that the compiler can optimize away. I'm using it for an image processing algorithm where I want to reuse the code of the outer loops, with various bits of inner code. The Args are being used as something similar to a lambda capture, except using traditional function pointers so that the compiler can optimize them away - which it seems not to be able to do with std::function<>

Body:
You can just allow the function to take any type, whether function pointer or lambda:

template<typename F, typename... Args>
void do_test(F f, Args&... args) {
    for (int i = 0; i != 100; i++)
      f(args...);
}

Depending on your use case, consider taking f by-const-reference or forwarding reference (i.e. F&&), as well.

You should also consider changing the way you take the args function parameters. Usually in such a situation you would take them by forwarding reference, meaning Args&&... args instead of Args&... args. Otherwise you won't be able to call the function with rvalues arguments.

Or if you have some specific reason to accept only this one specific function pointer type, you can make the first function parameter a non-deduced context, given that the template arguments can already be deduced from the other function parameters:

template<typename... Args>
void do_test(std::type_identity_t<Func<Args&...>> f, Args&... args) {
    for (int i = 0; i != 100; i++)
      f(args...);
}

std::type_identity_t is a C++20 feature, but can be easily implemented:

template<typename T>
struct type_identity {
    using type = T;
};

template<typename T>
using type_identity_t = typename type_identity<T>::type;

Everything left to the scope resolution operator :: in type_identity<T>::type is a non-deduced context and so the first function parameter will not be used to deduce the Args, which in turn means that implicit conversions will be considered (e.g. the lambda to function pointer conversion).

Alternatively, as mentioned by @FrançoisAndrieux in the question comments, you can use the lambda + trick to convert the lambda to a function pointer at the call site:

do_test(+[](int &y) { y++; }, x);

Also note that taking a function pointer of this specific type means that the function can only be called with functions that have exactly this type. For example args is always deduced to a reference type, so any possible function than may be used with this one must take only reference parameters. This is usually not what you want. Usually you want the loose behavior of std::function<R(Args...)>, which can be constructed from any function object that is callable with the specified Args and returns something that can be implicitly converted to R.


问:
Pasting columns from other sheets as row on different sheet
I am trying to write a script that will take data from columns on two different sheets and paste them into a row on a third sheet without overwriting each other.

```<code>Private Sub CommandButton1_Click()
 Dim InRangex1 As Range
 Dim OutRangex1 As Range

 Dim i As Long

 Set InRangex1 = Sheets("Line 1").Range("L4:L204")
 Set OutRangex1 = Sheets("Numeric Plot").Range("B1")
 InRangex1.Worksheet.Activate
 InRangex1.Select
 Selection.Copy
 OutRangex1.Worksheet.Activate
 OutRangex1.Select
 Selection.PasteSpecial Paste:=xlPasteValues, SkipBlanks:=True, Transpose:=True

 Dim InRangex2 As Range
 Dim OutRangex2 As Range

 Set InRangex2 = Sheets("Line 3").Range("L4:L204")
 Set OutRangex2 = Sheets("Numeric Plot").Range("B1").End(xlToRight).Offset(0, 1).Select
 InRangex2.Worksheet.Activate
 InRangex2.Select
 Selection.Copy
 OutRangex2.Worksheet.Activate
 OutRangex2.Select
 Selection.PasteSpecial Paste:=xlPasteValues, SkipBlanks:=True, Transpose:=True

End Sub
</code>```

I am getting a 424 "Object required" error when the second half of the script runs. Not sure where the problem is.

答:
Test this code, please. It it simpler, avoids Select, Activate, Copy and Paste and is very fast...

```<code>Private Sub CommandButton1_Click()
 Dim arr1 As Variant, arr2 As Variant, OutRangex2 As Range

 arr1 = Sheets("Line 1").Range("L4:L204").Value
 Sheets("Numeric Plot").Range("B1").Resize(1, UBound(arr1, 1)).Value = WorksheetFunction.Transpose(arr1)

 arr2 = Sheets("Line 3").Range("L4:L204").Value
 Set OutRangex2 = Sheets("Numeric Plot").Range("B1").End(xlToRight).Offset(0, 1)
  OutRangex2.Resize(1, UBound(arr2, 1)).Value = WorksheetFunction.Transpose(arr2)
End Sub
</code>```

I think the duplicates removal should be consider like being object of a new question, according to our rules...

Please test the next code. It works also using arrays and should be very speedy. Please let me know how it works. It could be integrated in the first sub, but I made it from scratch...

```<code>Sub removeDuplicate()
 Dim arrSort As Variant, lastCol As Long, lastRow As Long, arrSorted As Variant, sh As Worksheet
  Set sh = Sheets("Numeric Plot")
  lastCol = sh.Cells(1, sh.Cells.Columns.count).End(xlToLeft).column 'last col on the first row
  arrSort = sh.Range(sh.Cells(1, 2), sh.Cells(1, lastCol)).Value        'put the row values in an array
  'transpose the array in a column after the last one of the rows 1:
  sh.Cells(1, lastCol + 1).Resize(UBound(arrSort, 2), 1).Value = WorksheetFunction.Transpose(arrSort)
  'remove duplicates with Excel function:
  sh.Range(sh.Cells(1, lastCol + 1), sh.Cells(UBound(arrSort, 2), lastCol + 1)).RemoveDuplicates Columns:=1, Header:=xlNo
  lastRow = sh.Cells(sh.Cells.Rows.count, lastCol + 1).End(xlUp).row 'Last row after dupplicate elimination
  arrSorted = sh.Range(sh.Cells(1, lastCol + 1), sh.Cells(lastRow, lastCol + 1)).Value 'The cleared column pun in an array
    sh.Range(sh.Cells(1, 2), sh.Cells(1, lastCol)).Clear                     'clearing the data of the first row
    sh.Range(sh.Cells(1, lastCol + 1), sh.Cells(lastRow, lastCol + 1)).Clear 'clearing the data of temporary column
    Dim finalRng As Range
     Set finalRng = sh.Range("B1").Resize(1, UBound(arrSorted))
    finalRng.Value = WorksheetFunction.Transpose(arrSorted) 'transpose the fiterred array

   'sort the resulted range:
   finalRng.Sort Key1:=finalRng, Order1:=xlAscending, Orientation:=xlLeftToRight
End Sub
</code>```

Body:
I am trying to write a script that will take data from columns on two different sheets and paste them into a row on a third sheet without overwriting each other.

Private Sub CommandButton1_Click()
 Dim InRangex1 As Range
 Dim OutRangex1 As Range

 Dim i As Long

 Set InRangex1 = Sheets("Line 1").Range("L4:L204")
 Set OutRangex1 = Sheets("Numeric Plot").Range("B1")
 InRangex1.Worksheet.Activate
 InRangex1.Select
 Selection.Copy
 OutRangex1.Worksheet.Activate
 OutRangex1.Select
 Selection.PasteSpecial Paste:=xlPasteValues, SkipBlanks:=True, Transpose:=True

 Dim InRangex2 As Range
 Dim OutRangex2 As Range

 Set InRangex2 = Sheets("Line 3").Range("L4:L204")
 Set OutRangex2 = Sheets("Numeric Plot").Range("B1").End(xlToRight).Offset(0, 1).Select
 InRangex2.Worksheet.Activate
 InRangex2.Select
 Selection.Copy
 OutRangex2.Worksheet.Activate
 OutRangex2.Select
 Selection.PasteSpecial Paste:=xlPasteValues, SkipBlanks:=True, Transpose:=True

End Sub

I am getting a 424 "Object required" error when the second half of the script runs. Not sure where the problem is.

Body:
Test this code, please. It it simpler, avoids Select, Activate, Copy and Paste and is very fast...

Private Sub CommandButton1_Click()
 Dim arr1 As Variant, arr2 As Variant, OutRangex2 As Range

 arr1 = Sheets("Line 1").Range("L4:L204").Value
 Sheets("Numeric Plot").Range("B1").Resize(1, UBound(arr1, 1)).Value = WorksheetFunction.Transpose(arr1)

 arr2 = Sheets("Line 3").Range("L4:L204").Value
 Set OutRangex2 = Sheets("Numeric Plot").Range("B1").End(xlToRight).Offset(0, 1)
  OutRangex2.Resize(1, UBound(arr2, 1)).Value = WorksheetFunction.Transpose(arr2)
End Sub

I think the duplicates removal should be consider like being object of a new question, according to our rules...

Please test the next code. It works also using arrays and should be very speedy. Please let me know how it works. It could be integrated in the first sub, but I made it from scratch...

Sub removeDuplicate()
 Dim arrSort As Variant, lastCol As Long, lastRow As Long, arrSorted As Variant, sh As Worksheet
  Set sh = Sheets("Numeric Plot")
  lastCol = sh.Cells(1, sh.Cells.Columns.count).End(xlToLeft).column 'last col on the first row
  arrSort = sh.Range(sh.Cells(1, 2), sh.Cells(1, lastCol)).Value        'put the row values in an array
  'transpose the array in a column after the last one of the rows 1:
  sh.Cells(1, lastCol + 1).Resize(UBound(arrSort, 2), 1).Value = WorksheetFunction.Transpose(arrSort)
  'remove duplicates with Excel function:
  sh.Range(sh.Cells(1, lastCol + 1), sh.Cells(UBound(arrSort, 2), lastCol + 1)).RemoveDuplicates Columns:=1, Header:=xlNo
  lastRow = sh.Cells(sh.Cells.Rows.count, lastCol + 1).End(xlUp).row 'Last row after dupplicate elimination
  arrSorted = sh.Range(sh.Cells(1, lastCol + 1), sh.Cells(lastRow, lastCol + 1)).Value 'The cleared column pun in an array
    sh.Range(sh.Cells(1, 2), sh.Cells(1, lastCol)).Clear                     'clearing the data of the first row
    sh.Range(sh.Cells(1, lastCol + 1), sh.Cells(lastRow, lastCol + 1)).Clear 'clearing the data of temporary column
    Dim finalRng As Range
     Set finalRng = sh.Range("B1").Resize(1, UBound(arrSorted))
    finalRng.Value = WorksheetFunction.Transpose(arrSorted) 'transpose the fiterred array

   'sort the resulted range:
   finalRng.Sort Key1:=finalRng, Order1:=xlAscending, Orientation:=xlLeftToRight
End Sub


问:
How to get full list of Gatsby.js routes/endpoints in Cypress tests
I am currently writing some E2E tests with Cypress for a Gatsby based project.

For one test in particular, i'd like to loop through all pages of my Gatsby site, and in order to achieve this, I need a test fixture (e.g. endpoints.json) which includes an array of all urls.

I've tried the following methods (but all have limitations):

1. Running a node script to check the folder structure in the src/pages folder

Limitation - This doesn't account for dynamically generated pages in gatsby-node.js with graphql

2. Running a node script to scrape URLs in the sitemap.xml file generated with gatsby-plugin-sitemap

Limitation - The plugin only generated a sitemap.xml file in prod builds and not in dev (cypress runs a dev server)

Would be more than grateful if anyone has a suggestion for how we would get a full list of Gatsby endpoints in this environment.

答:
You might just want to generate a file in the desired format on-build using the data in GraphQL:

```<code>// gatsby-node.js
const path = require("path")
const fs = require("fs").promises

exports.onPostBuild = async ({ graphql }) => {
  const { data } = await graphql(`
    {
      pages: allSitePage {
        nodes {
          path
        }
      }
    }
  `)

  return fs.writeFile(
    path.resolve(__dirname, "all-pages.txt"),
    data.pages.nodes.map(node => node.path).join("\n")
  )
}
</code>```

This creates a .txt file with each page’s path on a line. You could also just write out the data as JSON by passing in JSON.stringify(data.pages) as the second argument to writeFile, though.

Body:
You might just want to generate a file in the desired format on-build using the data in GraphQL:

// gatsby-node.js
const path = require("path")
const fs = require("fs").promises

exports.onPostBuild = async ({ graphql }) => {
  const { data } = await graphql(`
    {
      pages: allSitePage {
        nodes {
          path
        }
      }
    }
  `)

  return fs.writeFile(
    path.resolve(__dirname, "all-pages.txt"),
    data.pages.nodes.map(node => node.path).join("\n")
  )
}

This creates a .txt file with each page’s path on a line. You could also just write out the data as JSON by passing in JSON.stringify(data.pages) as the second argument to writeFile, though.


答:
You want to start at the first whitespace and count until the last one.

```<code>int spaceCount = 0;
int i = line.indexOf(" "); // (You can replace this with a while loop to consider other whitespace characters)
while (line[i].equals(" ") && i < line.length) { // (Change criteria here if you want to consider other whitespace)
    i++;
    spaceCount++;
}
</code>```

If whitespace includes more characters than just a space, replace the indexOf line with a while loop that iterates to the first whitespace, and change the other while loop's criteria to go while " \n\t".contains(line[i]) (you can include whatever characters you consider whitespace in that string).

Title: How the count the number of whitespaces between the first and second word in Java

Body:
I have a string that looks like the following:

Here    is a test

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

Body:
You want to start at the first whitespace and count until the last one.

int spaceCount = 0;
int i = line.indexOf(" "); // (You can replace this with a while loop to consider other whitespace characters)
while (line[i].equals(" ") && i < line.length) { // (Change criteria here if you want to consider other whitespace)
    i++;
    spaceCount++;
}

If whitespace includes more characters than just a space, replace the indexOf line with a while loop that iterates to the first whitespace, and change the other while loop's criteria to go while " \n\t".contains(line[i]) (you can include whatever characters you consider whitespace in that string).


问:
I have an excel file. In which there are multiple columns and rows how does one filter the columns by the rows for ggplot
I have an excel file that has data as such:

I have to create a box plot and am using ggplot. How does one filter it such that the results for Lead will show based on what the Ward number is. For example if I say Ward==1 then it will show the results Lead 5.0, 7.8 and 6.3 and create a box plot with these . I am trying to create a geom_boxplot and stat_boxplot.

答:
We can specify the group as 'Ward' and apply the geom_boxplot

```<code>library(ggplot2)
library(dplyr)
df1 %>%
  mutate(Ward = factor(Ward)) %>%
  ggplot(aes(x = Ward, y = Lead, fill = Ward)) +
       geom_boxplot()
</code>```

-output

data

```<code>df1 <- structure(list(ID = 1:5, Ward = c(1L, 1L, 2L, 3L, 1L), Lead = c(5,
7.8, 3.6, 2.8, 6.3)), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
We can specify the group as 'Ward' and apply the geom_boxplot

library(ggplot2)
library(dplyr)
df1 %>%
  mutate(Ward = factor(Ward)) %>%
  ggplot(aes(x = Ward, y = Lead, fill = Ward)) +
       geom_boxplot()

-output

data

df1 <- structure(list(ID = 1:5, Ward = c(1L, 1L, 2L, 3L, 1L), Lead = c(5,
7.8, 3.6, 2.8, 6.3)), class = "data.frame", row.names = c(NA,
-5L))


问:
Randomize setInterval ( How to rewrite same random after random interval)
I'd like to know how to achieve:
generate a random number after a random number of time. And reuse it.

```<code>function doSomething(){
     // ... do something.....
}

var rand = 300; // initial rand time

i = setinterval(function(){

     doSomething();
     rand = Math.round(Math.random()*(3000-500))+500; // generate new time (between 3sec and 500"s)

}, rand);
</code>```

And do it repeatedly.

So far I was able to generate a random interval, but it last the same until the page was refreshed (generating than a different time- interval).

Thanks

答:
Here's a reusable version that can be cleared. Open-sourced as an NPM package with IntelliSense enabled.

Utility Function

```<code>const setRandomInterval = (intervalFunction, minDelay, maxDelay) => {
  let timeout;

  const runInterval = () => {
    const timeoutFunction = () => {
      intervalFunction();
      runInterval();
    };

    const delay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;

    timeout = setTimeout(timeoutFunction, delay);
  };

  runInterval();

  return {
    clear() { clearTimeout(timeout) },
  };
};
</code>```

Usage

```<code>const interval = setRandomInterval(() => console.log('Hello World!'), 1000, 5000);

// // Clear when needed.
// interval.clear();
</code>```

Body:
I'd like to know how to achieve:
generate a random number after a random number of time. And reuse it.

function doSomething(){
     // ... do something.....
}

var rand = 300; // initial rand time

i = setinterval(function(){

     doSomething();
     rand = Math.round(Math.random()*(3000-500))+500; // generate new time (between 3sec and 500"s)

}, rand);

And do it repeatedly.

So far I was able to generate a random interval, but it last the same until the page was refreshed (generating than a different time- interval).

Thanks

Body:
Here's a reusable version that can be cleared. Open-sourced as an NPM package with IntelliSense enabled.

Utility Function

const setRandomInterval = (intervalFunction, minDelay, maxDelay) => {
  let timeout;

  const runInterval = () => {
    const timeoutFunction = () => {
      intervalFunction();
      runInterval();
    };

    const delay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;

    timeout = setTimeout(timeoutFunction, delay);
  };

  runInterval();

  return {
    clear() { clearTimeout(timeout) },
  };
};

Usage

const interval = setRandomInterval(() => console.log('Hello World!'), 1000, 5000);

// // Clear when needed.
// interval.clear();


问:
docker-compose: Can't connect application container with mysql container
I am having trouble to make the container that contains a python/bottle web app to reach the mysql server/container.

docker-compose build:

```<code>Step 8/9 : RUN python3 bin/initdb.py
 ---> Running in 30d963677711
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/lib/python3.7/socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "bin/initdb.py", line 18, in <module>
    password=config('MYSQL_PASSWORD', default='tspass')
  File "/usr/local/lib/python3.7/dist-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name or service not known)")
ERROR: Service 'web' failed to build: The command '/bin/sh -c python3 bin/initdb.py' returned a non-zero code: 1
</code>```

docker-compose.yml:

```<code>version: '3'

services:
  db:
    container_name: mysql
    image: mysql
    env_file: .env
    restart: always
    volumes:
      - ./init.sql:/app/init.sql
    networks:
      - "dock"
    expose:
      - "3306"
    # on host it's mapped on 33060

  web:
    container_name: app
    build: .
    env_file: .env
    restart: always
    depends_on:
      - db
    links:
      - db:db
    networks:
      - "dock"
    ports:
      - "8888:8888"

networks:
  dock:
</code>```

Dockerfile:

```<code>FROM debian:stable

EXPOSE 8888
# CMD ["./bin/run.sh"]

RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential python3 python3-dev python3-pip python3-setuptools
RUN pip3 install --upgrade pip && \
    rm -rf /var/lib/apt/lists/* && rm -rf /var/cache/apt/archives/*.deb

WORKDIR /app

COPY . /app/
RUN pip install --no-cache-dir -r /app/requirements.txt

RUN python3 bin/initdb.py
RUN python3 main.py 0.0.0.0 8888
</code>```

initdb.py:

```<code>#!/usr/bin/env python

import pymysql
from decouple import Config, RepositoryEnv

...

conn = pymysql.connect(
    host=config('DB_HOST', default='db'),  # NOT ACCESSIBLE?
    port=config('DB_PORT', default=3306, cast=int),
    db=config('MYSQL_DATABASE', default='db1'),
    user=config('MYSQL_USER', default='user'),
    password=config('MYSQL_PASSWORD', default='password')
)
</code>```

.env:

```<code># DEPLOYMENT
DB_HOST=db
DB_PORT=3306

# DOCKER MYSQL
MYSQL_HOST="0.0.0.0"
MYSQL_ROOT_HOST="%"
MYSQL_ROOT_USER=root
MYSQL_ROOT_PASSWORD=toor
MYSQL_DATABASE=db1
MYSQL_USER=user
MYSQL_PASSWORD=password
</code>```

Any thoughts how to debug this?

PS: The above setup works perfectly without docker, by changing DB_HOST=db to DB_HOST=localhost and running python main.py

答:
Basically, any other container/service is not present in the build stage, so you can't access any other container (like 'db').
You may run any startup script during the container startup using the dockerfile CMD or ENTRYPOINT, for example:

myEntryPoint.sh (created in the root folder

```<code>python3 bin/initdb.py
python3 main.py 0.0.0.0 8888
</code>```

Dockerfile

```<code>COPY myEntryPoint.sh /
RUN chmod +x /myEntryPoint.sh
ENTRYPOINT ["/myEntryPoint.sh"]
</code>```

Body:
I am having trouble to make the container that contains a python/bottle web app to reach the mysql server/container.

docker-compose build:

Step 8/9 : RUN python3 bin/initdb.py
 ---> Running in 30d963677711
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/lib/python3.7/socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "bin/initdb.py", line 18, in <module>
    password=config('MYSQL_PASSWORD', default='tspass')
  File "/usr/local/lib/python3.7/dist-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "/usr/local/lib/python3.7/dist-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno -2] Name or service not known)")
ERROR: Service 'web' failed to build: The command '/bin/sh -c python3 bin/initdb.py' returned a non-zero code: 1

docker-compose.yml:

version: '3'

services:
  db:
    container_name: mysql
    image: mysql
    env_file: .env
    restart: always
    volumes:
      - ./init.sql:/app/init.sql
    networks:
      - "dock"
    expose:
      - "3306"
    # on host it's mapped on 33060

  web:
    container_name: app
    build: .
    env_file: .env
    restart: always
    depends_on:
      - db
    links:
      - db:db
    networks:
      - "dock"
    ports:
      - "8888:8888"

networks:
  dock:

Dockerfile:

FROM debian:stable

EXPOSE 8888
# CMD ["./bin/run.sh"]

RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential python3 python3-dev python3-pip python3-setuptools
RUN pip3 install --upgrade pip && \
    rm -rf /var/lib/apt/lists/* && rm -rf /var/cache/apt/archives/*.deb

WORKDIR /app

COPY . /app/
RUN pip install --no-cache-dir -r /app/requirements.txt

RUN python3 bin/initdb.py
RUN python3 main.py 0.0.0.0 8888

initdb.py:

#!/usr/bin/env python

import pymysql
from decouple import Config, RepositoryEnv

...

conn = pymysql.connect(
    host=config('DB_HOST', default='db'),  # NOT ACCESSIBLE?
    port=config('DB_PORT', default=3306, cast=int),
    db=config('MYSQL_DATABASE', default='db1'),
    user=config('MYSQL_USER', default='user'),
    password=config('MYSQL_PASSWORD', default='password')
)

.env:

# DEPLOYMENT
DB_HOST=db
DB_PORT=3306

# DOCKER MYSQL
MYSQL_HOST="0.0.0.0"
MYSQL_ROOT_HOST="%"
MYSQL_ROOT_USER=root
MYSQL_ROOT_PASSWORD=toor
MYSQL_DATABASE=db1
MYSQL_USER=user
MYSQL_PASSWORD=password

Any thoughts how to debug this?

PS: The above setup works perfectly without docker, by changing DB_HOST=db to DB_HOST=localhost and running python main.py

Body:
Basically, any other container/service is not present in the build stage, so you can't access any other container (like 'db').
You may run any startup script during the container startup using the dockerfile CMD or ENTRYPOINT, for example:

myEntryPoint.sh (created in the root folder

python3 bin/initdb.py
python3 main.py 0.0.0.0 8888

Dockerfile

COPY myEntryPoint.sh /
RUN chmod +x /myEntryPoint.sh
ENTRYPOINT ["/myEntryPoint.sh"]


问:
Clarity Design how to use e.g. .clr-row, only possible inside of content-area?
Maybe this is a basic question, if I copy the below code into a

 the window will show the horizontal scroll, but if the code goes to a

 then I have the expected behavior.

        4

        6

        2

```

e.g. the .clr-row must be only used inside a content-area ?
I'm using Angular 9 with Clarity Design 3.0.0-next.8.

Thank you for any hint.

答:
Yes, you should use clr-row inside of the .content-area container element.

We disucuss application layout and how it fits with the variaous navigation patterns here: https://v2.clarity.design/app-layout

But its not explicitly called out to use the layout classes and apply them to elements inside of the content-area.

Body:
Maybe this is a basic question, if I copy the below code into a

 the window will show the horizontal scroll, but if the code goes to a

 then I have the expected behavior.

        4

        6

        2

e.g. the .clr-row must be only used inside a content-area ?
I'm using Angular 9 with Clarity Design 3.0.0-next.8.

Thank you for any hint.


问:
Bracket Matching - Find closing bracket with input bracket index - ValueError
newb here looking for help with my bracket code. I want to find the index of the closing bracket
from a open/close bracket string given a starting index

```<code>def matching_bracket(string, idx):
    string = list(string)
    a = {
        "(": ")",
        "[": "]",
        "{": "}",
        "<": ">"
    }
    close_bracket = a[string[idx]]
    if idx != ''.join(string).rindex(string[idx]):      #if open bracket is first bracket
        b = ''.join(string).rindex(string[idx])         #rightmost open bracket
        c = string[b:].index(close_bracket)             #next closest close bracket
        string[b], string[b+c:] = ".", "."              #replace both
        string = matching_bracket(''.join(string), idx)  # recurse
    else:
        d = string[idx:].index(close_bracket)
        return(idx + d)

matching_bracket("(([()]))",0)          #this fails, get error "ValueError: ')' is not in list"

matching_bracket('({})', 0) == 3             #yet these few output a correct val???
matching_bracket('([])', 1) == 2
matching_bracket('()()', 2) == 3
</code>```

can anyone help me???

答:
This is kind of an odd way to do this (I would usually do things like this with a stack). But I can see a few issues, including the one that causes the value error.

The first is that string[b+c:] replaces everything from index b+c onward, you really wanted string[b+c]. So on the first run "(([()]))" becomes "(([..", which is not what you want.

The second is that you're not returning the value returned by your recursive step. I updated here those.

```<code>def matching_bracket(string, idx):
    a = {
        "(": ")",
        "[": "]",
        "{": "}",
        "<": ">"
    }
    close_bracket = a[string[idx]]

    if idx != string.rindex(string[idx]):      #if open bracket is first bracket
        b = string.rindex(string[idx])         #rightmost open bracket
        c = string[b:].index(close_bracket)             #next closest close bracket
        str_list = list(string)
        str_list[b], str_list[b+c] = ".", "."              #replace both
        return matching_bracket(''.join(str_list), idx)  # recurse
    else:
        d = string[idx:].index(close_bracket)
        return idx + d
</code>```

Hopefully that clears things up for you.

Body:
newb here looking for help with my bracket code. I want to find the index of the closing bracket
from a open/close bracket string given a starting index

def matching_bracket(string, idx):
    string = list(string)
    a = {
        "(": ")",
        "[": "]",
        "{": "}",
        "<": ">"
    }
    close_bracket = a[string[idx]]
    if idx != ''.join(string).rindex(string[idx]):      #if open bracket is first bracket
        b = ''.join(string).rindex(string[idx])         #rightmost open bracket
        c = string[b:].index(close_bracket)             #next closest close bracket
        string[b], string[b+c:] = ".", "."              #replace both
        string = matching_bracket(''.join(string), idx)  # recurse
    else:
        d = string[idx:].index(close_bracket)
        return(idx + d)

matching_bracket("(([()]))",0)          #this fails, get error "ValueError: ')' is not in list"

matching_bracket('({})', 0) == 3             #yet these few output a correct val???
matching_bracket('([])', 1) == 2
matching_bracket('()()', 2) == 3

can anyone help me???

Body:
This is kind of an odd way to do this (I would usually do things like this with a stack). But I can see a few issues, including the one that causes the value error.

The first is that string[b+c:] replaces everything from index b+c onward, you really wanted string[b+c]. So on the first run "(([()]))" becomes "(([..", which is not what you want.

The second is that you're not returning the value returned by your recursive step. I updated here those.

def matching_bracket(string, idx):
    a = {
        "(": ")",
        "[": "]",
        "{": "}",
        "<": ">"
    }
    close_bracket = a[string[idx]]

    if idx != string.rindex(string[idx]):      #if open bracket is first bracket
        b = string.rindex(string[idx])         #rightmost open bracket
        c = string[b:].index(close_bracket)             #next closest close bracket
        str_list = list(string)
        str_list[b], str_list[b+c] = ".", "."              #replace both
        return matching_bracket(''.join(str_list), idx)  # recurse
    else:
        d = string[idx:].index(close_bracket)
        return idx + d

Hopefully that clears things up for you.


问:
Dynamic pans in Audiomath not completely smooth
I've been trying to get an effect similar to the dynamic-panning demo from in the audiomath examples:

import math
import audiomath as am
s = am.TestSound('12').MixDownToMono()
p = am.Player(s)
period_in_seconds = 4.0
p.Play(loop=True, pan=lambda t: math.sin(2 * math.pi * t / period_in_seconds))
```

However, the pan doesn't sound smooth: the volume swells when the sound is in the middle and fades slightly at either side. Any advice on how can I make transitions like this sound smooth?

答:
From the .pan property docstring:

The way levels are computed from scalar values between -1 and +1 depends on .norm.

and accordingly from the .norm property docstring:

For a Player instance p, if you set p.pan to a scalar value between -1 and +1, the relative levels of left and right channels are computed such that::

left ** p.norm + right ** p.norm = 1

The value p.norm=2 produces a natural-sounding pan but it means that stereo sounds are reduced to 70.71% of their maximum amplitude by default. So instead, the default is to use the infinity-norm, p.norm='inf', which ensures that the larger of the two sides is always 1.0

So the default setting is indeed a non-smooth pan.  Adding norm=2 to your Player properties might be the way to go—that would keep total signal power constant across channels.  Incidentally, the most sensitive way to judge this would be by using a continuous tone stimulus like you get from ToneTest():

```<code>import math, audiomath as am
am.RequireAudiomathVersion('1.10')

period_in_seconds = 4.0
p = am.ToneTest(norm=2, pan=lambda t: math.sin(2 * math.pi * t / period_in_seconds) )
p.Play()
# now experiment with `p.norm` while it's playing
</code>```

You could also try norm=1 (keeps the sum of the channel amplitudes constant instead of power).

Body:
I've been trying to get an effect similar to the dynamic-panning demo from in the audiomath examples:

import math
import audiomath as am
s = am.TestSound('12').MixDownToMono()
p = am.Player(s)
period_in_seconds = 4.0
p.Play(loop=True, pan=lambda t: math.sin(2 * math.pi * t / period_in_seconds))

However, the pan doesn't sound smooth: the volume swells when the sound is in the middle and fades slightly at either side. Any advice on how can I make transitions like this sound smooth?

Body:
From the .pan property docstring:

The way levels are computed from scalar values between -1 and +1 depends on .norm.

and accordingly from the .norm property docstring:

For a Player instance p, if you set p.pan to a scalar value between -1 and +1, the relative levels of left and right channels are computed such that::

left ** p.norm + right ** p.norm = 1

The value p.norm=2 produces a natural-sounding pan but it means that stereo sounds are reduced to 70.71% of their maximum amplitude by default. So instead, the default is to use the infinity-norm, p.norm='inf', which ensures that the larger of the two sides is always 1.0

So the default setting is indeed a non-smooth pan.  Adding norm=2 to your Player properties might be the way to go—that would keep total signal power constant across channels.  Incidentally, the most sensitive way to judge this would be by using a continuous tone stimulus like you get from ToneTest():

import math, audiomath as am
am.RequireAudiomathVersion('1.10')

period_in_seconds = 4.0
p = am.ToneTest(norm=2, pan=lambda t: math.sin(2 * math.pi * t / period_in_seconds) )
p.Play()
# now experiment with `p.norm` while it's playing

You could also try norm=1 (keeps the sum of the channel amplitudes constant instead of power).