问:
EXEC statement and Transaction Scope
This seemed so easy at first but everything I know seems to be wrong again.

Looking at PAQ's the consensus seems to be that EXEC does not start an implicit transaction, you can test this doing :

```<code>create procedure usp_foo
as
begin
  select @@trancount;
end
go

exec usp_foo;
</code>```

which returns 0.

If you however step through this with the T-SQL debugger @@Transaction is in fact 1 inside the procedure according to the watch, although it does return 0 ...

So I think this is a side-effect of the debugger, but then I write some code to test it, do an update in a table and then select max (id) out the, the classic :

```<code>create table nextid
(
  id int
)

insert into nextid values (0)

create procedure nextid
as
BEGIN
  UPDATE nextid set id = id + 1
  select max(id) from nextid
END
</code>```

So I am expecting this to give out duplicate id's as executed in parallel 2 updates can complete before the 2 selects fetching the last id and returning the same value, but try as I might hitting it from multiple machines I cannot make it break. When monitoring the locks and transactions on the machine it reports that the exec is happening in a transaction and importantly, all the statements inside the exec are treated as one unit of work/one transaction.

I would understand if the update was in a transaction and this was the cause of the lock, but the lock seems to remain until after the select.

If I trace with profiler I can see that a transaction ID is provided for the entire execution of the EXEC statement, and transaction ID is not 0 as I would expect while executing ...

Can someone please explain to me where I am missing the plot or am I wrong and it is in fact safe to generate ID's like that?

答:
Your test must be giving you correct results because you are not fast enough to invoke the second call in between these two statements. Try adding a delay and you can see that the test would start failing.

```<code>CREATE TABLE NextID
(
    ID int
)
GO

INSERT INTO NextID VALUES (0)
GO

CREATE PROC GetNextID
AS
BEGIN
    UPDATE NextID SET ID = ID + 1
    WAITFOR DELAY '00:00:05'
    SELECT Max(ID) FROM NextID
END
</code>```

Issue an EXEC GetNextID and issue another EXEC GetNextID as soon as you can from another session. About 5 seconds later both EXEC would return same result i.e. incorrect value. Now change the SP to

```<code>CREATE PROC GetNextID
AS
BEGIN
    BEGIN TRAN

    UPDATE NextID SET ID = ID + 1
    WAITFOR DELAY '00:00:05'
    SELECT Max(ID) FROM NextID

    COMMIT TRAN
END
</code>```

and repeat the above test. You would see that both calls would return correct value. In addition second call (if issued as soon as possible) would return result approximately in 10 seconds because the UPDATE is blocked and has to wait 5 seconds (for the first call to COMMIT) and then its own 5 second wait.

Title: EXEC statement and Transaction Scope

Body:
This seemed so easy at first but everything I know seems to be wrong again.

Looking at PAQ's the consensus seems to be that EXEC does not start an implicit transaction, you can test this doing :

create procedure usp_foo
as
begin
  select @@trancount;
end
go

exec usp_foo;

which returns 0.

If you however step through this with the T-SQL debugger @@Transaction is in fact 1 inside the procedure according to the watch, although it does return 0 ...

So I think this is a side-effect of the debugger, but then I write some code to test it, do an update in a table and then select max (id) out the, the classic :

create table nextid
(
  id int
)

insert into nextid values (0)

create procedure nextid
as
BEGIN
  UPDATE nextid set id = id + 1
  select max(id) from nextid
END

So I am expecting this to give out duplicate id's as executed in parallel 2 updates can complete before the 2 selects fetching the last id and returning the same value, but try as I might hitting it from multiple machines I cannot make it break. When monitoring the locks and transactions on the machine it reports that the exec is happening in a transaction and importantly, all the statements inside the exec are treated as one unit of work/one transaction.

I would understand if the update was in a transaction and this was the cause of the lock, but the lock seems to remain until after the select.

If I trace with profiler I can see that a transaction ID is provided for the entire execution of the EXEC statement, and transaction ID is not 0 as I would expect while executing ...

Can someone please explain to me where I am missing the plot or am I wrong and it is in fact safe to generate ID's like that?

Body:
Your test must be giving you correct results because you are not fast enough to invoke the second call in between these two statements. Try adding a delay and you can see that the test would start failing.

CREATE TABLE NextID
(
    ID int
)
GO

INSERT INTO NextID VALUES (0)
GO

CREATE PROC GetNextID
AS
BEGIN
    UPDATE NextID SET ID = ID + 1
    WAITFOR DELAY '00:00:05'
    SELECT Max(ID) FROM NextID
END

Issue an EXEC GetNextID and issue another EXEC GetNextID as soon as you can from another session. About 5 seconds later both EXEC would return same result i.e. incorrect value. Now change the SP to

CREATE PROC GetNextID
AS
BEGIN
    BEGIN TRAN

    UPDATE NextID SET ID = ID + 1
    WAITFOR DELAY '00:00:05'
    SELECT Max(ID) FROM NextID

    COMMIT TRAN
END

and repeat the above test. You would see that both calls would return correct value. In addition second call (if issued as soon as possible) would return result approximately in 10 seconds because the UPDATE is blocked and has to wait 5 seconds (for the first call to COMMIT) and then its own 5 second wait.


来源: stackexchange

问:
How can I execute command line arguments in a node.js script
Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

```<code>const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})
</code>```

But if I run the script now, nothing happens.

What i've tried so far:
1. I tried to save the output in a constant and tried to output this on a console

```<code>const found = find().then(devices => {
    devices
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);
</code>```

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards,
Michael

答:
Certainly worth asking! JS can be a confusing language to learn.

If a function returns a Promise (as find does) then logging what it returns is not normally very useful. A Promise is something which will at some point be able to potentially give some sort of useful value.

The .then part of your function is where you can use the value that the promise contains. A Promise will run the function contained in .then once it has got the value back. So doing something like:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})
```

Means that when the function which finds the devices has got a value back, it will log that value.

ContentLicense: CC BY-SA 4.0

Body:
Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

But if I run the script now, nothing happens.

What i've tried so far:
1. I tried to save the output in a constant and tried to output this on a console

const found = find().then(devices => {
    devices
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards,
Michael

Body:
Certainly worth asking! JS can be a confusing language to learn.

If a function returns a Promise (as find does) then logging what it returns is not normally very useful. A Promise is something which will at some point be able to potentially give some sort of useful value.

The .then part of your function is where you can use the value that the promise contains. A Promise will run the function contained in .then once it has got the value back. So doing something like:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})

Means that when the function which finds the devices has got a value back, it will log that value.


问:
Include JavaScript file in partial views
I am wondering what the best practice is for including javascript files inside partial views. Once rendered this will end up as a js include tag in the middle of my page's html. From my point of view this isn't a nice way of doing this. They belong in the head tag and as such should not prevent the browser from rendering the html in one go.

An example:
I am using a jquery picturegallery plugin inside a 'PictureGallery' partial view as this partial view will be used on several pages. This plugin only needs to be loaded when this view is used and I don't want to have to need to know which plugins each partial view is using...

Thanks for your answers.

答:
So, this is kind of an old question, but I found it while trying to solve a recent issue.  I asked a question and answered it here.  Here is a copy of that answer.  It is similar to the OP's answer, but avoids using TempData.

One solution is to implement an Html helper extension function which will only load a script once.  See below.  (this can work for CSS and other included files, too).

Implement an extension for the HtmlHelper class and a private backing class as a singleton per HttpContext.

```<code>public static class YourHtmlHelperExtensionClass
{
    private class TagSrcAttrTracker
    {
        private TagSrcAttrTracker() { }

        public Dictionary<string, string> sources { get; } = new Dictionary<string, string>();

        public static TagSrcAttrTrackerInstance {
            get {
                IDictionary items = HttpContext.Current.Items;
                const string instanceName = "YourClassInstanceNameMakeSureItIsUniqueInThisDictionary";

                if(!items.Contains(instanceName))
                    items[instanceName] = new TagSrcAttrTracker();

                return items[instanceName] as TagSrcAttrTracker;
            }
        }
    }

    public static MvcHtmlString IncludeScriptOnlyOnce(this HtmlHelper helper, string urlOfScript)
    {
        if(TagSrcAttrTracker.Instance.sources.ContainsKey(urlOfScript))
            return null;

        TagSrcAttrTracker.Instance.sources[urlOfScript] = urlOfScript;

        TagBuilder script = new TagBuilder("script");
        scriptTag.MergeAttribute("src", urlOfScript);

        return MvcHtmlString.Create(script.ToString());
    }
}
</code>```

Then, separate the JavaScript and other code into separate files.

Example .js file contents

```<code>class MyClass{
    myFunction() {
        constructor(divId){
            this._divId = divId
        }

        doSomething() {
            // do something with a div with id == divId
        }
    }
}
</code>```

Example .cshtml file contents for partial view

```<code><link rel="stylesheet" type="text/css" href="~/Content/CustomCSS/MyPartialView.css"/>

<div id="@ViewBag.id">
    Some content!  Yay!
</div>

@Html.IncludeScriptOnlyOnce("/Scripts/CustomScripts/MyPartialView.js")
</code>```

Example .cshtml file that consumes the partial view

```<code>...
<body>
    <h1>Here is some content!</h1>
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_1"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_2"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_3"} })
</body>
<script>
$().ready(
    const id1Functionality = new MyClass("id_1") // forgive the poor naming :-)
    const id2Functionality = new MyClass("id_3")
    const id3Functionality = new MyClass("id_2")

    id1Functionality.doSomething();
    id2Functionality.doSomething();
    id3Functionality.doSomething();
)
</script>
</code>```

The partial view may have been included more than once and the JavaScript is packaged with the partial view, but the .js file is only included in the page once, hence no complaining by the browser that MyClass was declared more than once.

ContentLicense: CC BY-SA 2.5

Body:
So, this is kind of an old question, but I found it while trying to solve a recent issue.  I asked a question and answered it here.  Here is a copy of that answer.  It is similar to the OP's answer, but avoids using TempData.

One solution is to implement an Html helper extension function which will only load a script once.  See below.  (this can work for CSS and other included files, too).

Implement an extension for the HtmlHelper class and a private backing class as a singleton per HttpContext.

public static class YourHtmlHelperExtensionClass
{
    private class TagSrcAttrTracker
    {
        private TagSrcAttrTracker() { }

        public Dictionary<string, string> sources { get; } = new Dictionary<string, string>();

        public static TagSrcAttrTrackerInstance {
            get {
                IDictionary items = HttpContext.Current.Items;
                const string instanceName = "YourClassInstanceNameMakeSureItIsUniqueInThisDictionary";

                if(!items.Contains(instanceName))
                    items[instanceName] = new TagSrcAttrTracker();

                return items[instanceName] as TagSrcAttrTracker;
            }
        }
    }

    public static MvcHtmlString IncludeScriptOnlyOnce(this HtmlHelper helper, string urlOfScript)
    {
        if(TagSrcAttrTracker.Instance.sources.ContainsKey(urlOfScript))
            return null;

        TagSrcAttrTracker.Instance.sources[urlOfScript] = urlOfScript;

        TagBuilder script = new TagBuilder("script");
        scriptTag.MergeAttribute("src", urlOfScript);

        return MvcHtmlString.Create(script.ToString());
    }
}

Then, separate the JavaScript and other code into separate files.

Example .js file contents

class MyClass{
    myFunction() {
        constructor(divId){
            this._divId = divId
        }

        doSomething() {
            // do something with a div with id == divId
        }
    }
}

Example .cshtml file contents for partial view

<link rel="stylesheet" type="text/css" href="~/Content/CustomCSS/MyPartialView.css"/>

<div id="@ViewBag.id">
    Some content!  Yay!
</div>

@Html.IncludeScriptOnlyOnce("/Scripts/CustomScripts/MyPartialView.js")

Example .cshtml file that consumes the partial view

...
<body>
    <h1>Here is some content!</h1>
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_1"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_2"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_3"} })
</body>
<script>
$().ready(
    const id1Functionality = new MyClass("id_1") // forgive the poor naming :-)
    const id2Functionality = new MyClass("id_3")
    const id3Functionality = new MyClass("id_2")

    id1Functionality.doSomething();
    id2Functionality.doSomething();
    id3Functionality.doSomething();
)
</script>

The partial view may have been included more than once and the JavaScript is packaged with the partial view, but the .js file is only included in the page once, hence no complaining by the browser that MyClass was declared more than once.


问:
Unable to see specflow features in Item list
After added extensions and installed specflow package, Unable to see specflow features in the Item list.

答:
Even though the SpecFlow packages are installed through NuGet Package Manager. It requires to install the SpecFlow for Visual Studio extension as below.

Open your Visual Studio

Click on the Extensions Tab, which will display the Manage Extensions window

On the Right hand Search bar type as specflow

SpecFlow for Visual Studio would be displayed with download button. (Since I already installed it is displayed the tick symbol)

Click on the Download button and install the extension.

Now get back to your project, Right click the Features folder (I assume you have created this folder already if not create it) --> Add --> New item

Click on SpecFlow category and select the SpecFlow Feature File option to create the feature file


问:
Rails 3 - Handle Incoming Messages (Allowing Users to reply to email notifications)
Right now my app sends out email notifications. I'd like to allow the user to reply directly to the email, which then gets ingested by my app and inserted into the database.

Are there any Rails gems, services, tutorials that can point me in the right direction.

Also, probably need to make the reply-to email have a UID, replyto--UID@domain.com, so I don't have to rely on the from (sender).

What do you think?

Thanks

答:
We have a free service that posts incoming email to a url of your application (same as sendgrid API):
http://www.smtp2web.com

You can also use the mailman gem if you want to poll for the email at regular intervals:

https://github.com/titanous/mailman

As far as the 'replyto--UID@domain.com' kind of email addresses are concerned, you will have to create a catch-all address for your domain (it is better if you use a obscure subdomain, as it would reduce the amount of spam) which forwards all such email to a given mailbox(say notifications@domain.com).

ContentLicense: CC BY-SA 3.0


问:
Format a text box to display user input on runtime in form of thousand separator number with decimals
i am still new to c# , i am trying to build a simple calculator with c# windows form.
i did all the coding but i am stuck in formating my calculator screen(text box in this case) to display numbers with thousand separator comma and decimal point.

for example: if the user input 1000 i want it to display 1,000 of if the user input 1000.0123 i want it to display 1,000.0123 on the fly(just like the windows 10 calculator)

i really appreciate the any help , i have been searching all around the internet for some solution and came to nothing

答:
```<code>var input = 1024.10;
Console.WriteLine(input.ToString("N"));
</code>```

Output:

1,024.10

Format as a numeric value with 2 decimal places. For 3 or 4 decimal places you can use ToString("N3") or N4. For No decimal places ToString("N0")

Body:
var input = 1024.10;
Console.WriteLine(input.ToString("N"));

Output:

1,024.10

Format as a numeric value with 2 decimal places. For 3 or 4 decimal places you can use ToString("N3") or N4. For No decimal places ToString("N0")


问:
Filter out FASTA files by specified sequence length in bash
There's a FASTA file assembly.fasta containing contig names and corresponding sequences:

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
>contig_3
CGTGATCTCGCCATTCGTGCCG
</code>```

I want to get only contigs longer than 30 letters and get a new FASTA file assembly.filtered.fasta containing only those long sequences with contig names, in this format:

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
</code>```

答:
Using gnu-awk, you may use this simpler version:

```<code>awk -v RS='>[^\n]+\n' 'length() >= 30 {printf "%s", prt $0} {prt = RT}' file
</code>```

```<code>>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
</code>```

Body:
There's a FASTA file assembly.fasta containing contig names and corresponding sequences:

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA
>contig_3
CGTGATCTCGCCATTCGTGCCG

I want to get only contigs longer than 30 letters and get a new FASTA file assembly.filtered.fasta containing only those long sequences with contig names, in this format:

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA

Body:
Using gnu-awk, you may use this simpler version:

awk -v RS='>[^\n]+\n' 'length() >= 30 {printf "%s", prt $0} {prt = RT}' file

>contig_1
CCAATACGGGCGCGCAGGCTTTCTATCGCGCGGCCGGCTTCGTCGAGGACGGGCGGCGCA
AGGATTACTACCGCAGCGGC
>contig_2
ATATAAACCTTATTCATCGTTTTCAGCCTAATTTTCCATTTAACAGGGATGATTTTCGTC
AAAATGCTGAGGCTTTACCAAGATTTTCTACCTTGCACCTTCAGAAAAAAATCATGGCAT
TTATAGACGAAATTCTCGAGAAA


问:
Why does my code not realize that game = false?
I have a while loop that says:

```<code>game = True
while game == True:
    shop = False
    while shop == False:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
           game = False
</code>```

And yet it keeps on repeating and I cant cant figure out why (I'm also new to coding so there could be an obvious answer)
Link to code here: https://repl.it/@WeirdDragon/ore-digging-sim#main.py

答: You need shop == True to break from the inner while first. Then, it can realize that game == False

Body:
I have a while loop that says:

game = True
while game == True:
    shop = False
    while shop == False:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
           game = False

And yet it keeps on repeating and I cant cant figure out why (I'm also new to coding so there could be an obvious answer)
Link to code here: https://repl.it/@WeirdDragon/ore-digging-sim#main.py


问:
Functional delete command that have a problem, please, read the text before the code. Thanks
I am making a discord bot with discord.js and the case is that I have a command to delete messages from the chat but they can only be used by people who have the MANAGE_MESSAGES permission, this command works perfectly but what I don't understand it is because when it detects that this person does not have the permissions, it does not send the message that person does not have the MANAGE_MESSAGES permission. Thanks for the help.

```<code>case 'delete':
        if (!args[1]) return message.reply('Please enter a number of messages you would like to delete like ``k!delete 5``. LIMIT: 100 MESSAGES');
        message.channel.bulkDelete(args[1]);
        if (!message.member.hasPermission('MANAGE_MESSAGES'))
          return message.channel.send('You dont have the permission `MANAGE_MESSAGES` to use this command!!');
        break;
</code>```

答:
The command does not work perfectly. Since lines of code are executed in order, currently you are executing the bulkDelete before even seeing if the member has permission to do so.

The reason you aren't seeing the error message is likely due to a race condition of sorts: The bulk delete endpoint is handled by a background worker, and likely takes longer to process than your message.channel.send. So the message is getting sent, but immediately deleted from the bulkDelete happening shortly afterwards.

To fix, merely move your bulkDelete line after the permission check.

Body:
I am making a discord bot with discord.js and the case is that I have a command to delete messages from the chat but they can only be used by people who have the MANAGE_MESSAGES permission, this command works perfectly but what I don't understand it is because when it detects that this person does not have the permissions, it does not send the message that person does not have the MANAGE_MESSAGES permission. Thanks for the help.

case 'delete':
        if (!args[1]) return message.reply('Please enter a number of messages you would like to delete like ``k!delete 5``. LIMIT: 100 MESSAGES');
        message.channel.bulkDelete(args[1]);
        if (!message.member.hasPermission('MANAGE_MESSAGES'))
          return message.channel.send('You dont have the permission `MANAGE_MESSAGES` to use this command!!');
        break;


问:
How to stop the player from jumping while in the air?
I don't want my player to jump in the air but I can't seem to find anything out.

This is what I have. They can jump, but they can jump forever and that's a problem.

```<code>using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  public bool alive;
  private Rigidbody2D rigidBody;
  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
        // Use this for initialization
    }

  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }
    if(Input.GetButtonDown ("Jump")){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }
  }
}
</code>```

答:
An simple option is to maintain a boolean such as _inAir that gets set to true when the player first jumps, and to false when their RigidBody2D collides with the ground (see, e.g., OnCollisionEnter2D).

Then, the check if(Input.GetButtonDown ("Jump")){ becomes

```<code>if (!_inAir && Input.GetButtonDown("Jump")) {
</code>```

Body:
I don't want my player to jump in the air but I can't seem to find anything out.

This is what I have. They can jump, but they can jump forever and that's a problem.

using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  public bool alive;
  private Rigidbody2D rigidBody;
  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
        // Use this for initialization
    }

  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }
    if(Input.GetButtonDown ("Jump")){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }
  }
}

Body:
An simple option is to maintain a boolean such as _inAir that gets set to true when the player first jumps, and to false when their RigidBody2D collides with the ground (see, e.g., OnCollisionEnter2D).

Then, the check if(Input.GetButtonDown ("Jump")){ becomes

if (!_inAir && Input.GetButtonDown("Jump")) {


问:
Accessors are only available when targeting ECMAScript 5 and higher
I am trying to run this code, but it is giving me the following errors:

Animal.ts(10,13): error TS1056: Accessors are only available when
targeting ECMAScript 5 and higher. Animal.ts(14,13): error TS1056:
Accessors are only available when targeting ECMAScript 5 and higher.

```<code>interface IAnimal{
    name : string;
    sayName():string;
}

class AnimalImpm implements IAnimal{
    private _name : string = '[Animal]';
    get name():string{
        return this._name;
    }

    set name(name:string){
        this._name = name;
    }

    constructor(name:string){
        this.name = name;
    }

    sayName():string {
        console.log(`My name is ${this.name}`);
        return "Hello";
    }
}
</code>```

答:
I had the same issue and got it to work with this... for a single file!

tsc -target "es5" filename && node filename

"es5" with quotes

need not mention file extensions

tsc -target "es5" filename - transpiles the typescript to "es5" JavaScript

node filename - runs the transpiled JavaScript file

Body:
I am trying to run this code, but it is giving me the following errors:

Animal.ts(10,13): error TS1056: Accessors are only available when
targeting ECMAScript 5 and higher. Animal.ts(14,13): error TS1056:
Accessors are only available when targeting ECMAScript 5 and higher.

interface IAnimal{
    name : string;
    sayName():string;
}

class AnimalImpm implements IAnimal{
    private _name : string = '[Animal]';
    get name():string{
        return this._name;
    }

    set name(name:string){
        this._name = name;
    }

    constructor(name:string){
        this.name = name;
    }

    sayName():string {
        console.log(`My name is ${this.name}`);
        return "Hello";
    }
}


问:
Vue js cannot splice item from nested v-for
I'm starting with Vue.js and I read about splice() according to item id/index. It works fine if I try to splice() an item in "tours" v-for:

```<code>data:{
   tours: null,
},
methods: {
  deleteTour: function (id) {
    if (confirm('Are you sure?')) {
        const index = this.tours.findIndex(item => item.id === id);
      if (~index) {
         axios.post('deleteTour.php', { "token": token, "tourID": id }).then((response) => {
           this.deleted = response;
           console.log(this.deleted);

           // splice tour
           this.tours.splice(index, 1);
         }).catch((error) => {
           this.errored = error;
           console.log(this.errored);
         });
       }
    }
  },
}
</code>```

html

```<code><div id="app" class="row mb-50">
   <div v-for="(item, index) in tours" v-bind:key="item.id" id="tours" class="col-md-12 mb-30">
      <ul class="pics-list">
         <li v-for="(image, index) in item.images" ref="deleteItem" :class="{marginRightOpen: editingTour}">
            <span :hidden="editingTour !== item.id" class="badge" @click="deleteImage(image.imageID, item.id, index)">
            <i class="fa fa-fw fa-times-circle"></i>
            </span>
            <div class="pics-list-image-container img-fluid cursor-pointer" v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }" @click="openModal = true, showModal(image.image)">
            </div>
         </li>
         <li v-if="urls && editingTour == item.id" v-for="(url, key) in urls" :key="key">
            <div id="preview" :ref="'url'" class="pics-list-image-container img-fluid">
            </div>
         </li>
      </ul>
   </div>
</div>
</code>```

But I'm not able to splice() a list item within a nested v-for. I tried using ref in many ways but it didn't work.

```<code>deleteImage: function (id, tourID, index) {
   if (confirm('Are you sure?')) {

      // it could be done here
      this.$refs.deleteItem.splice(index, 1);

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},
</code>```

I want to remove the whole first list item that contains the badge icon. Is it possible to do that?

答:
Based on Cato Minor comment I changed

```<code>deleteImage: function (id, tourID, index) {
    this.$refs.deleteItem.splice(index, 1);
</code>```

to:

```<code>deleteImage: function (id, tourID, i, index) {
    this.tours[index].images.splice(i, 1);
</code>```

where i is the image index from <li v-for="(image, i) in item.images" and index is the tour index from <div v-for="(item, index) in tours"

Body:
I'm starting with Vue.js and I read about splice() according to item id/index. It works fine if I try to splice() an item in "tours" v-for:

data:{
   tours: null,
},
methods: {
  deleteTour: function (id) {
    if (confirm('Are you sure?')) {
        const index = this.tours.findIndex(item => item.id === id);
      if (~index) {
         axios.post('deleteTour.php', { "token": token, "tourID": id }).then((response) => {
           this.deleted = response;
           console.log(this.deleted);

           // splice tour
           this.tours.splice(index, 1);
         }).catch((error) => {
           this.errored = error;
           console.log(this.errored);
         });
       }
    }
  },
}

html

But I'm not able to splice() a list item within a nested v-for. I tried using ref in many ways but it didn't work.

deleteImage: function (id, tourID, index) {
   if (confirm('Are you sure?')) {

      // it could be done here
      this.$refs.deleteItem.splice(index, 1);

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},

I want to remove the whole first list item that contains the badge icon. Is it possible to do that?

Body:
Based on Cato Minor comment I changed

deleteImage: function (id, tourID, index) {
    this.$refs.deleteItem.splice(index, 1);

to:

deleteImage: function (id, tourID, i, index) {
    this.tours[index].images.splice(i, 1);

where i is the image index from <li v-for="(image, i) in item.images" and index is the tour index from <div v-for="(item, index) in tours"


问:
How to insert a div in a specific position in another div?
I have the following html structure

```<code><div class"parent1">
  <div class="child1">text</div>
  <div class="child2">text</div>
  <div class="child3">text</div>
  <div class="child4">text</div>
</div>

<div class="parent2">
  <div class="child2">some text</div>
</div>
</code>```

I am looping on the parent1 div and getting the index of the child divs. And if a div with that class is not present in parent2, I want to add an empty div with that class and exactly in same position as in parent1. So the result would be like this

```<code><div class="parent2">
  <div class="child1"></div>
  <div class="child2">some text</div>
  <div class="child3"></div>
  <div class="child4"></div>
</div>
</code>```

JQuery code

```<code>$(".parent1 div").each(function(){
  let index = $(this).index();
  let css_class = $(this).attr("class");
  if ($("." + css_class).length < 1) {
    // Here I need that logic to insert an empty div in parent2 in same position as in parent1
  }
});
</code>```

答:
You can do it like this:

$(".parent1 div").each(function() {
  let index = $(this).index();
  let css_class = $(this).attr("class");
  if ($(".parent2 ." + css_class).length < 1) {
    let div = "

";
    if (index == 0) {
      $(".parent2").prepend(div);
    } else {
      $(".parent2 div:nth-child(" + index + ")").after(div);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent1">
  <div class="child1"></div>
  <div class="child2"></div>
  <div class="child3"></div>
  <div class="child4"></div>
</div>

<div class="parent2">
  <div class="child2">some text</div>
</div></code>```

This is not much different from the answer given here that was already mentioned in the answer given by ehhc.

Body:
I have the following html structure

text

text

text

text

some text

I am looping on the parent1 div and getting the index of the child divs. And if a div with that class is not present in parent2, I want to add an empty div with that class and exactly in same position as in parent1. So the result would be like this

some text

JQuery code

$(".parent1 div").each(function(){
  let index = $(this).index();
  let css_class = $(this).attr("class");
  if ($("." + css_class).length < 1) {
    // Here I need that logic to insert an empty div in parent2 in same position as in parent1
  }
});

Body:
You can do it like this:

$(".parent1 div").each(function() {
  let index = $(this).index();
  let css_class = $(this).attr("class");
  if ($(".parent2 ." + css_class).length < 1) {
    let div = "<div class=" + css_class + "></div>";
    if (index == 0) {
      $(".parent2").prepend(div);
    } else {
      $(".parent2 div:nth-child(" + index + ")").after(div);
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent1">
  <div class="child1"></div>
  <div class="child2"></div>
  <div class="child3"></div>
  <div class="child4"></div>
</div>

<div class="parent2">
  <div class="child2">some text</div>
</div>

This is not much different from the answer given here that was already mentioned in the answer given by ehhc.


问:
Why are the "Enter name" output got skip over and when I type "close" in the output it keeps on looping
In the input below it keeps on looping when I type close in the output and after typing something in this part:

Before proceeding to our service, you need to fill in your details first as our record(type close to End):

The "Enter name: " part got skip

```<code>#include<stdio.h>
int main(void)
{
      char name[200],gender[20],op,option, close;
      int visit_ID, phone_number,day,month,year,service_needed, change_service, needed_days;
      float service_fee,payment_made, changes, change_service_fee;

      printf("\n\n*****Welcome to the Our Repair Centre*****");
      printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
      scanf("%s", &close);

      FILE * fpointer;
      fpointer = fopen("visitdetails.txt","w");

      while(close != "close")
      {
          printf("\n\nEnter information:\n");
          printf("\nEnter name: ");
          scanf("%[^\n]s", name);
          printf("\n\nEnter your ID number(Number only): ", visit_ID);
          scanf("%d",&visit_ID);
          printf("\n\nEnter today date dd mm yy(use space) :");
          scanf("%d", &day);
          scanf("%d", &month);
          scanf("%d", &year);
          printf("\n\nEnter your gender(Male/Female): ", gender);
          scanf("%s",gender);
          printf("\n\nEnter your phone number: ",phone_number);
          scanf("%d",&phone_number);
          printf("\n\nDone registered\n\n");

          printf("*****Welcome to the Computer centre*****\n");
          printf("-------------------------------------------------\n");
          printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
          printf("                                                                      |Normal|Urgent|\n");
          printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
          printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
          printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
          printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
          printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
          printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
          printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
          printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

          printf("\nWhich service type do you need(1-8)? ", service_needed);
          scanf("%d",&service_needed);

          switch(service_needed)
          {
            case 1:
            printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 2:
            printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 3:
            printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 4:
            printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 5:
            printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }
          printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
          fprintf(fpointer, "Visit ID = %d", visit_ID);
          fprintf(fpointer, "\nCustomer name = %s", name);
          fprintf(fpointer, "\nLast visit date : %d/%d/%d",day,month,year);
          fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
          fscanf(fpointer,"%d",service_needed);
          fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
          fprintf(fpointer,"\nLast payment: %.2f",payment_made);
          fclose(fpointer);
      }
}
</code>```

答:
Your code has several issues:

1.

close is a single char. In order to use scanf("%s", &close); close needs to be at least an array of 2 characters for storing the newline. For storing a character only, use %c instead. If you want to at least store the word "close" in it, you need an array of 6 char.

2.

scanf("%s", &close); leaves the newline made by the press to  in stdin.

This newline is catched by scanf("%[^\n]s", name);.

Use "%*c" after every conversion specifer for all format strings in your code like:    scanf("%s %*c", &close); to discard the newline.

3.

Note, that %[is separate from %s. Omit the s at the end of the format string.

Also add a white space before the %[ conversion specifier to catch leading white space.

Like: scanf(" %[^\n]", name);.

4.

while(close != "close)" is incorrect to be used for comparing strings. Use  while(strcmp(close, "close")) instead. Also I think if would be more appropriate here: if (strcmp(close, "close"))

5.

The while loop has no break; statement to get out of it. It will continue infinitely.

6.

fclose(fpointer); is placed inside of the while loop. If you want to iterate the while loop´s body, you need to place it out of it.

7.

printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close); - , close is full redundant here. Omit it.

8.

You should check whether the opening of the stream to visitdetails.txt was successful by checking the returned pointer of fopen() for a null pointer:

```<code>if (!(filePointer = fopen("visitdetails.txt", "w")))
{
    fputs("Error occurred at opening file!\n", stderr);
    exit(1);
}
</code>```

Body:
In the input below it keeps on looping when I type close in the output and after typing something in this part:

Before proceeding to our service, you need to fill in your details first as our record(type close to End):

The "Enter name: " part got skip

#include<stdio.h>
int main(void)
{
      char name[200],gender[20],op,option, close;
      int visit_ID, phone_number,day,month,year,service_needed, change_service, needed_days;
      float service_fee,payment_made, changes, change_service_fee;

      printf("\n\n*****Welcome to the Our Repair Centre*****");
      printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
      scanf("%s", &close);

      FILE * fpointer;
      fpointer = fopen("visitdetails.txt","w");

      while(close != "close")
      {
          printf("\n\nEnter information:\n");
          printf("\nEnter name: ");
          scanf("%[^\n]s", name);
          printf("\n\nEnter your ID number(Number only): ", visit_ID);
          scanf("%d",&visit_ID);
          printf("\n\nEnter today date dd mm yy(use space) :");
          scanf("%d", &day);
          scanf("%d", &month);
          scanf("%d", &year);
          printf("\n\nEnter your gender(Male/Female): ", gender);
          scanf("%s",gender);
          printf("\n\nEnter your phone number: ",phone_number);
          scanf("%d",&phone_number);
          printf("\n\nDone registered\n\n");

          printf("*****Welcome to the Computer centre*****\n");
          printf("-------------------------------------------------\n");
          printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
          printf("                                                                      |Normal|Urgent|\n");
          printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
          printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
          printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
          printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
          printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
          printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
          printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
          printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

          printf("\nWhich service type do you need(1-8)? ", service_needed);
          scanf("%d",&service_needed);

          switch(service_needed)
          {
            case 1:
            printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 2:
            printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 3:
            printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 4:
            printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 5:
            printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }
          printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
          fprintf(fpointer, "Visit ID = %d", visit_ID);
          fprintf(fpointer, "\nCustomer name = %s", name);
          fprintf(fpointer, "\nLast visit date : %d/%d/%d",day,month,year);
          fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
          fscanf(fpointer,"%d",service_needed);
          fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
          fprintf(fpointer,"\nLast payment: %.2f",payment_made);
          fclose(fpointer);
      }
}

Body:
Your code has several issues:

1.

close is a single char. In order to use scanf("%s", &close); close needs to be at least an array of 2 characters for storing the newline. For storing a character only, use %c instead. If you want to at least store the word "close" in it, you need an array of 6 char.

2.

scanf("%s", &close); leaves the newline made by the press to  in stdin.

This newline is catched by scanf("%[^\n]s", name);.

Use "%*c" after every conversion specifer for all format strings in your code like:    scanf("%s %*c", &close); to discard the newline.

3.

Note, that %[is separate from %s. Omit the s at the end of the format string.

Also add a white space before the %[ conversion specifier to catch leading white space.

Like: scanf(" %[^\n]", name);.

4.

while(close != "close)" is incorrect to be used for comparing strings. Use  while(strcmp(close, "close")) instead. Also I think if would be more appropriate here: if (strcmp(close, "close"))

5.

The while loop has no break; statement to get out of it. It will continue infinitely.

6.

fclose(fpointer); is placed inside of the while loop. If you want to iterate the while loop´s body, you need to place it out of it.

7.

printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close); - , close is full redundant here. Omit it.

8.

You should check whether the opening of the stream to visitdetails.txt was successful by checking the returned pointer of fopen() for a null pointer:

if (!(filePointer = fopen("visitdetails.txt", "w")))
{
    fputs("Error occurred at opening file!\n", stderr);
    exit(1);
}


问:
Puppeteer select option from drowpdown menu using xpath
I'm trying to select one of the optiones from this menu:

Let's say I want to click on the "Online Webinar" option.

I have to click on the input to open up the dropdown menu

I have to target the option that I'm looking for using waitForXPath, that means that I'm targeting elements for it's text content, not by class or id

This is my HTML structure:

And this is how I'm targeting the "Online Webinar" in my code:

And this is the what I'm getting from this code

As you can see, is not selecting the "Online Webinar" option, and I think that it's because there's a whitespace at the beginning and end of the string that I'm looking to target and I think this is the problem

However I don't know to workaround this issue, should I look for a way to use the trim() method, or there's a Puppeteer way to get around it?

答:
I found a pretty simple solution</p>

```<code>let venueOption = await page.waitForXPath(`//li[contains(text(),'Online Webinar')]`);
</code>```

Body:
I found a pretty simple solution

let venueOption = await page.waitForXPath(`//li[contains(text(),'Online Webinar')]`);


问:
TF LSTM multiple step predict seems to be wrong

you can see full source here

https://colab.research.google.com/drive/1kk24KjpZQEZpdlBxr4D4DO-IGHJ0439v?usp=sharing

The original data of x_test has a non-linear random walk property,

but the newly predicted 20 values have a linear shape.

Clearly, did I make the wrong prediction?

答:
I went ahead and read over your data a bit. Some comments on your training and model:

1) You specifically trained an LSTM to predict one value into the future from 20 past values. Why would you expect that model to be able to extrapolate to predicting another 19 values from the first one value? Your model was not trained to do that and doesn't know that is important.

2) Your model is extremely small. Your model has 491 variables (model.summary()), which is very tiny. How many features do you think influences the stock market? How many variables do you think model each feature? Most deep learning is going to take millions of variables to learn something complicated like the stock market. In addition this is a highly complicated field that is taking millions of people around the world to research.

3) You have barely done any kind of training for how complicated your data is. You ran 100 epochs, or about 250 seconds of training on a GPU.

4) Your model is EXTREMELY overfit. I think you are making the mistake in thinking that "low loss" == "good predicting model", this is simply not true. Here is an example I google'd for that shows what I mean,

https://towardsdatascience.com/regularization-the-path-to-bias-variance-trade-off-b7a7088b4577

https://miro.medium.com/max/552/1%2ARN6fYYl_Z_n9R3cr1zpcTA@2x.png

In this example, the trained model has essentially zero loss and predicts perfectly on the input data. But the model clearly knows nothing about the underlying feature curve that drives the input data with some noise. Hence, if you tried to predict the next value with the model, it will be extremely inaccurate.

5) I think you are misunderstanding what training a model does. When you train a model, you are converging to a "common" answer that produces a low loss. A model is never going to find some extreme example of weights that predicts really well; it is only going to find and slowly converge to a common solution that yields low loss. If for example, slightly adjusting your weights towards zero, makes the loss smaller, then that will be repeatedly emphasized during your training. If predicting a uniform linear answer produces the least loss amongst a seemingly random set of data, then that will be reinforced over and over again during training. In general (like I commented above), when a model is faced with uniformly random information, it has a tendency to favor the average of the information (because that produces less loss from batch to batch to batch).

I believe the code you have provided and the results you have gotten are expected.

EDIT:

Here are some examples of time-series data models (are they good, who knows, that depends on your data):

```<code># Basic LSTM that attempts to produce a prediction vector from a sequence of time data.
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(20),
])

# Maybe throw a few LSTM layers to help learn the information, add some dimensions.
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(5,return_sequences=True),
    tf.keras.layers.LSTM(50,return_sequences=True),
    tf.keras.layers.LSTM(20),
])

# Maybe some Dense layers should be used to re-arrange information.
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(20),
    tf.keras.layers.Dense(500),
    tf.keras.layers.Dense(20),
])
</code>```

Maybe throw in some activations, relu might be useful (kind of like giving the layer a garbage can to remove useless values). Or maybe some sigmoid (keep values small) or softmax (treat values like probabilities). You could also throw in some Dropout layers to prevent overfitting (keep your model on it's toes, don't let it get settled to quickly). Also, normalizing data can be useful. If you find the weights grow to quickly, add some regularization to force the model to use small weights while trying to learn the data.

```<code>model = tf.keras.Sequential([
    tf.keras.layers.LSTM(5,return_sequences=True,activation='relu'),
    tf.keras.layers.Dropout(0.10),
    tf.keras.layers.LSTM(50,return_sequences=True,activation='relu'),
    tf.keras.layers.Dropout(0.10),
    tf.keras.layers.LSTM(20),
])
</code>```

If you think the learning is going bad, switch from "adam" to another learning algorithm. Maybe your "Mean Squared Error" loss function is too harsh to large errors, maybe slow down the learning; try "logcosh" instead. Run it for 24 hours straight, preferably use a GPU.

If the LSTM layers are too slow. Maybe switch to using some Attention or Residual layers instead (got to google for this custom ideas).

You could always try a GRU layer instead of LSTM. Has about the same performance, but trains a little faster.

Body:
I went ahead and read over your data a bit. Some comments on your training and model:

1) You specifically trained an LSTM to predict one value into the future from 20 past values. Why would you expect that model to be able to extrapolate to predicting another 19 values from the first one value? Your model was not trained to do that and doesn't know that is important.

2) Your model is extremely small. Your model has 491 variables (model.summary()), which is very tiny. How many features do you think influences the stock market? How many variables do you think model each feature? Most deep learning is going to take millions of variables to learn something complicated like the stock market. In addition this is a highly complicated field that is taking millions of people around the world to research.

3) You have barely done any kind of training for how complicated your data is. You ran 100 epochs, or about 250 seconds of training on a GPU.

4) Your model is EXTREMELY overfit. I think you are making the mistake in thinking that "low loss" == "good predicting model", this is simply not true. Here is an example I google'd for that shows what I mean,

https://towardsdatascience.com/regularization-the-path-to-bias-variance-trade-off-b7a7088b4577

https://miro.medium.com/max/552/1%2ARN6fYYl_Z_n9R3cr1zpcTA@2x.png

In this example, the trained model has essentially zero loss and predicts perfectly on the input data. But the model clearly knows nothing about the underlying feature curve that drives the input data with some noise. Hence, if you tried to predict the next value with the model, it will be extremely inaccurate.

5) I think you are misunderstanding what training a model does. When you train a model, you are converging to a "common" answer that produces a low loss. A model is never going to find some extreme example of weights that predicts really well; it is only going to find and slowly converge to a common solution that yields low loss. If for example, slightly adjusting your weights towards zero, makes the loss smaller, then that will be repeatedly emphasized during your training. If predicting a uniform linear answer produces the least loss amongst a seemingly random set of data, then that will be reinforced over and over again during training. In general (like I commented above), when a model is faced with uniformly random information, it has a tendency to favor the average of the information (because that produces less loss from batch to batch to batch).

I believe the code you have provided and the results you have gotten are expected.

EDIT:

Here are some examples of time-series data models (are they good, who knows, that depends on your data):

# Basic LSTM that attempts to produce a prediction vector from a sequence of time data.
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(20),
])

# Maybe throw a few LSTM layers to help learn the information, add some dimensions.
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(5,return_sequences=True),
    tf.keras.layers.LSTM(50,return_sequences=True),
    tf.keras.layers.LSTM(20),
])

# Maybe some Dense layers should be used to re-arrange information.
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(20),
    tf.keras.layers.Dense(500),
    tf.keras.layers.Dense(20),
])

Maybe throw in some activations, relu might be useful (kind of like giving the layer a garbage can to remove useless values). Or maybe some sigmoid (keep values small) or softmax (treat values like probabilities). You could also throw in some Dropout layers to prevent overfitting (keep your model on it's toes, don't let it get settled to quickly). Also, normalizing data can be useful. If you find the weights grow to quickly, add some regularization to force the model to use small weights while trying to learn the data.

model = tf.keras.Sequential([
    tf.keras.layers.LSTM(5,return_sequences=True,activation='relu'),
    tf.keras.layers.Dropout(0.10),
    tf.keras.layers.LSTM(50,return_sequences=True,activation='relu'),
    tf.keras.layers.Dropout(0.10),
    tf.keras.layers.LSTM(20),
])

If you think the learning is going bad, switch from "adam" to another learning algorithm. Maybe your "Mean Squared Error" loss function is too harsh to large errors, maybe slow down the learning; try "logcosh" instead. Run it for 24 hours straight, preferably use a GPU.

If the LSTM layers are too slow. Maybe switch to using some Attention or Residual layers instead (got to google for this custom ideas).

You could always try a GRU layer instead of LSTM. Has about the same performance, but trains a little faster.


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
Both are certainly O(1) since O(1) means a constant.  They are probably not the same constant.  Big Oh notation is meant to understand asymptotic behavior independent of constants.

Oh yeah, one more thing.  Always profile before you optimize.  You'll find out very quickly that time isn't being spent where you think.  Always!

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.


问:
"Resource Not Found" error on deleting document from documentdb
I am having an issue deleting a document form document db. The code is very trivial and I am not doing anything fancy. Basically I am getting the self link of the document and then using the self link to delete but it is giving me exception.

```<code>await client.DeleteDocumentAsync(entity.SelfLink, new RequestOptions() { PartitionKey = new PartitionKey(partitionKey) }).ConfigureAwait(false);
</code>```

entity is a newly added document which exists in database (I have checked its existence from Azure Portal)

The exception I am getting:

Message: {"Errors":["Resource Not Found"]}
  ActivityId: 052ad225-4e04-4757-89b8-51f6ccf55f7c, Request URI: https://sy3prdddc05-docdb-1.documents.azure.com:15236/apps/0ee0095b-872d-45bc-8739-67cfbd97db79/services/466a4dd1-27d3-45ca-b013-6875f06a38ab/partitions/73e5c3d8-0332-4c0c-9aec-47a3469ba958/replicas/131354346050636923p//dbs/l29HAA==/colls/l29HAKZFJwA=/docs/l29HAKZFJwAfAAAAAAAAAA==

Any idea??

答:
I had a similar situation. In my Repository, I used a string as the partition key, in the document I used int type. Changed it to object to keep the Repository neutral and open for other types.</p>

```<code>public virtual async Task DeleteAsync(string databaseId, string collectionId, string id, object partitionKey)
    {
        var reqOptions = new RequestOptions()
        {
            PartitionKey = new PartitionKey(partitionKey)
        };

        await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, id), reqOptions);
    }
</code>```

Body:
I am having an issue deleting a document form document db. The code is very trivial and I am not doing anything fancy. Basically I am getting the self link of the document and then using the self link to delete but it is giving me exception.

await client.DeleteDocumentAsync(entity.SelfLink, new RequestOptions() { PartitionKey = new PartitionKey(partitionKey) }).ConfigureAwait(false);

entity is a newly added document which exists in database (I have checked its existence from Azure Portal)

The exception I am getting:

Message: {"Errors":["Resource Not Found"]}
  ActivityId: 052ad225-4e04-4757-89b8-51f6ccf55f7c, Request URI: https://sy3prdddc05-docdb-1.documents.azure.com:15236/apps/0ee0095b-872d-45bc-8739-67cfbd97db79/services/466a4dd1-27d3-45ca-b013-6875f06a38ab/partitions/73e5c3d8-0332-4c0c-9aec-47a3469ba958/replicas/131354346050636923p//dbs/l29HAA==/colls/l29HAKZFJwA=/docs/l29HAKZFJwAfAAAAAAAAAA==

Any idea??

Body:
I had a similar situation. In my Repository, I used a string as the partition key, in the document I used int type. Changed it to object to keep the Repository neutral and open for other types.

public virtual async Task DeleteAsync(string databaseId, string collectionId, string id, object partitionKey)
    {
        var reqOptions = new RequestOptions()
        {
            PartitionKey = new PartitionKey(partitionKey)
        };

        await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, id), reqOptions);
    }


答:
You need to break out of the inner loop so you can get back to the outer loop's test.</p>

```<code>game = True
while game:
    shop = False
    while not shop:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
            game = False
            break
</code>```

Title: Why does my code not realize that game = false?

Body:
You need to break out of the inner loop so you can get back to the outer loop's test.

game = True
while game:
    shop = False
    while not shop:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
            game = False
            break


问:
Connecting to remote TFS 2010 instance gives TF30063 error
I connect to a remote TFS 2010 instance using Visual Studio 2010.  I can Get Latest for all files within a particular project except for one database backup file.  When I try to Get Latest on this file I get the following error:

TF30063: You are not authorized to access Microsoft-IIS/6.0

I've tried clearing my local VS client cache, but that doesn't help.  There are no entries in the Event Logs to give any clues as to what is going on.

Any help appreciated, or any ideas where I can find out more diagnostic information via would be appreciated.

Colin.

Update : Trace information shows the following, no real pointers

```<code>06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Completed download: id = 0 in 61866          ms, active = 1
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Web method response: [xxxxx.homeserver.com] Ver-Download: Napier.bak 61866 ms
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Recorded m_exception in UpDownAsyncResult.Completed(): Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at      Microsoft.TeamFoundation.VersionControl.Client.FileUploader.HandleErrorResponse(HttpWebResponse response)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Caught and converted to non-fatal error: Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream)  at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Converted to non-fatal: Microsoft.TeamFoundation.VersionControl.Client.VersionControlException: C:\code\Remote\Napier\Trunk\Database Backups\Napier.bak: TF30063: You are not authorized to access Microsoft-IIS/6.0. Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not   authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream) at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) DownloadFiles: 62061 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) Acknowledgements: 0 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115349 ms) CreateWebRequest() -- Uri: https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) request.AutomaticDecompression: GZip
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) Web method running: [https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx] QueryItemsExtended[VersionControl]
06/01/2011 15:45:09 (pid 5560, tid 2784, 115649 ms) HTTP headers:
Content-Length: 1247
Cache-Control: private, max-age=0
Content-Type: application/soap+xml; charset=utf-8
Date: Wed, 01 Jun 2011 14:43:27 GMT
Server: Microsoft-IIS/6.0
Via: 1.1 Clearswift SECURE Web Gateway
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
</code>```

答:
It sounds like you may have a corrupt cache file on the server. I recommend logging on to the server and wiping the cache (usually under C:\program files\microsoft team foundation server 2010\Application Tier\Web Services\_tfs_data\{guid}\proxy)

Delete all the files there (it's not going to break anything, that folder is just a cache) and try your Get Latest again (no need to restart the server). If that doesn't work, I recommend contacting MS Customer Support.

Body:
I connect to a remote TFS 2010 instance using Visual Studio 2010.  I can Get Latest for all files within a particular project except for one database backup file.  When I try to Get Latest on this file I get the following error:

TF30063: You are not authorized to access Microsoft-IIS/6.0

I've tried clearing my local VS client cache, but that doesn't help.  There are no entries in the Event Logs to give any clues as to what is going on.

Any help appreciated, or any ideas where I can find out more diagnostic information via would be appreciated.

Colin.

Update : Trace information shows the following, no real pointers

06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Completed download: id = 0 in 61866          ms, active = 1
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Web method response: [xxxxx.homeserver.com] Ver-Download: Napier.bak 61866 ms
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Recorded m_exception in UpDownAsyncResult.Completed(): Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at      Microsoft.TeamFoundation.VersionControl.Client.FileUploader.HandleErrorResponse(HttpWebResponse response)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Caught and converted to non-fatal error: Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream)  at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Converted to non-fatal: Microsoft.TeamFoundation.VersionControl.Client.VersionControlException: C:\code\Remote\Napier\Trunk\Database Backups\Napier.bak: TF30063: You are not authorized to access Microsoft-IIS/6.0. Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not   authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream) at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) DownloadFiles: 62061 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) Acknowledgements: 0 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115349 ms) CreateWebRequest() -- Uri: https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) request.AutomaticDecompression: GZip
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) Web method running: [https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx] QueryItemsExtended[VersionControl]
06/01/2011 15:45:09 (pid 5560, tid 2784, 115649 ms) HTTP headers:
Content-Length: 1247
Cache-Control: private, max-age=0
Content-Type: application/soap+xml; charset=utf-8
Date: Wed, 01 Jun 2011 14:43:27 GMT
Server: Microsoft-IIS/6.0
Via: 1.1 Clearswift SECURE Web Gateway
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET


问:
Update sqlite3 database simply
I would like to update my data in a way to keep properties which have their values at null  as they were in the table and only change those who have new values as arguments .

This is my request it sends me errors when I have null values in my object :

```<code>/* THE OBJECT */

    let chick = { ID: 3, name: null, lastname: 'soup', phone: '60-58-22-12', password: null , mail: 'chicken@gmail.com' }

    /* UPDATE REQUEST */

     this.state._stmt = db.prepare("UPDATE user SET

        name = CASE WHEN (? = NULL) THEN name ELSE ? END ,

        lastname = CASE WHEN (? = NULL) THEN lastname ELSE ? END  ,

        phone= CASE WHEN (? = NULL) THEN phone ELSE ? END ,

        password = CASE WHEN (? = NULL) THEN password ELSE ? END,

        mail = CASE WHEN (? = NULL) THEN mail ELSE ? END

       WHERE ID=? ;");

     this.state._stmt.run(obj.name, obj.name, obj.lastname, obj.lastname , obj.phone, obj.phone, obj.password, obj.password, obj.mail, obj.mail, obj.ID);
</code>```

/

/* The error I get is : */

```<code>[Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: user.name
Emitted 'error' event on Statement instance at:
] {
  errno: 19,
  code: 'SQLITE_CONSTRAINT'
}
</code>```

答:
I found two way to do that :

USING COALESCE  THE SHORTER ONE

```<code>this.state._stmt = db.prepare("UPDATE user SET

        name = COALESCE(?, name) ,

        lastname = COALESCE(?, lastname)  ,

        phone= COALESCE(?, phone) ,

        password = COALESCE(?, password),

        mail = COALESCE(?, mail)

       WHERE ID=? ;
");
</code>```

Keeping my request but changing the condition NULL->'null'

```<code>UPDATE user

SET name = CASE

WHEN ? != 'null' THEN ?

ELSE  name END

WHERE ID= ? ;
</code>```

Title: Update sqlite3 database simply

Body:
I would like to update my data in a way to keep properties which have their values at null  as they were in the table and only change those who have new values as arguments .

This is my request it sends me errors when I have null values in my object :

/* THE OBJECT */

    let chick = { ID: 3, name: null, lastname: 'soup', phone: '60-58-22-12', password: null , mail: 'chicken@gmail.com' }

    /* UPDATE REQUEST */

     this.state._stmt = db.prepare("UPDATE user SET

        name = CASE WHEN (? = NULL) THEN name ELSE ? END ,

        lastname = CASE WHEN (? = NULL) THEN lastname ELSE ? END  ,

        phone= CASE WHEN (? = NULL) THEN phone ELSE ? END ,

        password = CASE WHEN (? = NULL) THEN password ELSE ? END,

        mail = CASE WHEN (? = NULL) THEN mail ELSE ? END

       WHERE ID=? ;");

     this.state._stmt.run(obj.name, obj.name, obj.lastname, obj.lastname , obj.phone, obj.phone, obj.password, obj.password, obj.mail, obj.mail, obj.ID);

/

/* The error I get is : */

[Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: user.name
Emitted 'error' event on Statement instance at:
] {
  errno: 19,
  code: 'SQLITE_CONSTRAINT'
}

Body:
I found two way to do that :

USING COALESCE  THE SHORTER ONE

this.state._stmt = db.prepare("UPDATE user SET

        name = COALESCE(?, name) ,

        lastname = COALESCE(?, lastname)  ,

        phone= COALESCE(?, phone) ,

        password = COALESCE(?, password),

        mail = COALESCE(?, mail)

       WHERE ID=? ;
");

Keeping my request but changing the condition NULL->'null'

UPDATE user

SET name = CASE

WHEN ? != 'null' THEN ?

ELSE  name END

WHERE ID= ? ;


问:
How to suppress Page Breaks in a mail merge?
I'm trying to create a one-to-many merge in Word using Excel VBA.  The form works as expected when manually running the process in Word 2013.

When I try to automate using VBA in Excel 2013, it defaults and inserts page breaks for each new row in the Excel Spreadsheet.

Here is my code altered from the source following the code block:

```<code>Dim cDir As String
Dim ThisFileName As String

Const WTempName = "HCCMailMerge.docx" 'This is Word Templates name
Dim NewFileName As String

NewFileName = "Testing123"

' Setup directory
cDir = ActiveWorkbook.Path + "\"
ThisFileName = ThisWorkbook.Name

'Open Word Template
Set objMMMD = objWord.Documents.Open(cDir + WTempName)
objMMMD.Activate

'Merge the data
With objMMMD.MailMerge
    .OpenDataSource _
        Name:=cDir + ThisFileName, _
        SQLStatement:="SELECT * FROM `Data$`"
    .Destination = wdSendToNewDocument
    .MainDocumentType = wdCatalog
    .Execute Pause:=False
End With
</code>```

Automating Mail Merge using Excel VBA

I assumed that when I changed .MainDocumentType = wdCatalog that it would suppress the page breaks.

Any help is much appreciated.

答: You can try removing the maindocumenttype=wdCatalog and save the main word document as directory (by manually selecting it). Then run the macro, it will append without the page breaks.

Body:
I'm trying to create a one-to-many merge in Word using Excel VBA.  The form works as expected when manually running the process in Word 2013.

When I try to automate using VBA in Excel 2013, it defaults and inserts page breaks for each new row in the Excel Spreadsheet.

Here is my code altered from the source following the code block:

Dim cDir As String
Dim ThisFileName As String

Const WTempName = "HCCMailMerge.docx" 'This is Word Templates name
Dim NewFileName As String

NewFileName = "Testing123"

' Setup directory
cDir = ActiveWorkbook.Path + "\"
ThisFileName = ThisWorkbook.Name

'Open Word Template
Set objMMMD = objWord.Documents.Open(cDir + WTempName)
objMMMD.Activate

'Merge the data
With objMMMD.MailMerge
    .OpenDataSource _
        Name:=cDir + ThisFileName, _
        SQLStatement:="SELECT * FROM `Data$`"
    .Destination = wdSendToNewDocument
    .MainDocumentType = wdCatalog
    .Execute Pause:=False
End With

Automating Mail Merge using Excel VBA

I assumed that when I changed .MainDocumentType = wdCatalog that it would suppress the page breaks.

Any help is much appreciated.


问:
How can I make two components communicate in React?
I have just started using React and I am struggling to figure out how to make 2 components communicate between each other to exchange data. For example, I am trying to build a calculator which has component buttons with their values and component input field which is supposed to display the value of the buttons. I think I can figure out how to write the code, but I am strugging to understand, how to make them know about each other?
Thank you!</p>

答:
If you have two components (let's call them A and B), you can make them "talk" between each other, by defining a context in one of their common parents, or even to the root of the app.
Then you can subscribe to this context (useContext) from both of A and B, and push data into the context, whenever you wish. This will trigger a re-render of all components which are using this context, and they will then get this updated data.

Using common state in the parent and passing it as props to A and B is also fine, but my proposal to do it with context is covering the cases where A and B are not siblings in the Virtual DOM tree, e.g. it's hard to pass props to them, from the parent, but it's super easy to do so by simply using a common context.

Hope this answers to your question! :)


问:
Layout not overing FragmentContainerView
I am trying to display android:id="@+id/menu_layout" fullscreen over layout that contains FragmentContainerView and BottomNavbar  blocking it with somehow. The part of over toolbar works.
I want to achive full screen android:id="@+id/menu_layout"
If I make FragmentContainerView  android:layout_height="0dp" it displays the layout
Here is my xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Activities.MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/catchupColor"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_scrollFlags="scroll|enterAlways"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/header_logo"/>

    </androidx.appcompat.widget.Toolbar>
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_on_demand"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/catchupColor"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        android:visibility="gone"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <TextView
            android:id="@+id/toolbarLogoText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:drawableEnd="@drawable/keyboard_arrow_down_white_24x24"
            android:gravity="center"
            android:lineSpacingExtra="3.6sp"
            android:text="On Demand"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="18sp"
            android:visibility="visible" />

        <ImageView
            android:id="@+id/btn_filter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_gravity="end"
            android:layout_marginEnd="10dp"
            android:src="@drawable/ic_filter_list"
            android:visibility="visible" />

        <ImageView
            android:id="@+id/btn_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_gravity="start"
            android:layout_marginStart="10dp"
            android:src="@drawable/ic_icn_search"
            android:visibility="visible" />

    </androidx.appcompat.widget.Toolbar>

    <LinearLayout
        android:id="@+id/menu_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#BE000000"
        android:orientation="vertical"
        android:visibility="visible">

        <ImageView
            android:id="@+id/main_menu_img_close"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_marginStart="14dp"
            android:layout_marginTop="14dp"
            android:src="@drawable/close" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_margin="15dp"
            android:gravity="center"
            android:orientation="vertical">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/main_menu_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_margin="20dp"
                android:foregroundGravity="center_vertical" />

        </LinearLayout>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottomNavigationView"
        android:layout_below="@+id/toolbar">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/mysat_nav">

        </androidx.fragment.app.FragmentContainerView>

    </RelativeLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#020712"
        android:layout_alignParentBottom="true"
        android:theme="@style/BottomNavigationTheme"
        app:menu="@menu/bottom_menu">

    </com.google.android.material.bottomnavigation.BottomNavigationView>
</code>```

答:
Try setting the elevation of menu_layout something like

android:elevation="10dp"

Body:
I am trying to display android:id="@+id/menu_layout" fullscreen over layout that contains FragmentContainerView and BottomNavbar  blocking it with somehow. The part of over toolbar works.
I want to achive full screen android:id="@+id/menu_layout"
If I make FragmentContainerView  android:layout_height="0dp" it displays the layout
Here is my xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Activities.MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/catchupColor"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_scrollFlags="scroll|enterAlways"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/header_logo"/>

    </androidx.appcompat.widget.Toolbar>
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_on_demand"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/catchupColor"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        android:visibility="gone"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <TextView
            android:id="@+id/toolbarLogoText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:drawableEnd="@drawable/keyboard_arrow_down_white_24x24"
            android:gravity="center"
            android:lineSpacingExtra="3.6sp"
            android:text="On Demand"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="18sp"
            android:visibility="visible" />

        <ImageView
            android:id="@+id/btn_filter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_gravity="end"
            android:layout_marginEnd="10dp"
            android:src="@drawable/ic_filter_list"
            android:visibility="visible" />

        <ImageView
            android:id="@+id/btn_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_gravity="start"
            android:layout_marginStart="10dp"
            android:src="@drawable/ic_icn_search"
            android:visibility="visible" />

    </androidx.appcompat.widget.Toolbar>

    <LinearLayout
        android:id="@+id/menu_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#BE000000"
        android:orientation="vertical"
        android:visibility="visible">

        <ImageView
            android:id="@+id/main_menu_img_close"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_marginStart="14dp"
            android:layout_marginTop="14dp"
            android:src="@drawable/close" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_margin="15dp"
            android:gravity="center"
            android:orientation="vertical">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/main_menu_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_margin="20dp"
                android:foregroundGravity="center_vertical" />

        </LinearLayout>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottomNavigationView"
        android:layout_below="@+id/toolbar">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/mysat_nav">

        </androidx.fragment.app.FragmentContainerView>

    </RelativeLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#020712"
        android:layout_alignParentBottom="true"
        android:theme="@style/BottomNavigationTheme"
        app:menu="@menu/bottom_menu">

    </com.google.android.material.bottomnavigation.BottomNavigationView>