问:
javascript onClick not working after Postback
I am using ASP.NET, Bootstrap and jQuery to display and edit data.

The data is searched for and returned by ASP.NET code behind which updates an update panel around the controls which update the data.

I have a HTML button outside of the update panel which moves the Bootstrap tab from tab(0) to tab(1).

If I press the button before doing a search for data, the onclick event fires and I get warnings that I have not completed all of the required data.

If I do a search for the data and update the update panel, the onclick event doesn't fire.

If I click anywhere on the page and then press the button, the onclick event fires and moves to the next tab.

In Chrome, the onclick event fires correctly, even after the update panel is updated.

I have the following at the top of the html to set up the jQuery functions:

```<code><script type="text/jscript" language="javascript">

        $(document).ready(startUp);

</script>
</code>```

The javascript is in a separate file, which I don't think causes a problem.

```<code>function firstButtonClick(move) {

    if (move = 1) {
        $(".nav-tabs > .active").next("li").find("a").trigger("click");
    }
</code>```

}

I added the parameter to stop the code being run after the update so a user can actually update it.

This is the code for the tab and button and update panel:

```<code>   <div id="mnuSupporterDetails" class="tab-pane fade in active">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="row">
                            <div class="col-lg-3">
                                Supporter Details
                            </div>
                            <div class="col-lg-8">
                                <div class="row">
                                    <div class="pull-right">
                                        <%--<a class="btn btn-default btnPrevious">Previous</a> --%>
                                        <a class="btn btn-success" onclick="firstButtonClick(1)">Next</a>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-1">
                            </div>
                        </div>
                    </div>
                    <div class="panel-body">
                        <asp:UpdatePanel ID="uppContactDetails" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <script type="text/javascript">
                                    Sys.Application.add_load(firstButtonClick(0));
                                </script>
                                <div class="row">
                                    <div class="col-lg-3">
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="row">
                                            <label for="inpSupporterNumber">
                                                Supporter Number:</label>
                                            <div class="input-group">
                                                <input type="text" class="form-control summary" runat="server" id="inpSupporterNumber"
                                                    placeholder="Supporter Number" maxlength="10" />
                                                <span class="input-group-btn">
                                                    <button class="btn btn-primary" id="btnSearchContacts" runat="server" type="submit">
                                                        Search</button>
                                                </span>
                                            </div>
                                            <label for="inpTitle">
                                                Title:</label>
                                            <input type="text" class="form-control summary" runat="server" id="inpTitle" placeholder="Title"
                                                required="true" maxlength="50" />
                                            <label for="inpForename">
                                                Forename:</label>
                                            <input type="text" class="form-control summary" runat="server" id="inpForename" placeholder="Forename"
                                                required="true" maxlength="30" />
                                            <label for="inpSurname">
                                                Surname:</label>
                                            <input type="text" class="form-control summary" runat="server" id="inpSurname" placeholder="Surname"
                                                required="true" maxlength="30" />
                                            <label for="inpAddressLine1">
                                                Address:</label>
                                            <%--<div class="input-group">--%>
                                                <input type="text" class="form-control summary" runat="server" id="inpAddressLine1"
                                                    placeholder="Address Line 1" required="true" maxlength="60" />
                                                <%--<span class="input-group-btn">--%>
                                                    <%--<button class="btn btn-primary" id="btnQAS" type="button" data-toggle="modal" data-target="#mdlQAS">--%>
                                                        <%--&nbsp<i class="glyphicon glyphicon-home"></i>--%>
                                                    <%--</button>--%>
                                                <%--</span>--%>
                                            <%--</div>--%>
                                            <label for="inpAddressLine2">
                                            </label>
                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine2"
                                                placeholder="Address Line 2" maxlength="35" />
                                            <label for="inpAddressLine3">
                                            </label>
                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine3"
                                                placeholder="Address Line 3" maxlength="35" />
                                            <label for="inpAddressLine4">
                                            </label>
                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine4"
                                                placeholder="Address Line 4" maxlength="35" />
                                            <label for="inpAddressLine5">
                                            </label>
                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine5"
                                                placeholder="Address Line 5" maxlength="35" />
                                            <label for="inpPostCode">
                                                Post Code:</label>
                                            <input type="text" class="form-control summary" runat="server" id="inpPostCode" placeholder="Post Code"
                                                required="true" maxlength="8" />
                                            <label for="inpCountry">
                                                Country:</label>
                                            <input type="text" class="form-control summary" runat="server" id="inpCountry" placeholder="Country"
                                                maxlength="42" />
                                        </div>
                                        <div class="row">
                                            <div class="form-group">
                                                <label for="inpTelephoneNumber">
                                                    Telephone Number:</label>
                                                <input type="text" class="form-control summary" runat="server" id="inpTelephoneNumber"
                                                    placeholder="Phone Number" maxlength="20" />
                                                <label for="inpEmailAddress">
                                                    EMail Address:</label>
                                                <input type="text" class="form-control summary" runat="server" id="inpEmailAddress"
                                                    placeholder="EMail Address" maxlength="100" />
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-3">
                                    </div>
                                </div>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </div>
                    <div class="panel-footer">
                        <div class="row">
                            <div class="col-lg-3">
                            </div>
                            <div class="col-lg-8">
                                <div class="row">
                                    <div class="pull-right">
                                        <a class="btn btn-success btnNext">Next</a>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-1 ">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
</code>```

Any help would be appreciated.

Sean

答:
Have you cleared your cache? As sometimes Javascript can hang around in Chrome and do weird things.

Cheers,
Definitely Not Mac

I accept apologies.

Body:
I am using ASP.NET, Bootstrap and jQuery to display and edit data.

The data is searched for and returned by ASP.NET code behind which updates an update panel around the controls which update the data.

I have a HTML button outside of the update panel which moves the Bootstrap tab from tab(0) to tab(1).

If I press the button before doing a search for data, the onclick event fires and I get warnings that I have not completed all of the required data.

If I do a search for the data and update the update panel, the onclick event doesn't fire.

If I click anywhere on the page and then press the button, the onclick event fires and moves to the next tab.

In Chrome, the onclick event fires correctly, even after the update panel is updated.

I have the following at the top of the html to set up the jQuery functions:

The javascript is in a separate file, which I don't think causes a problem.

function firstButtonClick(move) {

    if (move = 1) {
        $(".nav-tabs > .active").next("li").find("a").trigger("click");
    }

}

I added the parameter to stop the code being run after the update so a user can actually update it.

This is the code for the tab and button and update panel:

                                Supporter Details

                                        <%--Previous --%>
                                        Next

                        <asp:UpdatePanel ID="uppContactDetails" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>

                                                Supporter Number:

                                                <input type="text" class="form-control summary" runat="server" id="inpSupporterNumber"
                                                    placeholder="Supporter Number" maxlength="10" />

                                                    <button class="btn btn-primary" id="btnSearchContacts" runat="server" type="submit">
                                                        Search</button>

                                                Title:
                                            <input type="text" class="form-control summary" runat="server" id="inpTitle" placeholder="Title"
                                                required="true" maxlength="50" />

                                                Forename:
                                            <input type="text" class="form-control summary" runat="server" id="inpForename" placeholder="Forename"
                                                required="true" maxlength="30" />

                                                Surname:
                                            <input type="text" class="form-control summary" runat="server" id="inpSurname" placeholder="Surname"
                                                required="true" maxlength="30" />

                                                Address:
                                            <%--
--%>
                                                <input type="text" class="form-control summary" runat="server" id="inpAddressLine1"
                                                    placeholder="Address Line 1" required="true" maxlength="60" />
                                                <%----%>
                                                    <%--<button class="btn btn-primary" id="btnQAS" type="button" data-toggle="modal" data-target="#mdlQAS">--%>
                                                        <%--&nbsp--%>
                                                    <%--</button>--%>
                                                <%----%>
                                            <%--
--%>

                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine2"
                                                placeholder="Address Line 2" maxlength="35" />

                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine3"
                                                placeholder="Address Line 3" maxlength="35" />

                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine4"
                                                placeholder="Address Line 4" maxlength="35" />

                                            <input type="text" class="form-control summary" runat="server" id="inpAddressLine5"
                                                placeholder="Address Line 5" maxlength="35" />

                                                Post Code:
                                            <input type="text" class="form-control summary" runat="server" id="inpPostCode" placeholder="Post Code"
                                                required="true" maxlength="8" />

                                                Country:
                                            <input type="text" class="form-control summary" runat="server" id="inpCountry" placeholder="Country"
                                                maxlength="42" />

                                                    Telephone Number:
                                                <input type="text" class="form-control summary" runat="server" id="inpTelephoneNumber"
                                                    placeholder="Phone Number" maxlength="20" />

                                                    EMail Address:
                                                <input type="text" class="form-control summary" runat="server" id="inpEmailAddress"
                                                    placeholder="EMail Address" maxlength="100" />

                            </ContentTemplate>
                        </asp:UpdatePanel>

                                        Next

Any help would be appreciated.

Sean


来源: stackexchange

问:
Git rebase when previous commit changed
I frequently find myself working on two different work tickets that are on different git branches, but one is dependent on another, like this:

```<code>* later-branch
|
* earlier-branch
|
* some prior commit
|
</code>```

(Each is a single commit here because we are using gerrit, but this question might apply to multiple commits for each as well.)  The earlier branch may be going through review, and so I might have to go back and modify it at some point with a git commit --amend.  As must happen, this will fork the history:

```<code>* earlier-branch
|
|  * later-branch
|  |
|  * previous version of earlier-branch
| /
* some prior commit
|
</code>```

At this point I want to rebase the later-branch on top of the new version of earlier-branch.  But if I just do a git checkout later-branch followed by a git rebase earlier-branch, it always gets conflicts, because (I think) it must first apply the previous version of earlier-branch commit to the most recent version of earlier-branch.

What I end up doing is git checkout earlier-branch -b new-later-branch-name followed by git cherry-pick later-branch and git br -D later-branch.  Which is a pain.  Can anyone suggest a better way to handle this?

答:
I see two easy ways to do this.

The first, best option is to use git rebase in interactive mode. To do this, you would do

```<code>git checkout later-branch
git rebase -i earlier-branch
</code>```

In the screen that pops up, you would choose to drop the previous version of earlier-branch:

```<code>drop efb1c19 previous version of earlier-branch
pick a25ba16 later-branch

# Rebase 65f3afc..a25ba16 onto 65f3afc (2 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
...
</code>```

This will rebase later-branch on top of earlier-branch, providing the following tree:

```<code>* later-branch
|
* earlier-branch
|
|  * previous version of earlier-branch
| /
* some prior commit
|
</code>```

Another option is to simply do a git cherry-pick. If you do:

```<code>git checkout earlier-branch
git cherry-pick later-branch
</code>```

You'll get the following tree:

```<code>* earlier-branch -> cherry-picked commit 1
|
* earlier-branch -> amended commit 0, now commit 2
|
|  * later-branch -> commit 1
|  |
|  * previous version of earlier-branch -> commit 0
| /
* some prior commit
|
</code>```

So, in effect, this will produce the result you want, but it will advance earlier-branch by one. If the branch names are important to you, you could rename and reset them accordingly.

ContentLicense: CC BY-SA 3.0

Title: Git rebase when previous commit changed

Body:
I frequently find myself working on two different work tickets that are on different git branches, but one is dependent on another, like this:

* later-branch
|
* earlier-branch
|
* some prior commit
|

(Each is a single commit here because we are using gerrit, but this question might apply to multiple commits for each as well.)  The earlier branch may be going through review, and so I might have to go back and modify it at some point with a git commit --amend.  As must happen, this will fork the history:

* earlier-branch
|
|  * later-branch
|  |
|  * previous version of earlier-branch
| /
* some prior commit
|

At this point I want to rebase the later-branch on top of the new version of earlier-branch.  But if I just do a git checkout later-branch followed by a git rebase earlier-branch, it always gets conflicts, because (I think) it must first apply the previous version of earlier-branch commit to the most recent version of earlier-branch.

What I end up doing is git checkout earlier-branch -b new-later-branch-name followed by git cherry-pick later-branch and git br -D later-branch.  Which is a pain.  Can anyone suggest a better way to handle this?

Body:
I see two easy ways to do this.

The first, best option is to use git rebase in interactive mode. To do this, you would do

git checkout later-branch
git rebase -i earlier-branch

In the screen that pops up, you would choose to drop the previous version of earlier-branch:

drop efb1c19 previous version of earlier-branch
pick a25ba16 later-branch

# Rebase 65f3afc..a25ba16 onto 65f3afc (2 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
...

This will rebase later-branch on top of earlier-branch, providing the following tree:

* later-branch
|
* earlier-branch
|
|  * previous version of earlier-branch
| /
* some prior commit
|

Another option is to simply do a git cherry-pick. If you do:

git checkout earlier-branch
git cherry-pick later-branch

You'll get the following tree:

* earlier-branch -> cherry-picked commit 1
|
* earlier-branch -> amended commit 0, now commit 2
|
|  * later-branch -> commit 1
|  |
|  * previous version of earlier-branch -> commit 0
| /
* some prior commit
|

So, in effect, this will produce the result you want, but it will advance earlier-branch by one. If the branch names are important to you, you could rename and reset them accordingly.


问:
Random number generation in R with multiple conditions
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

```<code>Defect Table :

Length

6355
6236
1345
3123
</code>```

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

```<code> DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length
</code>```

Final data should something like this(values could be different as long as it satisfies above conditions)

```<code> Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120
</code>```

答:
Consider df to be your dataframe:

```<code> df$random<-runif(nrow(df)) #just create a random column and fill it with random numbers
</code>```

apply the condition

```<code> df$random<-ifelse(df$DefectEnds > df$DefectStarts,df$random,NA)#select rows with this condition
</code>```

Body:
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

Defect Table :

Length

6355
6236
1345
3123

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

 DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length

Final data should something like this(values could be different as long as it satisfies above conditions)

 Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120

Body:
Consider df to be your dataframe:

 df$random<-runif(nrow(df)) #just create a random column and fill it with random numbers

apply the condition

 df$random<-ifelse(df$DefectEnds > df$DefectStarts,df$random,NA)#select rows with this condition


问:
PhalconPHP - getRouter in \Phalcon\Di
I've created new project using PhalconPHP 3.1.2. Everything works fine, but I have problem with IDE. In PhpStorm I've added ide/stubs/Phalcon from phalcon-devtools 3.1.2 as external libraries to dispose of warnings and errors.

But there is still one problem: in app/config/router.php (standard catalog structure created by devtools) I got line $router = $di->getRouter(); (also created by devtools) with warning: Method getRouter not found in Phalcon\Di\FactoryDefault.

There is no method in this class indeed: https://github.com/phalcon/phalcon-devtools/blob/3.1.x/ide/stubs/Phalcon/di/FactoryDefault.php -> https://github.com/phalcon/phalcon-devtools/blob/3.1.x/ide/stubs/Phalcon/Di.php

Now I don't have autocomplete of router's methods and this is problem for me. Did I do something wrong?

答:
$di->getRouter() is magic method, Phalcon\Di implements __call method and it gets router service this way if you use getRouter().

If you want you can use PHPStorm metadata and use $di->get() https://www.google.pl/search?client=opera&q=phpstorm+metadata&sourceid=opera&ie=UTF-8&oe=UTF-8

Title: PhalconPHP - getRouter in \Phalcon\Di


问:
Android Voice Actions: set-alarm intent
What is the intent to handle the "set alarm" Voice Action?
(For "listen to" it is android.media.action.MEDIA_PLAY_FROM_SEARCH)</p>

答: Can you not use the standard android.intent.action.SET_ALARM from the android.provider.AlarmClock class?

ContentLicense: CC BY-SA 2.5

Title: Android Voice Actions: set-alarm intent


问:
Using Do/Catch in Swift
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

```<code>func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}
</code>```

It would be very nice if somebody could help me.

答:
You should check if the result is nil.

```<code>func processData(data: String?) -> String {
    guard let result = data else {
        return "Not Found"
    }

    return result
}
</code>```

Title: Using Do/Catch in Swift

Body:
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}

It would be very nice if somebody could help me.

Body:
You should check if the result is nil.

func processData(data: String?) -> String {
    guard let result = data else {
        return "Not Found"
    }

    return result
}


问:
Mysql Event Not Working
I have added the following simple test event on my mysql database via phpmyadmin:

```<code>CREATE DEFINER=`root`@`localhost` EVENT `my_event`
ON SCHEDULE EVERY 1 MINUTE STARTS '2013-05-27 00:00:00'
ON COMPLETION NOT PRESERVE ENABLE DO
BEGIN
    UPDATE `test` SET `name`="z";
END
</code>```

My environment is mac + MAMP Pro. I am expecting to change all rows on my 'test' table with name 'z' within a minute. But not happening so.

Do I have to something additional to get my events start working?

Output of "SHOW PROCESSLIST":

Thanks.

答:
Verify if the event_scheduler is On - execute the following command:

```<code>SHOW PROCESSLIST;
</code>```

It'll output a table/entries, you must look for an entry with User event_scheduler, and Command Daemon:

```<code>Id           User         Host      db  Command Time    State            Info
22870   event_scheduler localhost   \N   Daemon  23    Waiting for next activation  \N
</code>```

OR, you can also verify using the following command:

```<code>SELECT @@global.event_scheduler;
</code>```

The result should be ON, otherwise set it off (will get 0 for the command), as stated in the next section.

If you don't have any such entry (as above), you may start the event scheduler using the following command:

```<code> SET GLOBAL event_scheduler = ON;
</code>```

Once done, you can verify if it has been executed properly using the SHOW PROCESSLIST command, as mentioned above.

Title: Mysql Event Not Working

Body:
I have added the following simple test event on my mysql database via phpmyadmin:

CREATE DEFINER=`root`@`localhost` EVENT `my_event`
ON SCHEDULE EVERY 1 MINUTE STARTS '2013-05-27 00:00:00'
ON COMPLETION NOT PRESERVE ENABLE DO
BEGIN
    UPDATE `test` SET `name`="z";
END

My environment is mac + MAMP Pro. I am expecting to change all rows on my 'test' table with name 'z' within a minute. But not happening so.

Do I have to something additional to get my events start working?

Output of "SHOW PROCESSLIST":

Thanks.

Body:
Verify if the event_scheduler is On - execute the following command:

SHOW PROCESSLIST;

It'll output a table/entries, you must look for an entry with User event_scheduler, and Command Daemon:

Id           User         Host      db  Command Time    State            Info
22870   event_scheduler localhost   \N   Daemon  23    Waiting for next activation  \N

OR, you can also verify using the following command:

SELECT @@global.event_scheduler;

The result should be ON, otherwise set it off (will get 0 for the command), as stated in the next section.

If you don't have any such entry (as above), you may start the event scheduler using the following command:

 SET GLOBAL event_scheduler = ON;

Once done, you can verify if it has been executed properly using the SHOW PROCESSLIST command, as mentioned above.


问:
php mailer not showing errors but not sending emails
I have a server with email service and im trying to send emails using phpmailer like this:

```<code>include('config/class_phpmailer.php');

$email = new PHPMailer();

$email->IsSMTP();
$email->SMTPAuth = true;
$email->Host = 'smtp-mail.outlook.com'; // netcabo
$email->Port = 587;
$email->SMTPKeepAlive = true;
$email->Username = my_email@netcabo.pt;
$email->Password = my_password;
$email->SMTPSecure = 'tls';
$email->From      = my_email@netcabo.pt;
$email->FromName  = 'my_name';
$email->Subject   = $subject;
$email->Body      = $message;

// Set the Atatchment
if($attach) {
    $email->AddAttachment($attach);
}
// set the emails to send the message
foreach($emails_to as $mail) {
    $email->addAddress($mail);
}
// send the email
if(!$email->Send()) {
    echo "Message was not sent <br />PHPMailer Error: " . $email->ErrorInfo;
}
else {
    echo "Message has been sent";
}
</code>```

This works perfectly on localhost but when i upload it into a server, it gives me an error saying: "Message was not sent
PHPMailer Error: SMTP connect() failed". So, i've tried changing the host, port, user and pass to my email account from that server and nothing happened. no error, no "message has been sent", nothing... The email wasnt sent either. just a blank page.

What am i doing wrong? thanks in advance.

答:
If you want to catch an error you can do this</p>

```<code>$mail = new PHPMailer(true);
// the true param means it will throw exceptions on errors, which we need to catch
</code>```

Body:
I have a server with email service and im trying to send emails using phpmailer like this:

include('config/class_phpmailer.php');

$email = new PHPMailer();

$email->IsSMTP();
$email->SMTPAuth = true;
$email->Host = 'smtp-mail.outlook.com'; // netcabo
$email->Port = 587;
$email->SMTPKeepAlive = true;
$email->Username = my_email@netcabo.pt;
$email->Password = my_password;
$email->SMTPSecure = 'tls';
$email->From      = my_email@netcabo.pt;
$email->FromName  = 'my_name';
$email->Subject   = $subject;
$email->Body      = $message;

// Set the Atatchment
if($attach) {
    $email->AddAttachment($attach);
}
// set the emails to send the message
foreach($emails_to as $mail) {
    $email->addAddress($mail);
}
// send the email
if(!$email->Send()) {
    echo "Message was not sent
PHPMailer Error: " . $email->ErrorInfo;
}
else {
    echo "Message has been sent";
}

This works perfectly on localhost but when i upload it into a server, it gives me an error saying: "Message was not sent
PHPMailer Error: SMTP connect() failed". So, i've tried changing the host, port, user and pass to my email account from that server and nothing happened. no error, no "message has been sent", nothing... The email wasnt sent either. just a blank page.

What am i doing wrong? thanks in advance.

Body:
If you want to catch an error you can do this

$mail = new PHPMailer(true);
// the true param means it will throw exceptions on errors, which we need to catch


问:
Are HTML canvas clip paths inclusive or exclusive?
I've been working on a Typescript based touch screen client for our CQC home automation platform, and ran across something odd. There are lots of places where various graphical elements are layered over images. When it's time to update some area of the screen, I set a clip area and update.

But I always ended up with a line around everything, which was the color of the underlying color fill behind the image. I of course blamed myself. But, in the end, instead of committing suicide, I did a little test program.

It seems to indicate that drawImage() does NOT include the clip path boundary, while a color fill does. So blitting over the part of the images that underlies the area I'm updating doesn't completely fill the target area, leaving a line around the area.

After that simple program demonstrated the problem, I went back and for image updates I inflated the clip area by one, but left it alone for everything else, and now it's all working. I tested this in Chrome and Edge, just to make sure it wasn't some bug, and they both act exactly the same.

Strangely, I've never see any statement in the docs about whether clip paths are intended to be exclusive or inclusive of the boundary, but surely it shouldn't be one way for one type of primitive and another way for others, right?

```<code>function drawRect(ctx, x, y, w, h) {
    ctx.moveTo(x, y);
    ctx.lineTo(x + w, y);
    ctx.lineTo(x + w, y + h);
    ctx.lineTo(x, y + h);
    ctx.lineTo(x, y);
}

function init()
{
    var canvas = document.getElementById("output");
    canvas.style.width = 480;
    canvas.style.height = 480;
    canvas.width = 480;
    canvas.height = 480;

    var drawCtx = canvas.getContext("2d");
    drawCtx.translate(0.5, 0.5);

    var img = new Image();
    img.src = "test.jpg";
    img.onload = function() {

        // DRaw the image
        drawCtx.drawImage(img, 0, 0);

        // SEt a clip path
        drawCtx.beginPath();
        drawRect(drawCtx, 10, 10, 200, 200);
        drawCtx.clip();

        // Fill the whole area, which fills the clip area
        drawCtx.fillStyle = "black";
        drawCtx.fillRect(0, 0, 480, 480);

        // Draw the image again, which should fill the area
        drawCtx.drawImage(img, 0, 0);

        // But it ends up with a black line around it
    }
}

window.addEventListener("load", init, false);
</code>```

答:
I think they behave same.

Clip region are not inclusive of the border, but they can use anti aliasing.

Chrome was not using this techinque and was giving jagged lines on clipping. ( probably they changed recently ).

The thin black border is the side effect of a compositing operation.
The clip region is across a pixel. so the fillRect will draw black everywhere, but the border will be 50% black and 50% transparent, compositing with the first image draw.

The second draw image get clpped, at the border with 50% opacity to simulate the half pixel. at this point at the clip border you have:

image 100%
black fill 50%
image 50%

This will make a small dark border appear.

function drawRect(ctx, x, y, w, h) {
    ctx.moveTo(x, y);
    ctx.lineTo(x, y + h);
    ctx.lineTo(x + w, y + h);
    ctx.lineTo(x + w, y);
    ctx.closePath();
}

function init()
{
    var canvas = document.getElementById("output");
    canvas.style.width = 480;
    canvas.style.height = 480;
    canvas.width = 480;
    canvas.height = 480;

    var drawCtx = canvas.getContext("2d");
    drawCtx.translate(0.5, 0.5);

    var img = new Image();
    img.src = "http://fabricjs.com/assets/printio.png";
    img.onload = function() {

        // DRaw the image
        drawCtx.drawImage(img, 0, 0);

        // SEt a clip path
        drawCtx.beginPath();
        drawRect(drawCtx, 10, 10, 200, 200);
        drawCtx.clip();

        // Fill the whole area, which fills the clip area
        drawCtx.fillStyle = "black";
        drawCtx.fillRect(0, 0, 480, 480);

        // Draw the image again, which should fill the area
        drawCtx.drawImage(img, 0, 0);

        // But it ends up with a black line around it
    }
}

init();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="output" /></code>```

Body:
I've been working on a Typescript based touch screen client for our CQC home automation platform, and ran across something odd. There are lots of places where various graphical elements are layered over images. When it's time to update some area of the screen, I set a clip area and update.

But I always ended up with a line around everything, which was the color of the underlying color fill behind the image. I of course blamed myself. But, in the end, instead of committing suicide, I did a little test program.

It seems to indicate that drawImage() does NOT include the clip path boundary, while a color fill does. So blitting over the part of the images that underlies the area I'm updating doesn't completely fill the target area, leaving a line around the area.

After that simple program demonstrated the problem, I went back and for image updates I inflated the clip area by one, but left it alone for everything else, and now it's all working. I tested this in Chrome and Edge, just to make sure it wasn't some bug, and they both act exactly the same.

Strangely, I've never see any statement in the docs about whether clip paths are intended to be exclusive or inclusive of the boundary, but surely it shouldn't be one way for one type of primitive and another way for others, right?

function drawRect(ctx, x, y, w, h) {
    ctx.moveTo(x, y);
    ctx.lineTo(x + w, y);
    ctx.lineTo(x + w, y + h);
    ctx.lineTo(x, y + h);
    ctx.lineTo(x, y);
}

function init()
{
    var canvas = document.getElementById("output");
    canvas.style.width = 480;
    canvas.style.height = 480;
    canvas.width = 480;
    canvas.height = 480;

    var drawCtx = canvas.getContext("2d");
    drawCtx.translate(0.5, 0.5);

    var img = new Image();
    img.src = "test.jpg";
    img.onload = function() {

        // DRaw the image
        drawCtx.drawImage(img, 0, 0);

        // SEt a clip path
        drawCtx.beginPath();
        drawRect(drawCtx, 10, 10, 200, 200);
        drawCtx.clip();

        // Fill the whole area, which fills the clip area
        drawCtx.fillStyle = "black";
        drawCtx.fillRect(0, 0, 480, 480);

        // Draw the image again, which should fill the area
        drawCtx.drawImage(img, 0, 0);

        // But it ends up with a black line around it
    }
}

window.addEventListener("load", init, false);

Body:
I think they behave same.

Clip region are not inclusive of the border, but they can use anti aliasing.

Chrome was not using this techinque and was giving jagged lines on clipping. ( probably they changed recently ).

The thin black border is the side effect of a compositing operation.
The clip region is across a pixel. so the fillRect will draw black everywhere, but the border will be 50% black and 50% transparent, compositing with the first image draw.

The second draw image get clpped, at the border with 50% opacity to simulate the half pixel. at this point at the clip border you have:

image 100%
black fill 50%
image 50%

This will make a small dark border appear.

function drawRect(ctx, x, y, w, h) {
    ctx.moveTo(x, y);
    ctx.lineTo(x, y + h);
    ctx.lineTo(x + w, y + h);
    ctx.lineTo(x + w, y);
    ctx.closePath();
}

function init()
{
    var canvas = document.getElementById("output");
    canvas.style.width = 480;
    canvas.style.height = 480;
    canvas.width = 480;
    canvas.height = 480;

    var drawCtx = canvas.getContext("2d");
    drawCtx.translate(0.5, 0.5);

    var img = new Image();
    img.src = "http://fabricjs.com/assets/printio.png";
    img.onload = function() {

        // DRaw the image
        drawCtx.drawImage(img, 0, 0);

        // SEt a clip path
        drawCtx.beginPath();
        drawRect(drawCtx, 10, 10, 200, 200);
        drawCtx.clip();

        // Fill the whole area, which fills the clip area
        drawCtx.fillStyle = "black";
        drawCtx.fillRect(0, 0, 480, 480);

        // Draw the image again, which should fill the area
        drawCtx.drawImage(img, 0, 0);

        // But it ends up with a black line around it
    }
}

init();

<canvas id="output" />


问:
Should I use returns in multiline Scala methods?
Perhaps this is just my background in more imperative programming, but I like having return statements in my code.

I understand that in Scala, returns are not necessary in many methods, because whatever the last computed value is is returned by default. I understand that this makes perfect sense for a "one-liner", e.g.

```<code>def square(x) = x * x
</code>```

I also understand the definitive case for using explicit returns (when you have several branches your code could take, and you want to break out of the method for different branches, e.g. if an error occurs). But what about multiline functions? Wouldn't it be more readable and make more sense if there was an explicit return, e.g.

```<code>def average(x: List[Int]) : Float = {
  var sum = 0
  x.foreach(sum += _)
  return sum / x.length.toFloat
}
</code>```

答:
Your sense that the version with the return is more readable is probably a sign that you are still thinking imperatively rather than declaratively.  Try to think of your function from the perspective of what it is (i.e. how it is defined), rather than what it does (i.e. how it is computed).

Let's look at your average example, and pretend that the standard library doesn't have the features that make an elegant one-liner possible.  Now in English, we would say that the average of a list of numbers is the sum of the numbers in the list divided by its length.

```<code>def average(xs: List[Int]): Float = {
   var sum = 0
   xs.foreach(sum += _)
   sum / xs.length.toFloat
}
</code>```

This description is fairly close to the English version, ignoring the first two lines of the function.  We can factor out the sum function to get a more declarative description:

```<code>def average(xs: List[Int]): Float = {
   def sum(xs: List[Int]): Int = // ...
   sum(xs) / xs.length.toFloat
}
</code>```

In the declarative definition, a return statement reads quite unnaturally because it explicitly puts the focus on doing something.

Body:
Perhaps this is just my background in more imperative programming, but I like having return statements in my code.

I understand that in Scala, returns are not necessary in many methods, because whatever the last computed value is is returned by default. I understand that this makes perfect sense for a "one-liner", e.g.

def square(x) = x * x

I also understand the definitive case for using explicit returns (when you have several branches your code could take, and you want to break out of the method for different branches, e.g. if an error occurs). But what about multiline functions? Wouldn't it be more readable and make more sense if there was an explicit return, e.g.

def average(x: List[Int]) : Float = {
  var sum = 0
  x.foreach(sum += _)
  return sum / x.length.toFloat
}

Body:
Your sense that the version with the return is more readable is probably a sign that you are still thinking imperatively rather than declaratively.  Try to think of your function from the perspective of what it is (i.e. how it is defined), rather than what it does (i.e. how it is computed).

Let's look at your average example, and pretend that the standard library doesn't have the features that make an elegant one-liner possible.  Now in English, we would say that the average of a list of numbers is the sum of the numbers in the list divided by its length.

def average(xs: List[Int]): Float = {
   var sum = 0
   xs.foreach(sum += _)
   sum / xs.length.toFloat
}

This description is fairly close to the English version, ignoring the first two lines of the function.  We can factor out the sum function to get a more declarative description:

def average(xs: List[Int]): Float = {
   def sum(xs: List[Int]): Int = // ...
   sum(xs) / xs.length.toFloat
}

In the declarative definition, a return statement reads quite unnaturally because it explicitly puts the focus on doing something.


问:
How to use mongoDB collection output as variables in ansible
I can able to print the mongodb data using ansible. but here my requirement is to use the printed data as variables in ansible.

here is the output I'm getting ansible playbook output:

here is my ansible playbook.

```<code>---
- hosts: localhost
  vars:
    - i: "db.repo.find({ $and: [{'product': 'Admin'}, {'env':'SHK'}] }).pretty()"

  tasks:
  - name: Printing the retrieved data
    command: mongo Advantage --quiet --eval "{{i}}"
    register: temp

  - name: Printing the retrieved data
    set_fact:
     "{{item}}"
    with_items:
      - [ "{{temp.stdout.split('\t')[0] }}", "{{temp.stdout.split('\t')[1] }}", "{{temp.stdout.split('\t')[2] }}", "{{temp.stdout.split('\t')[3] }}", "{{temp.stdout.split('\t')[4] }}", "{{temp.stdout.split('\t')[5] }}", "{{temp.stdout.split('\t')[6] }}", "{{temp.stdout.split('\t')[7] }}", "{{temp.stdout.split('\t')[8] }}", "{{temp.stdout.split('\t')[9] }}" ]

- include: /etc/ansible/roles/patchdeployment_3_11_2/tasks/applypatch/applypatch_windows_websphere.yml PR_ID={{PR_ID}}
#- include: /etc/ansible/roles/patchdeployment_3_11_2/tasks/applypatch/applypatch_linux_websphere.yml
</code>```

please help me on the same.

答:
Make mongo output pure JSON friendly by disabling all fields with custom types (like _id) in query.

Then use from_json Ansible filter to parse output.

```<code>- hosts: localhost
  vars:
    qry: "db.repo.findOne({ $and: [{'product': 'Admin'}, {'env':'SHK'}] },{_id:false})"

  tasks:
    - name: Get data
      command: mongo Advantage --quiet --eval "{{qry}}"
      register: temp

    - name: Save parsed data
      set_fact:
        mongo_result: "{{ temp.stdout | from_json }}"

    - name: Print some data
      debug:
        var: mongo_result.appName
</code>```

Body:
I can able to print the mongodb data using ansible. but here my requirement is to use the printed data as variables in ansible.

here is the output I'm getting ansible playbook output:

here is my ansible playbook.

---
- hosts: localhost
  vars:
    - i: "db.repo.find({ $and: [{'product': 'Admin'}, {'env':'SHK'}] }).pretty()"

  tasks:
  - name: Printing the retrieved data
    command: mongo Advantage --quiet --eval "{{i}}"
    register: temp

  - name: Printing the retrieved data
    set_fact:
     "{{item}}"
    with_items:
      - [ "{{temp.stdout.split('\t')[0] }}", "{{temp.stdout.split('\t')[1] }}", "{{temp.stdout.split('\t')[2] }}", "{{temp.stdout.split('\t')[3] }}", "{{temp.stdout.split('\t')[4] }}", "{{temp.stdout.split('\t')[5] }}", "{{temp.stdout.split('\t')[6] }}", "{{temp.stdout.split('\t')[7] }}", "{{temp.stdout.split('\t')[8] }}", "{{temp.stdout.split('\t')[9] }}" ]

- include: /etc/ansible/roles/patchdeployment_3_11_2/tasks/applypatch/applypatch_windows_websphere.yml PR_ID={{PR_ID}}
#- include: /etc/ansible/roles/patchdeployment_3_11_2/tasks/applypatch/applypatch_linux_websphere.yml

please help me on the same.

Body:
Make mongo output pure JSON friendly by disabling all fields with custom types (like _id) in query.

Then use from_json Ansible filter to parse output.

- hosts: localhost
  vars:
    qry: "db.repo.findOne({ $and: [{'product': 'Admin'}, {'env':'SHK'}] },{_id:false})"

  tasks:
    - name: Get data
      command: mongo Advantage --quiet --eval "{{qry}}"
      register: temp

    - name: Save parsed data
      set_fact:
        mongo_result: "{{ temp.stdout | from_json }}"

    - name: Print some data
      debug:
        var: mongo_result.appName


问:
join symbol in javascript
I want to produce

1 • 2

But below code won't work?

```<code>const arr = [1,2]

console.log(arr.join(' - '))

console.log(arr.join(' • ')) // doesn't work
</code>```

答:
Try using HexCode...

const arr = [1,2]

console.log(arr.join(' - '))

console.log(arr.join( '\u2022' )) // doesn't work •```

Title: join symbol in javascript

Body:
I want to produce

1 • 2

But below code won't work?

const arr = [1,2]

console.log(arr.join(' - '))

console.log(arr.join(' • ')) // doesn't work

Body:
Try using HexCode...

const arr = [1,2]

console.log(arr.join(' - '))

console.log(arr.join( '\u2022' )) // doesn't work &#8226;


问:
Is there an API for api.ai which can be used to add intents and train the model?
I couldn't find an API for api.ai. The requirement is to add intents and train the model programmatically through an ajax API call.</p>

答:
Yes, API.AI has a REST-like API that lets you manipulate Intents, Entities, user specific and session Entities, Contexts, and even execute Queries.

You'll need to read details about the developer token and the version string to use, but documentation about getting, creating, updating, and deleting intents, as well as the layout for the intent object, are available at https://api.ai/docs/reference/agent/intents

If you're familiar with REST-like APIs, it is pretty straightforward.


问:
How to get previous 2 years data in OBIEE 11g analysis
When I click year prompt, It must display both current year along with previous 2 years data in OBI 11g (Analysis).

eg., when I click 2015 in prompt, It must display 2015,2016 and 2014's data.

Could anyone of you suggest me how to do it?

答:
Many options. Fastest = presentation variable + analysis filter:

```<code>"Time"."Year" >= @{pv_Year}{2017} - 2 AND "Time"."Year" <= @{pv_Year}{2017}
</code>```

This of course assumes that your "Year" is a numeric value and not a string.

Body:
Many options. Fastest = presentation variable + analysis filter:

"Time"."Year" >= @{pv_Year}{2017} - 2 AND "Time"."Year" <= @{pv_Year}{2017}

This of course assumes that your "Year" is a numeric value and not a string.


问:
Regex : How to return an array of matches that need different regex?
I have to transform txt files in json files, so I use regex to parse different type of datas. I want to record data such as first name, last name, birthday and other stuff.

The data are formatted this way :

```<code>/Indicator /
/[A-Z][a-z]+ /
/[A-Z][a-z]+ /
/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/
</code>```

More specific example :

```<code>Indicator Tom Smith 01/01/2001
</code>```

So I know how where my info begins (it always starts with "Indicator ") and that after that there is the first name then the last name then the birthday, I also know what regex to use for theses types of data individually but not how to implement them all together.

This is what I do for the moment and I doubt it is optimal or recommended :

```<code>let first_name = "";
let last_name = "";
let birthday = "";
let j = 10; // Length of "Indicator "
let regex = /Indicator /;
let match = regex.exec(data);

j += match.index;
while (data[j] !== ' ')
    first_name += data[j++];
j++;
while (data[j] !== ' ')
    last_name += data[j++];
j++;
while (data[j] !== '<')
    birthday += data[j++];
console.log(first_name);
console.log(last_name);
console.log(birthday);
</code>```

My question is, what regex rule should I use to get the array ['Tom', 'Smith', '01/01/2001'] with one execution of regex.exec ?

答:
The first question is why you want to use regex?

My suggestion:
You can directly go for str.split(" ") which will return you array of ['Indicator','Tom', 'Smith', '01/01/2001'] and you can process as you want.

For big file with such data you can do it like:

Indicator Tom Smith 01/01/2001 Indicator xyz abc 11/02/2002

you will do some thing like this :

```<code>var str = "Indicator Tom Smith 01/01/2001 Indicator xyz abc 11/02/2002";
var strArray = str.splice(" ");
var
for(var i = 0; i < strArray.length;i++){
   if(strArray[i] === 'Indicator'){
   var firstname = strArray[i+1];
   var lastname = strArray[i+2];
   var dob = strArray[i+3];
   //use them as you want
   i += 2;
  }
}
</code>```

Body:
I have to transform txt files in json files, so I use regex to parse different type of datas. I want to record data such as first name, last name, birthday and other stuff.

The data are formatted this way :

/Indicator /
/[A-Z][a-z]+ /
/[A-Z][a-z]+ /
/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/

More specific example :

Indicator Tom Smith 01/01/2001

So I know how where my info begins (it always starts with "Indicator ") and that after that there is the first name then the last name then the birthday, I also know what regex to use for theses types of data individually but not how to implement them all together.

This is what I do for the moment and I doubt it is optimal or recommended :

let first_name = "";
let last_name = "";
let birthday = "";
let j = 10; // Length of "Indicator "
let regex = /Indicator /;
let match = regex.exec(data);

j += match.index;
while (data[j] !== ' ')
    first_name += data[j++];
j++;
while (data[j] !== ' ')
    last_name += data[j++];
j++;
while (data[j] !== '<')
    birthday += data[j++];
console.log(first_name);
console.log(last_name);
console.log(birthday);

My question is, what regex rule should I use to get the array ['Tom', 'Smith', '01/01/2001'] with one execution of regex.exec ?

Body:
The first question is why you want to use regex?

My suggestion:
You can directly go for str.split(" ") which will return you array of ['Indicator','Tom', 'Smith', '01/01/2001'] and you can process as you want.

For big file with such data you can do it like:

Indicator Tom Smith 01/01/2001 Indicator xyz abc 11/02/2002

you will do some thing like this :

var str = "Indicator Tom Smith 01/01/2001 Indicator xyz abc 11/02/2002";
var strArray = str.splice(" ");
var
for(var i = 0; i < strArray.length;i++){
   if(strArray[i] === 'Indicator'){
   var firstname = strArray[i+1];
   var lastname = strArray[i+2];
   var dob = strArray[i+3];
   //use them as you want
   i += 2;
  }
}


问:
how can i send http post request from localhost:5000 to localhost:3000
I'm trying to send a http post request from application running on localhost:5000 to my server at localhost:3000

this angular script is running on localhost:5000

```<code>    var data = {name:"john", description:"100"};
    var url = 'localhost:3000/razor';

    $http.post(url, data).then(function(response){
      if(response.data){
        console.log("success");
      } else {
        console.log("failure");
      }
    });
</code>```

localhost:3000 is not receiving any POST request. What should I do?
Error in console -

```<code>Error: A network error occurred.
rg/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:107:276
p@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:102:434
n/b<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:100:207
h/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:133:460
$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:309
$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:144:412
$evalAsync/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:398
f@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:47:146
kg/k.defer/c<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:50:68
 Possibly unhandled rejection: {}
</code>```

答:
You need to add http in front of url path to make it absolute URL
Try replacing this once

var url = 'http://localhost:3000/razor';

Thanks

Body:
I'm trying to send a http post request from application running on localhost:5000 to my server at localhost:3000

this angular script is running on localhost:5000

    var data = {name:"john", description:"100"};
    var url = 'localhost:3000/razor';

    $http.post(url, data).then(function(response){
      if(response.data){
        console.log("success");
      } else {
        console.log("failure");
      }
    });

localhost:3000 is not receiving any POST request. What should I do?
Error in console -

Error: A network error occurred.
rg/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:107:276
p@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:102:434
n/b<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:100:207
h/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:133:460
$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:309
$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:144:412
$evalAsync/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:147:398
f@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:47:146
kg/k.defer/c<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js:50:68
 Possibly unhandled rejection: {}


问:
Implement Google Voice Actions in Android
How can I implement the fairly new Voice Actions from Google, in Android?

I'm thinking about the possibility to listen to the Listen to action as used by some music application.

Is there a specific broadcast my app must register as a receiver to?

答:
This is explained in Android Developers Blog: Supporting the new music Voice Action:

In your AndroidManifest.xml, just register one of your activities for the new intent android.media.action.MEDIA_PLAY_FROM_SEARCH.… When your activity receives this intent, you can find the user’s search query inside the SearchManager.QUERY string extra.


问:
i want to count table rows from sql database with between two times
```<code>SELECT *
FROM `table_name`
WHERE `time_from` >= '".$time_from."'
AND `time_to` <= '".$time_to."' AND `member_id` = '".$member_id."'
AND status ='Active'
</code>```

After getting values query like this

```<code>SELECT *
FROM `table_name`
WHERE time_from >= '2pm'
AND time_to <= '5pm'
AND `member_id` = '5'
AND date = '2017-07-08'
AND status ='Active'
</code>```

Gtting answer correct if time_from = 2pm and time_to = 5pm but if provide value like time_from 3pm to time_to 4pm it displaynum_rows '0' because in database table there is time_from value 2pm and time_to value 5pm

I want the sql query if user entered time_from 3pm and time_to 4pm or 2pm and 4pm or any value in between 2pm and 5pm, the result should be num_rows 1 or more if more than one entry is matched with provided values

答:
This will not as give count as query is treating 2pm as string not as timestamp.
you need to alter your column from varchar/text to date time and save time in required format.</p>

Body:
SELECT *
FROM `table_name`
WHERE `time_from` >= '".$time_from."'
AND `time_to` <= '".$time_to."' AND `member_id` = '".$member_id."'
AND status ='Active'

After getting values query like this

SELECT *
FROM `table_name`
WHERE time_from >= '2pm'
AND time_to <= '5pm'
AND `member_id` = '5'
AND date = '2017-07-08'
AND status ='Active'

Gtting answer correct if time_from = 2pm and time_to = 5pm but if provide value like time_from 3pm to time_to 4pm it displaynum_rows '0' because in database table there is time_from value 2pm and time_to value 5pm

I want the sql query if user entered time_from 3pm and time_to 4pm or 2pm and 4pm or any value in between 2pm and 5pm, the result should be num_rows 1 or more if more than one entry is matched with provided values


问:
Handling special characters in VARCHAR2 while converting it to json
I have the following pl/sql  block where in I am converting a VARCHAR2 type into json. I am facing an issue when the VARCHAR2 type consists of  a special character like / the json parser throws an exception:

```<code>DECLARE
oj json := json('{a/b:xy})');
BEGIN
dbms_output.put_line(oj.TO_CHAR());
END;`enter code here`

ORA-20100: JSON Scanner exception @ line: 1 column: 5 - Unexpected char: /
ORA-06512: at "PARIS.JSON_PARSER", line 87
ORA-06512: at "PARIS.JSON_PARSER", line 447
ORA-06512: at "PARIS.JSON_PARSER", line 646
ORA-06512: at "PARIS.JSON", line 13
ORA-06512: at line 2
</code>```

Can this be handled?

答:
Your json can't be parsed </p>

<p>Try to send a valid JSON and it'll work </p>

```<code>json('{"a/b": "xy"}')
</code>```

Body:
I have the following pl/sql  block where in I am converting a VARCHAR2 type into json. I am facing an issue when the VARCHAR2 type consists of  a special character like / the json parser throws an exception:

DECLARE
oj json := json('{a/b:xy})');
BEGIN
dbms_output.put_line(oj.TO_CHAR());
END;`enter code here`

ORA-20100: JSON Scanner exception @ line: 1 column: 5 - Unexpected char: /
ORA-06512: at "PARIS.JSON_PARSER", line 87
ORA-06512: at "PARIS.JSON_PARSER", line 447
ORA-06512: at "PARIS.JSON_PARSER", line 646
ORA-06512: at "PARIS.JSON", line 13
ORA-06512: at line 2

Can this be handled?

Body:
Your json can't be parsed

Try to send a valid JSON and it'll work

json('{"a/b": "xy"}')


问:
How to create modules in C
I have an interface with which I want to be able to statically link modules. For example, I want to be able to call all functions (albeit in seperate files) called FOO or that match a certain prototype, ultimately make a call into a function in the file without a header in the other files. Dont say that it is impossible since I found a hack that can do it, but I want a non hacked method. (The hack is to use nm to get functions and their prototypes then I can dynamically call the function). Also, I know you can do this with dynamic linking, however, I want to statically link the files. Any ideas?</p>

答:
Put a table of all functions into each translation unit:

```<code>struct functions MOD1FUNCS[]={
     {"FOO", foo},
     {"BAR", bar},
     {0, 0}
};
</code>```

Then put a table into the main program listing all these tables:

```<code>struct functions* ALLFUNCS[]={
    MOD1FUNCS,
    MOD2FUNCS,
    0
};
</code>```

Then, at run time, search through the tables, and lookup the corresponding function pointer.

Title: How to create modules in C

Body:
Put a table of all functions into each translation unit:

struct functions MOD1FUNCS[]={
     {"FOO", foo},
     {"BAR", bar},
     {0, 0}
};

Then put a table into the main program listing all these tables:

struct functions* ALLFUNCS[]={
    MOD1FUNCS,
    MOD2FUNCS,
    0
};

Then, at run time, search through the tables, and lookup the corresponding function pointer.


问:
Accessing Parameters mapped by @RequestMapping for Tracing
I am currently working on a monitoring application using Spring Cloud Sleuth. Currently I try to collect as much information about my requests as possible.

To keep the approach as scalable as possible I use GenericFilterBeans and HandlerInterceptorAdapter to access information from the requests sent to the REST-API.

I am struggling with getting parameters of a REST-call where the parameters are mapped from the URL like in the following code snippet:

```<code>  @RequestMapping(
            value = {"/{service}/{route_id}/book", "/accounting-core-service/{service}/{route_id}/book"},
            method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView book(@PathVariable(value="service") String serviceName,
                             @PathVariable(value = "route_id") int routeId,
                             HttpServletResponse response) {
    /*Do something*/
}
</code>```

The question is not, whether it is good practice or not to write it like so. The question is whether there is an approach similar to Filter or Interceptor (or the proper use of them) to access those parameters.

A requirement is, that it can be applied easily to an application by adding very few lines of code. Annotating every Method call manually or manually inserting the code to write the parameters into the trace from within the method is not feasible for me.

If you need more information feel free to ask. I will provide you with all information you need to help me with my problem.

答:
You can create a Filter that intercept all the requests.

For each request you can retrieve also this informations:

query parameters

body of request

url

header parameters

You can save all this data as you need.
This is the best way you can do that.

If you need to group all urls like /{service}/{route_id}/book in a "family" of urls you can do that splitting the url and check if it is part of the family, but when a new family is added in your code you need to update the filter (or configure something in an external file or database).

Body:
I am currently working on a monitoring application using Spring Cloud Sleuth. Currently I try to collect as much information about my requests as possible.

To keep the approach as scalable as possible I use GenericFilterBeans and HandlerInterceptorAdapter to access information from the requests sent to the REST-API.

I am struggling with getting parameters of a REST-call where the parameters are mapped from the URL like in the following code snippet:

  @RequestMapping(
            value = {"/{service}/{route_id}/book", "/accounting-core-service/{service}/{route_id}/book"},
            method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView book(@PathVariable(value="service") String serviceName,
                             @PathVariable(value = "route_id") int routeId,
                             HttpServletResponse response) {
    /*Do something*/
}

The question is not, whether it is good practice or not to write it like so. The question is whether there is an approach similar to Filter or Interceptor (or the proper use of them) to access those parameters.

A requirement is, that it can be applied easily to an application by adding very few lines of code. Annotating every Method call manually or manually inserting the code to write the parameters into the trace from within the method is not feasible for me.

If you need more information feel free to ask. I will provide you with all information you need to help me with my problem.


问:
fatal: unable to get credential storage lock: File exists
I am using git-scm and tried to push to a repository. Upon doing so, I was greeted with the following message:

```<code>fatal: unable to get credential storage lock: File exists
</code>```

While the push did end up pushing successfully, I was wondering why this error appeared. It is still doing this, and was not doing this before. Any help is appreciated. Thanks!

答:
I've had a hard time figuring out where the lock file was.
On Linux, just use strace, but don't forget to follow child processes with the -f option:

```<code>strace -f -eopen git credential-store --file=~/mystore store < creds
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libpcre.so.3", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libz.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libresolv.so.2", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/dev/null", O_RDWR)               = 3
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
open("/home/g179531/.gitconfig", O_RDONLY) = 3
Process 8269 attached
[pid  8269] open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libpcre.so.3", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libz.so.1", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("~/mystore.lock", O_RDWR|O_CREAT|O_EXCL, 0666) = -1 ENOENT (No such file or directory)
fatal: unable to get credential storage lock: No such file or directory
[pid  8269] +++ exited with 128 +++
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=8269, si_status=128, si_utime=0, si_stime=0} ---
+++ exited with 128 ++
</code>```

The last file that the program tried to open before printing the error is the lock file. In my case, it's ~/mystore.lock.

Body:
I am using git-scm and tried to push to a repository. Upon doing so, I was greeted with the following message:

fatal: unable to get credential storage lock: File exists

While the push did end up pushing successfully, I was wondering why this error appeared. It is still doing this, and was not doing this before. Any help is appreciated. Thanks!

Body:
I've had a hard time figuring out where the lock file was.
On Linux, just use strace, but don't forget to follow child processes with the -f option:

strace -f -eopen git credential-store --file=~/mystore store < creds
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libpcre.so.3", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libz.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libresolv.so.2", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/dev/null", O_RDWR)               = 3
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
open("/home/g179531/.gitconfig", O_RDONLY) = 3
Process 8269 attached
[pid  8269] open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libpcre.so.3", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libz.so.1", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
[pid  8269] open("~/mystore.lock", O_RDWR|O_CREAT|O_EXCL, 0666) = -1 ENOENT (No such file or directory)
fatal: unable to get credential storage lock: No such file or directory
[pid  8269] +++ exited with 128 +++
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=8269, si_status=128, si_utime=0, si_stime=0} ---
+++ exited with 128 ++

The last file that the program tried to open before printing the error is the lock file. In my case, it's ~/mystore.lock.


问:
Reactjs AutoComplete : 'off'
```<code><div className={inputContainerClass}>
 <input
                    required
                    autoComplete='off'
                    value={value}
                    type='password'
                    maxLength=15
                />

</div>
</code>```

autoComplete : 'off', autoComplete: {'off'}, autocomplete:{false}, <input type="password"  style="display:none"> are not working.

答:
You need to use autoComplete="off". See working example.

const Element = () => (

    <input
      name="email"
      autoComplete="off" />

);

ReactDOM.render(
  <Element />,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div></code>```

ContentLicense: CC BY-SA 4.0

Title: Reactjs AutoComplete : 'off'

Body:
 <input
                    required
                    autoComplete='off'
                    value={value}
                    type='password'
                    maxLength=15
                />

autoComplete : 'off', autoComplete: {'off'}, autocomplete:{false}, <input type="password"  style="display:none"> are not working.

Body:
You need to use autoComplete="off". See working example.

const Element = () => (
  <div>
    <input
      name="email"
      autoComplete="off" />
  </div>
);

ReactDOM.render(
  <Element />,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>


问:
Custom taglib not loaded with Liferay7
I am migrating my Liferay portlets from 6.0 to Liferay 7.0 and one of the many roadblocks that I am hitting is the inclusion of my custom taglib.

I followed the advice from: Creating a custom taglib in Liferay 7 but my portlet fails to load the taglib, the following error is logged:

09:50:48,566 ERROR [http-nio-8080-exec-10][FreeMarkerManager:208] Unable to add taglib my_tags to context
FreeMarker template error:
freemarker.template.TemplateModelException: Error while loading tag library for URI "/META-INF/my_tags.tld" from TLD location "servletContext:/META-INF/my_tags.tld"; see cause exception.
        at freemarker.ext.jsp.TaglibFactory.get(TaglibFactory.java:260)
        at com.liferay.portal.template.freemarker.internal.FreeMarkerManager$TaglibFactoryWrapper.get(FreeMarkerManager.java:647)
        at com.liferay.portal.template.freemarker.internal.FreeMarkerManager.addTaglibSupport(FreeMarkerManager.java:205)
        at com.liferay.taglib.util.ThemeUtil.doIncludeFTL(ThemeUtil.java:276)
        at com.liferay.taglib.util.ThemeUtil.doDispatch(ThemeUtil.java:157)
        at com.liferay.taglib.util.ThemeUtil.includeFTL(ThemeUtil.java:100)
        at com.liferay.taglib.util.ThemeUtil.include(ThemeUtil.java:82)
```

<p>However, my bundle JAR <strong>does</strong> contain <code>META-INF/my_tags.tld</code></p>

<p>What strikes me, is that the error does not happen when my JSP is loaded but somewhere inside the theme's FreeMarker template. Apparently my JSP isn't even loaded at that point. </p>

<p>The error is thrown on <strong>each</strong> page in my portal, not only those that contain my portlet(s) (which is to be expected if the theme is already failing to access the taglib)</p>

<p>The structure of the bundle JAR is: </p>

<pre class="lang-none prettyprint-override"><code>com/
content/
META-INF/
   +--- resources/
   MANIFEST.MF
   taglib-mappings.properties
   my_tags.tld
OSGI-INF/
WEB-INF/
</code>```

The MANIFEST.MF that is generated by the bnd task contains the following dependency:

```<code>Require-Capability: osgi.extender;osgi.extender="jsp.taglib";uri="/META-INF/my_tags.tld"
</code>```

The file taglib-mappings.properties contains:

```<code>my_tags=/META-INF/my_tags.tld
</code>```

I also tried putting the .tld files into WEB-INF/tld where it would be with a plain, simple, standard portlet or web application, but to no avail either.

Do I need to add a mapping in the web.xml (I am not sure if the new OSGi portlets even use web.xml) or add some other configuration option?

答:
OK, I managed to figure this out by myself.

The directory layout needs to be like this:

```<code>+---java
|   \---com
|       \---mypackage
|           |
|           +---portlet
|           |       MyPortlet.java
|           |
|           \---tags
|                   LabelTag.java
|
\---resources
    +---content
    |       Language.properties
    |
    +---META-INF
    |   |   my_tags.tld
    |   |
    |   \---resources
    |       |   view.jsp
    |
    \---WEB-INF
</code>```

In contrast to some hints on the internet, the file taglib-mappings.properties is not needed. If it is present, Liferay throws a gazillion of exceptions because the Freemarker engine tries to access the taglibs that are referenced in taglib-mappings.properties.

And my_tags.tld contains the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.1</jsp-version>
  <short-name>ka</short-name>
  <uri>http://example.com/tld/my_tags</uri>

  <tag>
    <name>label</name>
    <tag-class>com.mypackage.tags.LabelTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
      <name>labelText</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.lang.String</type>
    </attribute>
  </tag>
</taglib>
</code>```

The in the JSP page, the tag is defined as:

```<code><%@ taglib uri="http://example.com/tld/my_tags" prefix="my" %>
</code>```

I do not include a Require-Capability: for my own tags in the OSGI MANIFEST.MF file.

I only include that for the standard JSTL and Liferay tags:

```<code>Require-Capability: osgi.extender;filter:="(&(osgi.extender=jsp.taglib)(
 uri=http://java.sun.com/portlet_2_0))",osgi.extender;filter:="(&(osgi.e
 xtender=jsp.taglib)(uri=http://liferay.com/tld/aui))",osgi.extender;fil
 ter:="(&(osgi.extender=jsp.taglib)(uri=http://liferay.com/tld/portlet))
 ",osgi.extender;filter:="(&(osgi.extender=jsp.taglib)(uri=http://lifera
 y.com/tld/theme))",osgi.extender;filter:="(&(osgi.extender=jsp.taglib)(
 uri=http://liferay.com/tld/ui))",osgi.ee;filter:="(&(osgi.ee=JavaSE)(ve
 rsion=1.8))"
</code>```

However, I did need to exclude some packages in the OSGI bnd.bnd file that were included due to the dependency on javax.servlet.jsp and jstl

```<code>Import-Package: \
    .....
    !com.ibm.*,\
    !com.sun.*,\
    !javax.jmdns.*,\
    *
</code>```

Title: Custom taglib not loaded with Liferay7

Body:
I am migrating my Liferay portlets from 6.0 to Liferay 7.0 and one of the many roadblocks that I am hitting is the inclusion of my custom taglib.

I followed the advice from: Creating a custom taglib in Liferay 7 but my portlet fails to load the taglib, the following error is logged:

09:50:48,566 ERROR [http-nio-8080-exec-10][FreeMarkerManager:208] Unable to add taglib my_tags to context
FreeMarker template error:
freemarker.template.TemplateModelException: Error while loading tag library for URI "/META-INF/my_tags.tld" from TLD location "servletContext:/META-INF/my_tags.tld"; see cause exception.
        at freemarker.ext.jsp.TaglibFactory.get(TaglibFactory.java:260)
        at com.liferay.portal.template.freemarker.internal.FreeMarkerManager$TaglibFactoryWrapper.get(FreeMarkerManager.java:647)
        at com.liferay.portal.template.freemarker.internal.FreeMarkerManager.addTaglibSupport(FreeMarkerManager.java:205)
        at com.liferay.taglib.util.ThemeUtil.doIncludeFTL(ThemeUtil.java:276)
        at com.liferay.taglib.util.ThemeUtil.doDispatch(ThemeUtil.java:157)
        at com.liferay.taglib.util.ThemeUtil.includeFTL(ThemeUtil.java:100)
        at com.liferay.taglib.util.ThemeUtil.include(ThemeUtil.java:82)

However, my bundle JAR does contain META-INF/my_tags.tld

What strikes me, is that the error does not happen when my JSP is loaded but somewhere inside the theme's FreeMarker template. Apparently my JSP isn't even loaded at that point.

The error is thrown on each page in my portal, not only those that contain my portlet(s) (which is to be expected if the theme is already failing to access the taglib)

The structure of the bundle JAR is:

com/
content/
META-INF/
   +--- resources/
   MANIFEST.MF
   taglib-mappings.properties
   my_tags.tld
OSGI-INF/
WEB-INF/

The MANIFEST.MF that is generated by the bnd task contains the following dependency:

Require-Capability: osgi.extender;osgi.extender="jsp.taglib";uri="/META-INF/my_tags.tld"

The file taglib-mappings.properties contains:

my_tags=/META-INF/my_tags.tld

I also tried putting the .tld files into WEB-INF/tld where it would be with a plain, simple, standard portlet or web application, but to no avail either.

Do I need to add a mapping in the web.xml (I am not sure if the new OSGi portlets even use web.xml) or add some other configuration option?

Body:
OK, I managed to figure this out by myself.

The directory layout needs to be like this:

+---java
|   \---com
|       \---mypackage
|           |
|           +---portlet
|           |       MyPortlet.java
|           |
|           \---tags
|                   LabelTag.java
|
\---resources
    +---content
    |       Language.properties
    |
    +---META-INF
    |   |   my_tags.tld
    |   |
    |   \---resources
    |       |   view.jsp
    |
    \---WEB-INF

In contrast to some hints on the internet, the file taglib-mappings.properties is not needed. If it is present, Liferay throws a gazillion of exceptions because the Freemarker engine tries to access the taglibs that are referenced in taglib-mappings.properties.

And my_tags.tld contains the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.1</jsp-version>
  <short-name>ka</short-name>
  <uri>http://example.com/tld/my_tags</uri>

  <tag>
    <name>label</name>
    <tag-class>com.mypackage.tags.LabelTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
      <name>labelText</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.lang.String</type>
    </attribute>
  </tag>
</taglib>

The in the JSP page, the tag is defined as:

<%@ taglib uri="http://example.com/tld/my_tags" prefix="my" %>

I do not include a Require-Capability: for my own tags in the OSGI MANIFEST.MF file.

I only include that for the standard JSTL and Liferay tags:

Require-Capability: osgi.extender;filter:="(&(osgi.extender=jsp.taglib)(
 uri=http://java.sun.com/portlet_2_0))",osgi.extender;filter:="(&(osgi.e
 xtender=jsp.taglib)(uri=http://liferay.com/tld/aui))",osgi.extender;fil
 ter:="(&(osgi.extender=jsp.taglib)(uri=http://liferay.com/tld/portlet))
 ",osgi.extender;filter:="(&(osgi.extender=jsp.taglib)(uri=http://lifera
 y.com/tld/theme))",osgi.extender;filter:="(&(osgi.extender=jsp.taglib)(
 uri=http://liferay.com/tld/ui))",osgi.ee;filter:="(&(osgi.ee=JavaSE)(ve
 rsion=1.8))"

However, I did need to exclude some packages in the OSGI bnd.bnd file that were included due to the dependency on javax.servlet.jsp and jstl

Import-Package: \
    .....
    !com.ibm.*,\
    !com.sun.*,\
    !javax.jmdns.*,\
    *


问:
sails lift error in sail.js application in command prompt?
I try to run the sail application but I got an error  when using sails lift.I followed the procedure to install the sail.js. I created one notepad file I uses the command node C:\Users\Vignesh Ravi\AppData\Roaming\npm\node_modules\sails\bin\sails.js lift and save as sails.bat file and put into C:\Windows\System32.but still I got an error can anyone solve this error? Thanks in advance....

I followed the procedure:

C:\Users\Vignesh Ravi>cd AppData

C:\Users\Vignesh Ravi\AppData>cd Roaming

C:\Users\Vignesh Ravi\AppData\Roaming>cd npm

C:\Users\Vignesh Ravi\AppData\Roaming\npm>sails new xyz
=====================================================
You seem to be using NPM >= v3.0.0, which no longer
supports symbolic links in the `node_modules/` folder.
As of Feb. 2016, the Sails team is still working on a
speedier solution to optimize `sails new` that will
be released as a 0.12.x patch. But in the mean time,
your new Sails app's dependencies must be set up
using `npm install`.
Because of this, creating your new Sails app will
take longer than you might be used to. Please bear
with us; or if you have a need for speed, downgrade
to NPM < v3.0.0 in the mean time.  Thanks!
=====================================================
Installing dependencies... (this could take a little while)
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN prefer global coffee-script@1.10.0 should be installed with -g
npm notice created a lockfile as package-lock.json. You should commit this file.
added 261 packages in 22.306s
info: Created a new Sails app `xyz`!

C:\Users\Vignesh Ravi\AppData\Roaming\npm>cd xyz

C:\Users\Vignesh Ravi\AppData\Roaming\npm\xyz>npm install
up to date in 3.282s

C:\Users\Vignesh Ravi\AppData\Roaming\npm\xyz>sails lift

C:\Users\Vignesh Ravi\AppData\Roaming\npm\xyz>node C:\Users\Vignesh Ravi\AppData\Roaming\npm\node_modules\sails\bin\sails.js lift
module.js:487
    throw err;
    ^

Error: Cannot find module 'C:\Users\Vignesh'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3```

答:
Try this,

```<code>$ sails new sdc
$ cd sdc
$ npm install
$ sails lift
</code>```

What you are missing?

You are running sails lift in a wrong directory

Body:
Try this,

$ sails new sdc
$ cd sdc
$ npm install
$ sails lift

What you are missing?

You are running sails lift in a wrong directory


问:
Odoo - Add (AM/PM) in datetime in qweb report
```<code><span t-field="o.date_order"/>
</code>```

which gives output as:

04/11/2017 09:48:35

But how can I get output like:

04/11/2017 09:48 AM

答:
Hello Aiswarya,

Try this below code,

1. Using Template,

If your o.date_order field return this format type 10/10/2017 10:10 AM DateTime with AM/PM so use below code otherwise gives the error.

```<code><td>
    Order Date:
    <t t-esc="time.strftime('%d/%m/%Y %H:%M %a',time.strptime(o.date_order,'%d/%m/%Y %H:%M %a'))" />
</td>
</code>```

2. You can also be using create function in python,

If you have multiple date fields use same or different date format so python function use is better because improve Reusability of code.

1. First your report.py file inside write below code,

```<code>def __init__(self, cr, uid, name, context=None):
    super(class_name, self).__init__(cr, uid, name, context=context)

    self.localcontext.update({
        'format_date':self.format_date
    })

def format_date(self,date):
        if date:
           return str(datetime.strptime(o.date_order, '%d/%m/%Y %H:%M %a').strftime('%d/%m/%Y %H:%M %a'))
</code>```

2. Second your report_view_template.xml file inside write below code,

```<code><td>
    Order Date:
    <t t-esc="format_date(o.date_order)" />
</td>
</code>```

I hope my answer is helpful. If any query so comments, please.

Body:
Hello Aiswarya,

Try this below code,

1. Using Template,

If your o.date_order field return this format type 10/10/2017 10:10 AM DateTime with AM/PM so use below code otherwise gives the error.

<td>
    Order Date:
    <t t-esc="time.strftime('%d/%m/%Y %H:%M %a',time.strptime(o.date_order,'%d/%m/%Y %H:%M %a'))" />
</td>

2. You can also be using create function in python,

If you have multiple date fields use same or different date format so python function use is better because improve Reusability of code.

1. First your report.py file inside write below code,

def __init__(self, cr, uid, name, context=None):
    super(class_name, self).__init__(cr, uid, name, context=context)

    self.localcontext.update({
        'format_date':self.format_date
    })

def format_date(self,date):
        if date:
           return str(datetime.strptime(o.date_order, '%d/%m/%Y %H:%M %a').strftime('%d/%m/%Y %H:%M %a'))

2. Second your report_view_template.xml file inside write below code,

<td>
    Order Date:
    <t t-esc="format_date(o.date_order)" />
</td>

I hope my answer is helpful. If any query so comments, please.


问:
'module' object has no attribute 'PortScanner'
I'm using Ubuntu 12.04 and installed python-nmap to create a script.  If I use IDLE and type in the following, it runs fine:

```<code>import nmap
nm = nmap.PortScanner()
nm.scan('127.0.0.1', '22-443')
</code>```

However, if I perform this in Eclipse, I receive the following error:

```<code>Traceback (most recent call last):
  File "/home/russ/workspace/ViPyNmap/MyFiles/nmaptest.py", line 2, in <module>
    nm = nmap.PortScanner()
AttributeError: 'module' object has no attribute 'PortScanner'
</code>```

I've added the egg file and also the folder to the Eclipse path for the project, with no luck.  I've also restarted Eclipse after doing so, with no luck. I apologize for my inexperience with both Eclipse and Python and appreciate the help.

答:
You likely installed the package "nmap", not "python-nmap":

So, just uninstall "nmap" and install "python-nmap":

```<code>pip uninstall nmap
pip install python-nmap
</code>```

Body:
I'm using Ubuntu 12.04 and installed python-nmap to create a script.  If I use IDLE and type in the following, it runs fine:

import nmap
nm = nmap.PortScanner()
nm.scan('127.0.0.1', '22-443')

However, if I perform this in Eclipse, I receive the following error:

Traceback (most recent call last):
  File "/home/russ/workspace/ViPyNmap/MyFiles/nmaptest.py", line 2, in <module>
    nm = nmap.PortScanner()
AttributeError: 'module' object has no attribute 'PortScanner'

I've added the egg file and also the folder to the Eclipse path for the project, with no luck.  I've also restarted Eclipse after doing so, with no luck. I apologize for my inexperience with both Eclipse and Python and appreciate the help.

Body:
You likely installed the package "nmap", not "python-nmap":

So, just uninstall "nmap" and install "python-nmap":

pip uninstall nmap
pip install python-nmap


问:
C#: Why is my background worker thread signaling done when it isn't?
C#, using VS2010 and I've got something that makes no sense.

At startup my program needs to load several hundred k from text files.  After ensuring the loading code was working fine I threw it in a background thread.  So long as this is run from within the IDE everything's fine but when it's run standalone the thread says it's done when it isn't.  This of course goes boom.

The trigger code:

```<code>BackgroundWorker Background = new BackgroundWorker();
Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DatabaseLoaded);
Background.DoWork += new DoWorkEventHandler(delegate { Database.Load(); });
Background.RunWorkerAsync();
</code>```

and the stuff that's going boom is in DatabaseLoaded().

I put some messageboxes to trace what's going on:  The first and last lines of the Load() method and the first line of DatabaseLoaded().

In the IDE this triggers as I expect:  Load() beginning, Load() done, DatabaseLoaded().  However, when run standalone I get Load() beginning, DatabaseLoaded() and then the unhandled exception box (the loader hasn't even gotten to build empty tables, let alone fill them.)

Am I nuts or is Microsoft?

答: There's probably an exception thrown from Database.Load(). BackgroundWorker catches any unhandled exception before triggering the RunWorkerCompleted event. Check the RunWorkerCompletedEventArgs.Error property in DatabaseLoaded.

Body:
C#, using VS2010 and I've got something that makes no sense.

At startup my program needs to load several hundred k from text files.  After ensuring the loading code was working fine I threw it in a background thread.  So long as this is run from within the IDE everything's fine but when it's run standalone the thread says it's done when it isn't.  This of course goes boom.

The trigger code:

BackgroundWorker Background = new BackgroundWorker();
Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DatabaseLoaded);
Background.DoWork += new DoWorkEventHandler(delegate { Database.Load(); });
Background.RunWorkerAsync();

and the stuff that's going boom is in DatabaseLoaded().

I put some messageboxes to trace what's going on:  The first and last lines of the Load() method and the first line of DatabaseLoaded().

In the IDE this triggers as I expect:  Load() beginning, Load() done, DatabaseLoaded().  However, when run standalone I get Load() beginning, DatabaseLoaded() and then the unhandled exception box (the loader hasn't even gotten to build empty tables, let alone fill them.)

Am I nuts or is Microsoft?