问:
UIDatePicker not showing up in UITextField. Swift 3
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}
</code>```

答:
There is two change in your code which is below..

1.

```<code>pickerView5.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
</code>```

2.

```<code>func datePickerValueChanged(sender:UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    whenTextField.text = dateFormatter.string(from: sender.date)
}
</code>```

Complete running code

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!

//    @IBAction func whenTextField(_ sender: UITextField) {
//
//        let datePickerView:UIDatePicker = UIDatePicker()
//        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
//        sender.inputView = datePickerView
//        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
//    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()

        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;

        pickerView5.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {

        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}
</code>```

Body:
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}

Body:
There is two change in your code which is below..

1.

pickerView5.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)

2.

func datePickerValueChanged(sender:UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    whenTextField.text = dateFormatter.string(from: sender.date)
}

Complete running code

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!

//    @IBAction func whenTextField(_ sender: UITextField) {
//
//        let datePickerView:UIDatePicker = UIDatePicker()
//        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
//        sender.inputView = datePickerView
//        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
//    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()

        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;

        pickerView5.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {

        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}


来源: stackexchange

问:
Replace string on a line using sed command
I have following content in a file

```<code>return o.baseUrl="http://info.example.com/api/v1/",a.init=t,o.login=e(o.baseUrl+"login",{email:"@email",password:"@password"}
</code>```

I want to replace info.example.com with api.example.com

Currently I am using

```<code>sed -i "s/^info\.example\.com.*$/api.example.com/g" /var/html/www/index.js
</code>```

But this is not working.
I don't know much about regular expression.
Can somebody help me on this ?

答:
^ anchor matches info\.example\.com at the beginning of the lines.

Anchors are useless in your case. Remove the ^ and $ from your pattern:

```<code>sed -i 's/info\.example\.com/api.example.com/g' /var/html/www/index.js
</code>```

More about anchors here.

ContentLicense: CC BY-SA 3.0

Body:
I have following content in a file

return o.baseUrl="http://info.example.com/api/v1/",a.init=t,o.login=e(o.baseUrl+"login",{email:"@email",password:"@password"}

I want to replace info.example.com with api.example.com

Currently I am using

sed -i "s/^info\.example\.com.*$/api.example.com/g" /var/html/www/index.js

But this is not working.
I don't know much about regular expression.
Can somebody help me on this ?

Body:
^ anchor matches info\.example\.com at the beginning of the lines.

Anchors are useless in your case. Remove the ^ and $ from your pattern:

sed -i 's/info\.example\.com/api.example.com/g' /var/html/www/index.js

More about anchors here.


问:
How can I modify multicast TCP/IP packets' TTL?
I'm supporting a 3rd party app that sends multicast packets with a TTL of 1.  We cannot modify the app, but need a higher TTL to route the packets to another customer's network. Is there a network appliance or windows (server 2003) app that will let me modify this?

Is there a better approach for connecting the sender and receiver in this scenario?

答: You might check out mTunnel, it is made to tunnel multicast traffic. </p>

OwnerDisplayName: Daniel

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: ceretullis


问:
why can't we do Html.ActionLink("Edit Dinner", "Edit", new { dinner=Model })?
```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        <%:Model.Title %></h2>
    <fieldset>
        <legend>
            <%: Model.HostedBy %></legend>
        <p>
            <strong>When: </strong>
            <%: Model.EventDate.ToShortDateString() %>
            <strong>at: </strong>
            <%: Model.EventDate.ToShortTimeString() %>
        </p>
        <p>
            <strong>Description: </strong>
            <%: Model.Description %>
        </p>
    </fieldset>
    <p>
        <%: Html.ActionLink("Edit Dinner", "Edit", new { dinner=Model }) %>
        |
        <%: Html.ActionLink("Delete Dinner", "Delete", new { id=Model.DinnerId }) %>
        |
        <%: Html.ActionLink("Back to Dinner list", "Index") %>
    </p>
</asp:Content>
</code>```

<hr>

```<code>public ActionResult Edit(Dinner dinner)
{
    //Dinner dinner = dinnerRepository.GetDinnerById(id);

    if (dinner == null)
        return View("NotFound");
    else
        return View(dinner);
}

[HttpPost]
public ActionResult Edit(Dinner dinner, object dummy)
{
    Dinner temp = dinnerRepository.GetDinnerById(dinner.DinnerId);

    if (TryUpdateModel(temp))
    {
        dinnerRepository.Save();

        return RedirectToAction("Details", new { id = dinner.DinnerId });
    }
    else
        return View(temp);
}
</code>```

答:
What would you expect the output HTML to look like?

Ultimately, whatever data you shove in your RouteValues dictionary needs to be rendered as part of the (text) href for the hyperlink:-

```<code><a href="Dinners/Edit/<!-- We can't put a Dinner in here!! -->">Edit Dinner</a>
</code>```

Edit:

In fact, if you look at your controller code, you're grabbing the id of the model that gets passed in and looking it up from the database again anyway!

If having action methods take id parameters offends you, you can have a look at using the ModelBinder framework to do the database lookup for you. That's a bit controversial though. I'd just go with how the examples do it until you've got a feel for the framework.

Body:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

        <%:Model.Title %>

    <fieldset>
        <legend>
            <%: Model.HostedBy %></legend>

            When:
            <%: Model.EventDate.ToShortDateString() %>
            at:
            <%: Model.EventDate.ToShortTimeString() %>

            Description:
            <%: Model.Description %>

    </fieldset>

        <%: Html.ActionLink("Edit Dinner", "Edit", new { dinner=Model }) %>
        |
        <%: Html.ActionLink("Delete Dinner", "Delete", new { id=Model.DinnerId }) %>
        |
        <%: Html.ActionLink("Back to Dinner list", "Index") %>

</asp:Content>

public ActionResult Edit(Dinner dinner)
{
    //Dinner dinner = dinnerRepository.GetDinnerById(id);

    if (dinner == null)
        return View("NotFound");
    else
        return View(dinner);
}

[HttpPost]
public ActionResult Edit(Dinner dinner, object dummy)
{
    Dinner temp = dinnerRepository.GetDinnerById(dinner.DinnerId);

    if (TryUpdateModel(temp))
    {
        dinnerRepository.Save();

        return RedirectToAction("Details", new { id = dinner.DinnerId });
    }
    else
        return View(temp);
}

Body:
What would you expect the output HTML to look like?

Ultimately, whatever data you shove in your RouteValues dictionary needs to be rendered as part of the (text) href for the hyperlink:-

<a href="Dinners/Edit/<!-- We can't put a Dinner in here!! -->">Edit Dinner</a>

Edit:

In fact, if you look at your controller code, you're grabbing the id of the model that gets passed in and looking it up from the database again anyway!

If having action methods take id parameters offends you, you can have a look at using the ModelBinder framework to do the database lookup for you. That's a bit controversial though. I'd just go with how the examples do it until you've got a feel for the framework.


问:
How to get the date period by months in pgSQL as an integer
How can I get the date period by months in pgsql. I need to divide a value by month range of the date period. Like 2016/01/31 and 2016/03/31 have 2 months of period and I need to divide a value by 2. I am sending two dates as parameters for the pgSQL stored procedure.

答:
Here is Function Date Period by Months Period Return Integer

```<code>CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE
v_result integer;
BEGIN

select into v_result date_part('months',end_date::date)- date_part('months',start_date::date) as date_period;

/* v_result is integer */
RETURN (v_result);

/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;
</code>```

EXEC: SELECT * FROM date_period('2016/01/31','2016/05/31');

FOR DIFFERENT YEAR YOU COULD USE THIS FUNCTION

```<code>CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE
v_result integer;
BEGIN

select into v_result ((extract( epoch from end_date::date)-extract( epoch from start_date::date))/60/60/24/30)::integer as date_period;

/* v_result is integer */
RETURN (v_result);

/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;
</code>```

EXEC: SELECT * FROM date_period('2016/01/31','2017/03/31');

Body:
Here is Function Date Period by Months Period Return Integer

CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE
v_result integer;
BEGIN

select into v_result date_part('months',end_date::date)- date_part('months',start_date::date) as date_period;

/* v_result is integer */
RETURN (v_result);

/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;

EXEC: SELECT * FROM date_period('2016/01/31','2016/05/31');

FOR DIFFERENT YEAR YOU COULD USE THIS FUNCTION

CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE
v_result integer;
BEGIN

select into v_result ((extract( epoch from end_date::date)-extract( epoch from start_date::date))/60/60/24/30)::integer as date_period;

/* v_result is integer */
RETURN (v_result);

/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);

END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;

EXEC: SELECT * FROM date_period('2016/01/31','2017/03/31');


问:
Unable to execute statement in php only when user selects yes in dialog box
Hi am trying to insert data into mysql only when user enters yes in confirm dialog but the data always inserted into mysql even if the user enters no.Here is my code..</p>

```<code><?php if (mysqli_num_rows($data_query) >= 1) { ?>
    <script>
        var txt;
        var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it')
        if (r == true) {
            <?php
                $query="INSERT INTO video_data(date) " ;
                $query .= "VALUES('{$date}')";
                $create_video_query=mysqli_query($connection,$query);

                if (!$create_video_query) {
                    die("failed".mysqli_error());
                } else {
                    $success = "Video added succesfully";
                }
            ?>
        }
    </script>
<?php } ?>
</code>```

答:
You can not mix server-side (PHP) and client-side (JavaScript) together to interact in real time together. You have to use AJAX or you have to submit a form (either one built in the html or built by javascript). Here is just a basic example:</p>

```<code><?php
# Checks to see if the form has been submitted
if(isset($_POST['add'])) {
    $query="INSERT INTO video_data(date) " ;
    $query .= "VALUES('{$date}')";
    $create_video_query=mysqli_query($connection,$query);
    if(!$create_video_query) {
        die("failed".mysqli_error());
    }
    else {
        $success = "Video added succesfully";
    }
}
?>

<?php
# I don't know what this is based on (the query) so I don't know if it's required.
# I just left it
if(mysqli_num_rows($data_query) >= 1) { ?>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
if(r !== false){
    // Assumes there is a form to submit and submits it
    form.submit();
}
</script>
<?php  } ?>
</code>```

Body:
Hi am trying to insert data into mysql only when user enters yes in confirm dialog but the data always inserted into mysql even if the user enters no.Here is my code..

<?php if (mysqli_num_rows($data_query) >= 1) { ?>

<?php } ?>

Body:
You can not mix server-side (PHP) and client-side (JavaScript) together to interact in real time together. You have to use AJAX or you have to submit a form (either one built in the html or built by javascript). Here is just a basic example:

<?php
# Checks to see if the form has been submitted
if(isset($_POST['add'])) {
    $query="INSERT INTO video_data(date) " ;
    $query .= "VALUES('{$date}')";
    $create_video_query=mysqli_query($connection,$query);
    if(!$create_video_query) {
        die("failed".mysqli_error());
    }
    else {
        $success = "Video added succesfully";
    }
}
?>

<?php
# I don't know what this is based on (the query) so I don't know if it's required.
# I just left it
if(mysqli_num_rows($data_query) >= 1) { ?>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
if(r !== false){
    // Assumes there is a form to submit and submits it
    form.submit();
}
</script>
<?php  } ?>


问:
converting Document objects in MongoDB 3 to POJOS
I'm saving an object with a java.util.Date field into a MongoDB 3.2 instance.

```<code>ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(myObject);
collection.insertOne(Document.parse(json));
</code>```

the String contains:

```<code>"captured": 1454549266735
</code>```

then I read it from the MongoDB instance:

```<code>    final Document document = collection.find(eq("key", value)).first();
    final String json = document.toJson();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    xx = mapper.readValue(json, MyClass.class);
</code>```

the deserialization fails:

java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException:
  Can not deserialize instance of java.util.Date out of START_OBJECT token

I see that the json string created by "document.toJson()" contains:

```<code>"captured": {
    "$numberLong": "1454550216318"
}
</code>```

instead of what was there originally ("captured": 1454549266735)
MongoDB docs say they started using "MongoDB Extended Json". I tried both Jackson 1 and 2 to parse it - no luck.

what is the easiest way to convert those Document objects provided by MongoDB 3 to Java POJOs? maybe I can skip toJson() step altogether?

I tried mongojack - that one does not support MongoDB3.

Looked at couple other POJO mappers listed on MongoDB docs page - they all require putting their custom annotations to Java classes.

答:
It looks like you are using Date object inside "myObject". In that case, you should use a DateSerializer that implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> and then register it with GsonBuilder. Sample code follows:

```<code>public class My_DateSerializer implements JsonSerializer<LocalDate>,
                                                          JsonDeserializer<LocalDate> {

@Override
public LocalDate deserialize(JsonElement json, Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
    final String dateAsString = json.getAsString();
    final DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_FORMAT);
    if (dateAsString.length() == 0)
    {
        return null;
    }
    else
    {
        return dtf.parseLocalDate(dateAsString);
    }
}

@Override
public JsonElement serialize(LocalDate src, Type typeOfSrc,
                                                     JsonSerializationContext context) {
    String retVal;
    final DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_FORMAT);
    if (src == null)
    {
        retVal = "";
    }
    else
    {
        retVal = dtf.print(src);
    }
    return new JsonPrimitive(retVal);
}
}
</code>```

Now register it with GsonBuilder:

```<code>final GsonBuilder builder = new GsonBuilder()
           .registerTypeAdapter(LocalDate.class, new My_DateSerializer());
final Gson gson = builder.create();
</code>```

Body:
I'm saving an object with a java.util.Date field into a MongoDB 3.2 instance.

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(myObject);
collection.insertOne(Document.parse(json));

the String contains:

"captured": 1454549266735

then I read it from the MongoDB instance:

    final Document document = collection.find(eq("key", value)).first();
    final String json = document.toJson();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    xx = mapper.readValue(json, MyClass.class);

the deserialization fails:

java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException:
  Can not deserialize instance of java.util.Date out of START_OBJECT token

I see that the json string created by "document.toJson()" contains:

"captured": {
    "$numberLong": "1454550216318"
}

instead of what was there originally ("captured": 1454549266735)
MongoDB docs say they started using "MongoDB Extended Json". I tried both Jackson 1 and 2 to parse it - no luck.

what is the easiest way to convert those Document objects provided by MongoDB 3 to Java POJOs? maybe I can skip toJson() step altogether?

I tried mongojack - that one does not support MongoDB3.

Looked at couple other POJO mappers listed on MongoDB docs page - they all require putting their custom annotations to Java classes.

Body:
It looks like you are using Date object inside "myObject". In that case, you should use a DateSerializer that implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> and then register it with GsonBuilder. Sample code follows:

public class My_DateSerializer implements JsonSerializer<LocalDate>,
                                                          JsonDeserializer<LocalDate> {

@Override
public LocalDate deserialize(JsonElement json, Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
    final String dateAsString = json.getAsString();
    final DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_FORMAT);
    if (dateAsString.length() == 0)
    {
        return null;
    }
    else
    {
        return dtf.parseLocalDate(dateAsString);
    }
}

@Override
public JsonElement serialize(LocalDate src, Type typeOfSrc,
                                                     JsonSerializationContext context) {
    String retVal;
    final DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_FORMAT);
    if (src == null)
    {
        retVal = "";
    }
    else
    {
        retVal = dtf.print(src);
    }
    return new JsonPrimitive(retVal);
}
}

Now register it with GsonBuilder:

final GsonBuilder builder = new GsonBuilder()
           .registerTypeAdapter(LocalDate.class, new My_DateSerializer());
final Gson gson = builder.create();


问:
Is this a naming convention or a function declaration
I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

```<code>var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}
</code>```

does test1 is a part of stringFunction or just a naming convention.Thanks in advance

答:
function instances are sort of "weird" in Javascript as they are objects but their typeof is "function" and not "object".

They can however have properties added and accessed using either the syntax f.x or f["x"]. Your code simply adds a property to a function object (the value of the property is also a function, but that is irrelevant).

Body:
I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}

does test1 is a part of stringFunction or just a naming convention.Thanks in advance


问:
scp or sftp copy multiple files with single command
I'd like to copy files from/to remote server in different directories.
For example, I want to run these 4 commands at once.

```<code>scp remote:A/1.txt local:A/1.txt
scp remote:A/2.txt local:A/2.txt
scp remote:B/1.txt local:B/1.txt
scp remote:C/1.txt local:C/1.txt
</code>```

What is the easiest way to do that?

答:
Problem: Copying multiple directories from remote server to local machine using a single SCP command and retaining each directory as it is in the remote server.

Solution: SCP can do this easily. This solves the annoying problem of entering password multiple times when using SCP with multiple folders. Consequently, this also saves a lot of time!

e.g.

```<code># copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command

~$ cd ~/working/directory
~$ scp -r username@contact.server.de:/work/datasets/images/test/\{t1,t2,t3\}  .
</code>```

PS: Motivated by this great answer: scp or sftp copy multiple files with single command

Based on the comments, this also works fine in Git Bash on Windows

Body:
I'd like to copy files from/to remote server in different directories.
For example, I want to run these 4 commands at once.

scp remote:A/1.txt local:A/1.txt
scp remote:A/2.txt local:A/2.txt
scp remote:B/1.txt local:B/1.txt
scp remote:C/1.txt local:C/1.txt

What is the easiest way to do that?

Body:
Problem: Copying multiple directories from remote server to local machine using a single SCP command and retaining each directory as it is in the remote server.

Solution: SCP can do this easily. This solves the annoying problem of entering password multiple times when using SCP with multiple folders. Consequently, this also saves a lot of time!

e.g.

# copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command

~$ cd ~/working/directory
~$ scp -r username@contact.server.de:/work/datasets/images/test/\{t1,t2,t3\}  .

PS: Motivated by this great answer: scp or sftp copy multiple files with single command

Based on the comments, this also works fine in Git Bash on Windows

ContentLicense: CC BY-SA 4.0


问:
document.queryCommandValue returns (empty string) in Firefox
I want to read if a certain text in a contenteditable element is bold or not. In Chrome document.queryCommandValue("bold") returns "true"/"false" as a string, IE returns a true/false as a boolean, but Firefox returns (empty string) in the developer console.

I made a fiddle as an example:
http://jsfiddle.net/nTQd2/

If you write som text in the div, mark it and then hit "Bold" the span should show "true"/"false" or true/false. I don't really care if its as a string or a boolean as I can convert it later.

答:
That's simple.

```<code>Document.queryCommandValue()
</code>```

returns a string. Instead of that use this.

```<code>Document.queryCommandState('Bold')
</code>```

This will return a boolean value as true/false.

Example:

```<code>function isSelectedTextBold()
{
    var isBold = document.queryCommandState("Bold");
    return isBold;
}
</code>```

I am also specifying function calls for other formatting options.

Italic -> document.queryCommandState("Italic");

Underline -> document.queryCommandState("Underline");

Left Justify -> document.queryCommandState("justifyLeft");

Center Justify -> document.queryCommandState("justifyCenter");

Right Justify -> document.queryCommandState("justifyRight");

I hope this helps. :)

Body:
That's simple.

Document.queryCommandValue()

returns a string. Instead of that use this.

Document.queryCommandState('Bold')

This will return a boolean value as true/false.

Example:

function isSelectedTextBold()
{
    var isBold = document.queryCommandState("Bold");
    return isBold;
}

I am also specifying function calls for other formatting options.

Italic -> document.queryCommandState("Italic");

Underline -> document.queryCommandState("Underline");

Left Justify -> document.queryCommandState("justifyLeft");

Center Justify -> document.queryCommandState("justifyCenter");

Right Justify -> document.queryCommandState("justifyRight");

I hope this helps. :)


问:
just 1st record is not displaying is drowpdown. but other is displaying . code igniter
[add_library form ]

```<code><select   name="employee_id" class="form-control">
                                <option  value="">Select Employee.....</option
                                <?php
                                if (!empty($employee_info) && is_array($employee_info)){
                                    foreach ($employee_info as $emp_info) {
                                        // blow option of compare db id and  select option value ?>
                                        <option  <?php echo ($emp_info->employee_id==$library_info->employee_id  ) ? 'selected' : ''; ?>

                                        value="<?php echo $emp_info->employee_id; ?>">
                                        <?php echo $emp_info->first_name . ' ' . $emp_info->last_name ?>
                                    </option>
                                    <?php
                                    }
                                }
                                ?>
                            </select>
</code>```

here is screen shot of front end. Am new in developing. thanks for help in advance . this is the pic of front end

答:
I'm not entirely sure how you have this set up, because I wouldn't do it this way. But try this:

```<code><select name="employee_id" class="form_control">
    <option value="">Select Employee...</option>
    <?php
    if (!empty($employee_info)) { // Left out the is_array. You can check one or the other. empty only checks arrays. Can include it to be thorough
        foreach ($employee_info AS $ei) {
            echo '<option value="' . $ei->employee_id . '"';
            echo ($ei->employee_id == $library_info->employee_id) ? ' SELECTED ' : '' . '>';
            echo $ei->first_name . ' ' . $ei->last_name;
            echo '</option>'.PHP_EOL;
        }
    }
    ?>
</select>
</code>```

It may take a little tweaking.

Body:
[add_library form ]

<select   name="employee_id" class="form-control">
                                <option  value="">Select Employee.....</option
                                <?php
                                if (!empty($employee_info) && is_array($employee_info)){
                                    foreach ($employee_info as $emp_info) {
                                        // blow option of compare db id and  select option value ?>
                                        <option  <?php echo ($emp_info->employee_id==$library_info->employee_id  ) ? 'selected' : ''; ?>

                                        value="<?php echo $emp_info->employee_id; ?>">
                                        <?php echo $emp_info->first_name . ' ' . $emp_info->last_name ?>
                                    </option>
                                    <?php
                                    }
                                }
                                ?>
                            </select>

here is screen shot of front end. Am new in developing. thanks for help in advance . this is the pic of front end

Body:
I'm not entirely sure how you have this set up, because I wouldn't do it this way. But try this:

<select name="employee_id" class="form_control">
    <option value="">Select Employee...</option>
    <?php
    if (!empty($employee_info)) { // Left out the is_array. You can check one or the other. empty only checks arrays. Can include it to be thorough
        foreach ($employee_info AS $ei) {
            echo '<option value="' . $ei->employee_id . '"';
            echo ($ei->employee_id == $library_info->employee_id) ? ' SELECTED ' : '' . '>';
            echo $ei->first_name . ' ' . $ei->last_name;
            echo '</option>'.PHP_EOL;
        }
    }
    ?>
</select>

It may take a little tweaking.


问:
Update two ID's at once SQL - PHP
I have a table that's PK is an int field.
My problem is I need to swap two of the values round.

This is my current code:

```<code>$newId = (int)$id; $newId = $newId - 1;

$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());
</code>```

The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.

答:
The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.

If that's the case, then your application/database is poorly architect-ed, and you need to re-think your database design before you go any further.

Primary keys should be immutable, i.e.: they should never change. What you're talking about doing is changing primary keys.

Fix your application/database, and you won't have this problem. Are you sure you shouldn't just be adding a new field 'sort_order' and ORDER BY sort_order instead or ordering by the ID field?

Title: Update two ID's at once SQL - PHP

Body:
I have a table that's PK is an int field.
My problem is I need to swap two of the values round.

This is my current code:

$newId = (int)$id; $newId = $newId - 1;

$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());

The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.


问:
Selenium WebDriver NoSuchElementException for a checkbox
The thing is my test works great when i run it(by the way, its based on IE8), but when its run from Bamboo, it doesn't find an element, even though its not hidden and it is there on the page.
I use this to get the elements:

```<code>public WebElement getElementWhenVisible(By locator, int timeout) {
        WebElement element = null;
        WebDriverWait wait = new WebDriverWait(driver, timeout);
        log.info("Getting element with locator {}", locator);
        element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
        return element;
    }
</code>```

My element is just a simple checkbox in a table. Every time in normal conditions it finds it, but for a strange reason on the Bamboo it doesnt find it
The windows is XP and driver version 2.37, .I  think

 My question is, is there a way I can force retrieve the element or tell the webdriver to refresh the table that contains the element?

答:
This may help you:</p>

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));
</code>```

Body:
The thing is my test works great when i run it(by the way, its based on IE8), but when its run from Bamboo, it doesn't find an element, even though its not hidden and it is there on the page.
I use this to get the elements:

public WebElement getElementWhenVisible(By locator, int timeout) {
        WebElement element = null;
        WebDriverWait wait = new WebDriverWait(driver, timeout);
        log.info("Getting element with locator {}", locator);
        element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
        return element;
    }

My element is just a simple checkbox in a table. Every time in normal conditions it finds it, but for a strange reason on the Bamboo it doesnt find it
The windows is XP and driver version 2.37, .I  think

 My question is, is there a way I can force retrieve the element or tell the webdriver to refresh the table that contains the element?

Body:
This may help you:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));


问:
Change all elements in Numpy array that end up as individual arrays to floats Python
I have an array in which all of the elements in the array are also arrays:

```<code>a = [[array([ 4.15167139]) array([ 2.80260218]) array([ 3.34189103])
  array([ 3.73434426]) array([ 3.76504973]) array([ 3.91946708])
  array([ 2.850741]) array([ 1.9985034]) array([ 4.05191836])
  array([ 3.46145848]) array([ 2.99489689]) array([ 2.60462582])
  array([ 1.91031189]) array([ 2.90006744]) array([ 3.69799451])
  array([ 3.83314665]) array([ 4.42917628]) array([ 5.17647658])
  array([ 4.63462677]) array([ 4.69085313]) array([ 4.84746095])
  array([ 5.04396694]) array([ 5.10152712]) array([ 3.33442499])
  array([ 4.87380637]) ...]]
</code>```

I want this to be the same shape array that it is now (20,96) but instead of all of the elements within this array being arrays I would just like them to be floats:

```<code> a = [[ 4.15167139  2.80260218  3.34189103...4.87380637 ...]]
</code>```

What is the best way to iterate over this array and change all of the elements from individual arrays to floats?

答:
It may be that np.concatenate is more reliable as said in hpaulj's answer, but in the current case np.array makes for a simpler solution, as it retains the dimensions. Applying it directly at the current array, will add a third dimension, however. This can be removed by slicing as:

```<code>b = np.array(a)[:,:,0]
</code>```

It does not have to be more complicated than that.

Body:
I have an array in which all of the elements in the array are also arrays:

a = [[array([ 4.15167139]) array([ 2.80260218]) array([ 3.34189103])
  array([ 3.73434426]) array([ 3.76504973]) array([ 3.91946708])
  array([ 2.850741]) array([ 1.9985034]) array([ 4.05191836])
  array([ 3.46145848]) array([ 2.99489689]) array([ 2.60462582])
  array([ 1.91031189]) array([ 2.90006744]) array([ 3.69799451])
  array([ 3.83314665]) array([ 4.42917628]) array([ 5.17647658])
  array([ 4.63462677]) array([ 4.69085313]) array([ 4.84746095])
  array([ 5.04396694]) array([ 5.10152712]) array([ 3.33442499])
  array([ 4.87380637]) ...]]

I want this to be the same shape array that it is now (20,96) but instead of all of the elements within this array being arrays I would just like them to be floats:

 a = [[ 4.15167139  2.80260218  3.34189103...4.87380637 ...]]

What is the best way to iterate over this array and change all of the elements from individual arrays to floats?

Body:
It may be that np.concatenate is more reliable as said in hpaulj's answer, but in the current case np.array makes for a simpler solution, as it retains the dimensions. Applying it directly at the current array, will add a third dimension, however. This can be removed by slicing as:

b = np.array(a)[:,:,0]

It does not have to be more complicated than that.


问:
Finding what branch a Git commit came from
Is there a way to find out what branch a commit comes from given its SHA-1 hash value?

Bonus points if you can tell me how to accomplish this using Ruby Grit.

答:
To find the local branch:

```<code>grep -lR YOUR_COMMIT .git/refs/heads | sed 's/.git\/refs\/heads\///g'
</code>```

To find the remote branch:

```<code>grep -lR $commit .git/refs/remotes | sed 's/.git\/refs\/remotes\///g'
</code>```

Body:
To find the local branch:

grep -lR YOUR_COMMIT .git/refs/heads | sed 's/.git\/refs\/heads\///g'

To find the remote branch:

grep -lR $commit .git/refs/remotes | sed 's/.git\/refs\/remotes\///g'


问:
Mongo how to join two collection and add condition on second collection
I have two collections
users{id, name} and files{id, userId, name} I want to find all the files whose file name "abc.xyz", I tried to write a code using $lookup but getting all the files belong to user and not filtering it by name  "abc.xyz", I have written following query.

```<code>db.user.aggregate([
{"$lookup":
    {
        "from": "files",
        "localField": "id",
        "foreignField": "userId",
        "as": "fileList"
    }
},
{"$project": { "filList":{
    "$filter": {
                    "input":"$fileList",
                    "as":"file"
                    "cond": {"$eq": ["$file.name","abc.xyz"]}
           }
             }
         }
}
])
</code>```

Thank you

答:
I want to find all the files whose file name "abc.xyz" … but getting all the files belong to user and not filtering it by name "abc.xyz"

Based on your question above, it could also be interpreted as "Find all files with name abc.xyz along with its owner information".

In which case, it would be better to filter the files collection first using $match to filter file name equal to abc.xyz. This would limit the number of documents to look-up into users collection, instead of perfoming lookup for both collections then perform filtering.

For example:

```<code>db.files.aggregate([
    {"$match": {"name":"abc.xyz"}},
    {"$lookup": {
                "from": "users",
                "localField": "userId",
                "foreignField": "_id",
                "as": "users"
                 }
     }]);
</code>```

Please note that the collection is now reversed, from files looking up into users. An example result would be:

```<code>  "result": [
    {
      "_id": 111,
      "userId": 999,
      "name": "abc.xyz",
      "owner": [
        {
          "_id": 999,
          "name": "xmejx"
        }
      ]
    },
    {
      "_id": 222,
      "userId": 998,
      "name": "abc.xyz",
      "owner": [
        {
          "_id": 998,
          "name": "kalwb"
        }
      ]
    }
  ]
</code>```

I would also recommend to check out:

Data Model Examples with Patterns

Aggregation Pipeline Optimisation

Body:
I have two collections
users{id, name} and files{id, userId, name} I want to find all the files whose file name "abc.xyz", I tried to write a code using $lookup but getting all the files belong to user and not filtering it by name  "abc.xyz", I have written following query.

db.user.aggregate([
{"$lookup":
    {
        "from": "files",
        "localField": "id",
        "foreignField": "userId",
        "as": "fileList"
    }
},
{"$project": { "filList":{
    "$filter": {
                    "input":"$fileList",
                    "as":"file"
                    "cond": {"$eq": ["$file.name","abc.xyz"]}
           }
             }
         }
}
])

Thank you

Body:
I want to find all the files whose file name "abc.xyz" … but getting all the files belong to user and not filtering it by name "abc.xyz"

Based on your question above, it could also be interpreted as "Find all files with name abc.xyz along with its owner information".

In which case, it would be better to filter the files collection first using $match to filter file name equal to abc.xyz. This would limit the number of documents to look-up into users collection, instead of perfoming lookup for both collections then perform filtering.

For example:

db.files.aggregate([
    {"$match": {"name":"abc.xyz"}},
    {"$lookup": {
                "from": "users",
                "localField": "userId",
                "foreignField": "_id",
                "as": "users"
                 }
     }]);

Please note that the collection is now reversed, from files looking up into users. An example result would be:

  "result": [
    {
      "_id": 111,
      "userId": 999,
      "name": "abc.xyz",
      "owner": [
        {
          "_id": 999,
          "name": "xmejx"
        }
      ]
    },
    {
      "_id": 222,
      "userId": 998,
      "name": "abc.xyz",
      "owner": [
        {
          "_id": 998,
          "name": "kalwb"
        }
      ]
    }
  ]

I would also recommend to check out:

Data Model Examples with Patterns

Aggregation Pipeline Optimisation


问:
Eval within if statement
How can I dynamically pass eq or ne inside perl if statement? I tried below but is not working:</p>

```<code>my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}
</code>```

答:
```<code>if (($cond eq 'eq') xor ($this ne $that)) {
     print $cond;
};
</code>```

<p>But maybe a better and more general approach would be to use perl's functional capabilities and create a hash table of functions: </p>

```<code>my %compare = (
     eq => sub {shift eq shift},
     ne => sub {shift ne shift},
     lt => sub {shift lt shift},
     like => sub {$_[0] =~ /$_[1]/},
     # ....
);

#...
if ($compare{$cond}->($this, $that)) {
     print $cond;
};
</code>```

Title: Eval within if statement

Body:
How can I dynamically pass eq or ne inside perl if statement? I tried below but is not working:

my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}

Body:
if (($cond eq 'eq') xor ($this ne $that)) {
     print $cond;
};

But maybe a better and more general approach would be to use perl's functional capabilities and create a hash table of functions:

my %compare = (
     eq => sub {shift eq shift},
     ne => sub {shift ne shift},
     lt => sub {shift lt shift},
     like => sub {$_[0] =~ /$_[1]/},
     # ....
);

#...
if ($compare{$cond}->($this, $that)) {
     print $cond;
};


问:
Asp.net MVC and AngularJS Boilerplate framework
We are looking to upgrade our current product. The current product is built using web forms (asp.net), c# and Sql server. The current product does not follow much of the best practices such as IOC, Unit of work, Repository pattern etc, however it does follow three layered architecture.

We would like to build the new product from scratch using best practices so that product can be scaled up when required. Our product needs to be a multi tennant web application which should be mobile friendly if viewed on a mobile device. We have found aspnet zero boiler plate which follows best practices but it seems a wee bit limited for us. The disappointment for us is the effort it requires to just add one new field as we would need to add it into multiple places and then recompile the product and publish it. Our product also rely on multiple forms and each form can contain hundereds of fields and on top of that each of our customers may not use all fields in the same form so we need a mechanism to hide and display fields based on customer's credentials. The dynamic creation of forms is a must requirement for us. I have listed below the requirements that we need:

Must follow Industry standard best practices (IOC, Unit of work, Repository, logging etc)

Ability to create forms dynamically and to report on these fields.

Should not rely on compiling and publishing the product for adding additonal field.

Custom business rules for each customer

Adhoc web based reporting

Full auditing to record changed and new value for certain or all fields.

Fully scalable

Role/User based permissions

Is there a suitable framework for achieving above or do we need to build it ourselves?

答:
All the features you specified are included in AspNet Zero application framework. You can start a free demo to see the user interface. Check out the documentation. If you like it you can buy. There's 30 day money guarantee back.

https://aspnetzero.com/


问:
Json data bind div in angularjs
Please help. I am new at angularjs, I want to bind json data into div as list using angularjs

Sample Data

```<code>"[{"T_FORM_CODE":"T12040"},{"T_FORM_CODE":"T18025"},{"T_FORM_CODE":"Q12014"},{"T_FORM_CODE":"R12039"}]"
</code>```

答:
you can use ng-repeat.
you can see plunker

```<code> <div ng-repeat ="dr in data">
 {{dr.column}}
 </div>
</code>```

Plunker

Title: Json data bind div in angularjs

Body:
Please help. I am new at angularjs, I want to bind json data into div as list using angularjs

Sample Data

"[{"T_FORM_CODE":"T12040"},{"T_FORM_CODE":"T18025"},{"T_FORM_CODE":"Q12014"},{"T_FORM_CODE":"R12039"}]"

Body:
you can use ng-repeat.
you can see plunker

 <div ng-repeat ="dr in data">
 {{dr.column}}
 </div>

Plunker


问:
How can I specify network interface for redis replication?
I'm using Redis 3.2.0 and enabled replication. But I got result for "info replication" as follows:

master_link_status:down

Redis log shows:

Connecting to MASTER master_host:6379

MASTER <-> SLAVE sync started

...

Timeout connecting to the MASTER

Connecting to MASTER master_host:6379

...

Ping and telnet to port 6379 of master host from slave host is succeeded.

So, I thought redis process on slave host is trying to connect to master host via wrong network interface(slave host has multiple network interfaces).

Can I specify network interface which is used by redis replication?

答: When Redis connects to master host, client socket is binded to address which is specified by first argument of "bind" parameter.</p>


问:
Android Studio XML error "Corresponding method handler not found" on onClick
Why do I get error "Corresponding method handler not found" on the XML onClick line, after naming the onClick in XML and calling it on Main Activity?

Snippet from activity_main.xml:

```<code>        <Button
            android:id="@+id/buPercentage"
            android:layout_width="30pt"
            android:layout_height="30pt"
            android:layout_weight="1"
            android:background="@color/lightgray"
            android:onClick="buPercentageEvent" //Error says Corresponding method handler not found
            android:text="%"
            android:textSize="18sp" />
</code>```

Snippet from MainActivity.kt

```<code>fun buPercentageEvent()
{
    val convertToDecimal = displayText.text.toString()
    val newNumber = convertToDecimal.toDouble() / 100
    displayText.setText(newNumber.toString())
}
</code>```

答:
Do this

```<code>fun test(view: View){
        Log.e("Click","Yes")
    }
</code>```

This will work.

Body:
Why do I get error "Corresponding method handler not found" on the XML onClick line, after naming the onClick in XML and calling it on Main Activity?

Snippet from activity_main.xml:

        <Button
            android:id="@+id/buPercentage"
            android:layout_width="30pt"
            android:layout_height="30pt"
            android:layout_weight="1"
            android:background="@color/lightgray"
            android:onClick="buPercentageEvent" //Error says Corresponding method handler not found
            android:text="%"
            android:textSize="18sp" />

Snippet from MainActivity.kt

fun buPercentageEvent()
{
    val convertToDecimal = displayText.text.toString()
    val newNumber = convertToDecimal.toDouble() / 100
    displayText.setText(newNumber.toString())
}

Body:
Do this

fun test(view: View){
        Log.e("Click","Yes")
    }

This will work.


问:
Docker maven plugin ClientProtocolException (Windows 10 using Docker Toolbox)
I am trying to build a docker image using the docker-maven-plugin (provided by spotify: https://github.com/spotify/docker-maven-plugin) but things aren't really working out. At first I got this exception:

```<code>org.apache.http.conn.HttpHostConnectException: Connect to localhost:2375
</code>```

I found out that I had to create an env. variable to fix this (https://github.com/spotify/docker-maven-plugin/issues/135):

```<code>set DOCKER_HOST=set DOCKER_HOST=tcp://192.168.99.100:2376
</code>```

So after setting that env. variable I keep getting this ClientProtocolException:

```<code>[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:0.3.258:build (default-cli) on project docker_micro_maven: Exception caught: java.util.concurrent.ExecutionException: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException: The server failed to respond with a valid HTTP response
</code>```

I have no idea how I could fix this, any input would be greatly appreciated.

答:
docker-machine env default</p>

```<code>set DOCKER_HOST=tcp://192.168.99.100:2376
set DOCKER_MACHINE_NAME=default
set DOCKER_TLS_VERIFY=1
set DOCKER_TOOLBOX_INSTALL_PATH=C:\Program Files\Docker Toolbox
set DOCKER_CERT_PATH=C:\Users\panhl-a\.docker\machine\machines\default
</code>```

Body:
I am trying to build a docker image using the docker-maven-plugin (provided by spotify: https://github.com/spotify/docker-maven-plugin) but things aren't really working out. At first I got this exception:

org.apache.http.conn.HttpHostConnectException: Connect to localhost:2375

I found out that I had to create an env. variable to fix this (https://github.com/spotify/docker-maven-plugin/issues/135):

set DOCKER_HOST=set DOCKER_HOST=tcp://192.168.99.100:2376

So after setting that env. variable I keep getting this ClientProtocolException:

[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:0.3.258:build (default-cli) on project docker_micro_maven: Exception caught: java.util.concurrent.ExecutionException: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: org.apache.http.client.ClientProtocolException: The server failed to respond with a valid HTTP response

I have no idea how I could fix this, any input would be greatly appreciated.

Body:
docker-machine env default

set DOCKER_HOST=tcp://192.168.99.100:2376
set DOCKER_MACHINE_NAME=default
set DOCKER_TLS_VERIFY=1
set DOCKER_TOOLBOX_INSTALL_PATH=C:\Program Files\Docker Toolbox
set DOCKER_CERT_PATH=C:\Users\panhl-a\.docker\machine\machines\default


问:
How to remove a part of all strings in an array in javascript?
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.

答:
So here is the way without using any regex by only using string and array methods.

const gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001', 'XYZAB.PORSCHE.YSA.2021']

for (let i = 0; i < gUser.length; i++) {
  console.log('Required String: ', gUser[i].split('.').slice(1).join('.'));
}```

What we do is, we split the string into parts where . is encountered.

gUser[0].split('.') returns ['CAR', 'BENZ', 'CCLASS', '1962']

Later when slice(1) is called, the zeroth element of array is chopped off and will return ['BENZ', 'CCLASS', '1962']

And finally using join('.'), we merge the array elements to a single string with a . between each element, which returns BENZ.CCLASS.1962

Hope this helps! :)

Body:
So here is the way without using any regex by only using string and array methods.

const gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001', 'XYZAB.PORSCHE.YSA.2021']

for (let i = 0; i < gUser.length; i++) {
  console.log('Required String: ', gUser[i].split('.').slice(1).join('.'));
}

What we do is, we split the string into parts where . is encountered.

gUser[0].split('.') returns ['CAR', 'BENZ', 'CCLASS', '1962']

Later when slice(1) is called, the zeroth element of array is chopped off and will return ['BENZ', 'CCLASS', '1962']

And finally using join('.'), we merge the array elements to a single string with a . between each element, which returns BENZ.CCLASS.1962

Hope this helps! :)


问:
Websocket, Angular 2 and JSON Web token Authentication
My Angular 2 app (coded in typescript) has a simple authentication scheme:

User logs in:

Server returns JSON Web Token (JWT) abc123...

On every API call, the app sends the JWT in the Authorization header

Server validates the JWT and grants access

Now I'd like to add websockets. I'm wondering how to authenticate the user there. Since I don't control which headers are sent to the websocket server (WS), I cannot send the JWT.

My idea so far (not yet implemented):

Client opens websocket: let sock = new WebSocket('wss://example.com/channel/');

WS server accepts the handshake without any authentication check. Standard HTTP headers are available at this stage.

Client listens to the open event on the socket. Once the socket is open:

client sends a message with type='auth' payload='JWT_VALUE'

WS server expects 1st message on a socket to be of type auth. Once that is received, server reads the payload, validates JWT_VALUE and sets an isAuthenticated flag

If validation fails, server disconnects the socket

If a client without isAuthenticated sends any other type of message, server disconnects the socket

2 problems: server resources can be taken up by clients who connect but never send the JWT, and a cleaner solution would block the handshake if the client is not authenticated.

Other ideas:

Client could send JWT in the path: new WebSocket('wss://example.com/channel/<JWT>/')

pro: this info is available during the handshake

con: the path doesn't seem to be the "appropriate" place for a JWT. Specifically because intermediate proxies and access logs will save the path; When designing the HTTP API I already made the decision not to include the JWT in the url

Server could read the client's IP + UserAgent and match against a DB record that was created by the HTTP server when the JWT was issued. Server will then guess who is connecting

pro: this info may be available during the handshake (not sure about IP)

con: it seems horribly insecure to "guess" that a client should be associated with a JWT when the client never presented it in the first place. It would mean for instance that someone who spoofs the victim's UA and uses the same network (proxy, public wifi, university intranet...) will be able to impersonate the victim.

How do you authenticate clients on websockets? Assume the user already logged in via HTTP and that the Angular 2 app has a JWT token.

答:
Client opens the websocket, sending the UserName and Password in query param

```<code>ws://<username>:<password>@<ip-address><path>
</code>```

Example:  new $WebSocket('ws://user:123456@127.0.0.0/util')

Body:
Client opens the websocket, sending the UserName and Password in query param

ws://<username>:<password>@<ip-address><path>

Example:  new $WebSocket('ws://user:123456@127.0.0.0/util')


问:
Is this a naming convention or a function declaration
I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

```<code>var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}
</code>```

does test1 is a part of stringFunction or just a naming convention.Thanks in advance

答:
Here test1() is a property (function type) of the stringFunction var.

So you defined a function in a function object.

You can use it by invoking stringFunction.test1(); as you can invoke the outer function : stringFunction();

```<code>var stringFunction = function(){console.log("Test stringFunction")};

stringFunction.test1 = function(){
    console.log("Test 1");
}

stringFunction();
stringFunction.test1();
</code>```

OUTPUT :

Test stringFunction

Test 1

Body:
I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}

does test1 is a part of stringFunction or just a naming convention.Thanks in advance

Body:
Here test1() is a property (function type) of the stringFunction var.

So you defined a function in a function object.

You can use it by invoking stringFunction.test1(); as you can invoke the outer function : stringFunction();

var stringFunction = function(){console.log("Test stringFunction")};

stringFunction.test1 = function(){
    console.log("Test 1");
}

stringFunction();
stringFunction.test1();

OUTPUT :

Test stringFunction

Test 1


问:
Passing an additional parameter with an onChange event
What I'm trying to do:

I am trying to pass a string from a child component to the handleChange function of a parent component.

What currently works:

I have a parent React JS class with the following method:

```<code>handleChange(event) {

    console.log(event.target.value);
}
</code>```

In the render function I have the following:

```<code><Child handleChange={this.handleChange.bind(this)} />
</code>```

In the Child class I have:

```<code><fieldset onChange={this.props.handleChange}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
</code>```

This works fine.

What I am trying to do instead:

I am attempting to add a section parameter to the handleChange function as follows:

```<code>handleChange(section, event) {
    console.log(section);
    console.log(event.target.value);
}
</code>```

And in the Child class I have:

```<code><fieldset onChange={this.props.handleChange("tags")}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
</code>```

I now get the error:

```<code>Uncaught TypeError: Cannot read property 'target' of undefined
</code>```

This error is being thrown in my second console.log statement.

What am I doing wrong?

Also, I am considering making the section parameter optional. If so, is there an easy way to do this? It seems like it might not be possible if the event parameter needs to be last.

答:
As the OP, I had originally posted this as a follow up on my question, but it was deleted and I was told to post it as an answer instead, so here it is:

Based on Ritesh Bansal's answer, I have learned the following:

The following line was not working because when using parenthesis after the function name, the function is called immediately rather than waiting for a change to happen:

```<code><fieldset onChange={this.props.handleChange("tags")}>
</code>```

The above will not work, neither would a function such as this:

```<code><fieldset onChange={this.props.handleChange()}>
</code>```

The above would also get called immediately on first render.

There are two solutions to this:

The not-so good way:

```<code><fieldset onChange={this.props.handleChange.bind(this, "tags")}>
</code>```

The much better way:

```<code><fieldset onChange={(evt) => this.props.handleChange("tags", evt)}>
</code>```

The problem is now solved. Thank you everyone!

Update:

I also researched Shubham Khatri's suggestion to change the child element to this:

```<code><Child handleChange={(e,val) => this.handleChange(e, val)}/>
</code>```

I did not realize that using bind in the render function, that every time render is called it creates a new function instance. I can, therefore, either use Shubham Khatri's method, or bind the methods in the constructor.

Body:
What I'm trying to do:

I am trying to pass a string from a child component to the handleChange function of a parent component.

What currently works:

I have a parent React JS class with the following method:

handleChange(event) {

    console.log(event.target.value);
}

In the render function I have the following:

<Child handleChange={this.handleChange.bind(this)} />

In the Child class I have:

<fieldset onChange={this.props.handleChange}>

Tag 1: <input id="tag1" value={tags[0]} />

Tag 2: <input id="tag2" value={tags[1]} />

Tag 3: <input id="tag3" value={tags[2]} />

</fieldset>

This works fine.

What I am trying to do instead:

I am attempting to add a section parameter to the handleChange function as follows:

handleChange(section, event) {
    console.log(section);
    console.log(event.target.value);
}

And in the Child class I have:

<fieldset onChange={this.props.handleChange("tags")}>

Tag 1: <input id="tag1" value={tags[0]} />

Tag 2: <input id="tag2" value={tags[1]} />

Tag 3: <input id="tag3" value={tags[2]} />

</fieldset>

I now get the error:

Uncaught TypeError: Cannot read property 'target' of undefined

This error is being thrown in my second console.log statement.

What am I doing wrong?

Also, I am considering making the section parameter optional. If so, is there an easy way to do this? It seems like it might not be possible if the event parameter needs to be last.

Body:
As the OP, I had originally posted this as a follow up on my question, but it was deleted and I was told to post it as an answer instead, so here it is:

Based on Ritesh Bansal's answer, I have learned the following:

The following line was not working because when using parenthesis after the function name, the function is called immediately rather than waiting for a change to happen:

<fieldset onChange={this.props.handleChange("tags")}>

The above will not work, neither would a function such as this:

<fieldset onChange={this.props.handleChange()}>

The above would also get called immediately on first render.

There are two solutions to this:

The not-so good way:

<fieldset onChange={this.props.handleChange.bind(this, "tags")}>

The much better way:

<fieldset onChange={(evt) => this.props.handleChange("tags", evt)}>

The problem is now solved. Thank you everyone!

Update:

I also researched Shubham Khatri's suggestion to change the child element to this:

<Child handleChange={(e,val) => this.handleChange(e, val)}/>

I did not realize that using bind in the render function, that every time render is called it creates a new function instance. I can, therefore, either use Shubham Khatri's method, or bind the methods in the constructor.


问:
Error Having From using Inner Join Query while connecting 3 three tables
I m trying to join three tables while using the join queries but when execute the code I have a face a syntax error in the FROM clause. I have write the snippet please suggest what is the error in my code.</p>

```<code> SELECT u.UserID, t.UserName,u.email, d.debit,d.credit,d.hand_on_cash
  FROM userdetails u JOIN usertable t  JOIN userdata d
  WHERE u.UserID=t.UserID
   AND u.UserID=d.UserID
  ORDER BY u.UserID,t.UserID
</code>```

答:
You are mixing ON and don't need to use  WHERE

```<code>SELECT u.UserID, t.UserName,u.email, d.debit,d.credit,d.hand_on_cash
      FROM userdetails u JOIN usertable t ON u.UserID=t.UserID
      JOIN userdata d ON u.UserID=d.UserID
       --WHERE u.UserID=t.UserID
       --AND u.UserID=d.UserID
      ORDER BY u.UserID,t.UserID
</code>```

Body:
I m trying to join three tables while using the join queries but when execute the code I have a face a syntax error in the FROM clause. I have write the snippet please suggest what is the error in my code.

 SELECT u.UserID, t.UserName,u.email, d.debit,d.credit,d.hand_on_cash
  FROM userdetails u JOIN usertable t  JOIN userdata d
  WHERE u.UserID=t.UserID
   AND u.UserID=d.UserID
  ORDER BY u.UserID,t.UserID

Body:
You are mixing ON and don't need to use  WHERE

SELECT u.UserID, t.UserName,u.email, d.debit,d.credit,d.hand_on_cash
      FROM userdetails u JOIN usertable t ON u.UserID=t.UserID
      JOIN userdata d ON u.UserID=d.UserID
       --WHERE u.UserID=t.UserID
       --AND u.UserID=d.UserID
      ORDER BY u.UserID,t.UserID


问:
trigger alert on div's mouse out
Im testing out something here,so please excuse the css rules.I have got a ul list in a div,and im trying to trigger a alert on the mouseout of the div but the alert triggers each time i mouseout the li items in the ul. Could some please tell me the reason behind it? I guess its something to so with bubbling but im not sure.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<style>
#box{
cursor:pointer;width:300px;height:500px;background-color:#F1E0BB;
}

ul#myList{
list-style:none;padding-top:20px;
}

ul#myList li{
font-family:Arial;font-size:20px;font-weight:bold;height:40px;cursor:pointer;border:solid 1px #000;
}
</style>
</head>
<body>

<div id="box">
    <ul id="myList">
        <li>Item 11</li>
        <li>Item 12</li>
        <li>Item 13</li>
        <li>Item 14</li>
        <li>Item 15</li>
    </ul>
</div>

</body>
</html>
</code>```

Jquery script i used

```<code>$('#box').mouseout(function(){

alert("ccc");

})
</code>```

答:
Use the mouseleave event here instead, which doesn't fire when leaving children:

```<code>$('#box').mouseleave(function(){
  alert("ccc");
});
</code>```

You're assumption about bubbling is correct, it's those child elements bubbling up that's triggering your handler.  From the .mouseleave() docs:

The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

Title: trigger alert on div's mouse out

Body:
Im testing out something here,so please excuse the css rules.I have got a ul list in a div,and im trying to trigger a alert on the mouseout of the div but the alert triggers each time i mouseout the li items in the ul. Could some please tell me the reason behind it? I guess its something to so with bubbling but im not sure.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

Item 11

Item 12

Item 13

Item 14

Item 15

Jquery script i used

$('#box').mouseout(function(){

alert("ccc");

})

Body:
Use the mouseleave event here instead, which doesn't fire when leaving children:

$('#box').mouseleave(function(){
  alert("ccc");
});

You're assumption about bubbling is correct, it's those child elements bubbling up that's triggering your handler.  From the .mouseleave() docs:

The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.


问:
bind jsgrid from json data
I have a webservice which return data in json

```<code>[WebMethod]
    public string json_Getdata()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("id", typeof(string));
        dt.Columns.Add("name", typeof(string));
        dt.Columns.Add("Age", typeof(string));
        dt.Columns.Add("Country", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Phone", typeof(string));

        for (int i = 1; i < 6; i++)
        {
            DataRow dr = dt.NewRow();
            dr["id"] = i.ToString();
            dr["name"] = "Mr. xyz";
            dr["Age"] = (24 + i).ToString();
            dr["Country"] = "India";
            dr["Address"] = "H no- 456" + i;
            dr["Phone"] = "125896" + i;
            dt.Rows.Add(dr);
        }
        return JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
    }
</code>```

I want to fill this data into jsgrid , sample code is below from their website

```<code>    $(function() {

    $("#jsGrid").jsGrid({
        height: "90%",
        width: "100%",

        filtering: true,
        editing: true,
        sorting: true,
        paging: true,
        autoload: true,

        pageSize: 15,
        pageButtonCount: 5,

        deleteConfirm: "Do you really want to delete the client?",

        controller: db,

        fields: [
            { name: "Name", type: "text", width: 150 },
            { name: "Age", type: "number", width: 50 },
            { name: "Address", type: "text", width: 200 },
            { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" },
            { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
            { type: "control" }
        ]
    });

});
</code>```

after consuming the webservice

```<code><script type="text/javascript">
$(function () {
    $.ajax({
        type: "POST",
        url: "http://localhost:50015/WebService1.asmx/json_Getdata",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            debugger;
            alert(response.d);
        },
        error: function (response) {
            debugger;
            alert(response.d);
        }
    });
});

function OnSuccess(response) {
    var  records = response.d;
    debugger;
}
</code>```

I m getting data like below

```<code>[
{"id": "1","name": "Mr. xyz","Age": "25","Country": "India","Address": "H no- 4561","Phone": "1258961"},
{"id": "2","name": "Mr. xyz","Age": "26","Country": "India","Address": "H no- 4562","Phone": "1258962"},
{"id": "3","name": "Mr. xyz","Age": "27","Country": "India","Address": "H no- 4563","Phone": "1258963"},
{"id": "4","name": "Mr. xyz","Age": "28","Country": "India","Address": "H no- 4564","Phone": "1258964"},
{"id": "5","name": "Mr. xyz","Age": "29","Country": "India","Address": "H no- 4565","Phone": "1258965"}
]
</code>```

As per my understanding it is in array but i am not able to access data by index (like  records[0].name) - it always show undefined

Cabn someone tell me why is this happening

答:
```<code>$(function() {

    $("#jsGrid").jsGrid({
        height: "90%",
        width: "100%",

        filtering: true,
        editing: true,
        sorting: true,
        paging: true,
        autoload: true,

        pageSize: 15,
        pageButtonCount: 5,

        deleteConfirm: "Do you really want to delete the client?",
       controller: {
                loadData: function (filter) {
                    var d1 = $.Deferred();
                    $.ajax({
                       type: "POST",
                       url: "http://localhost:50015/WebService1.asmx/json_Getdata",
                       data: '{}',
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                    }).done(function (response) {
                        d1.resolve(jQuery.parseJSON(response.d));
                    });

                    return d1.promise();
                },
            },
        fields: [
            { name: "Name", type: "text", width: 150 },
            { name: "Age", type: "number", width: 50 },
            { name: "Address", type: "text", width: 200 },
            { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" },
            { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
            { type: "control" }
        ]
    });
});
</code>```

Please try this to get data from web method.

Title: bind jsgrid from json data

Body:
I have a webservice which return data in json

[WebMethod]
    public string json_Getdata()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("id", typeof(string));
        dt.Columns.Add("name", typeof(string));
        dt.Columns.Add("Age", typeof(string));
        dt.Columns.Add("Country", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Phone", typeof(string));

        for (int i = 1; i < 6; i++)
        {
            DataRow dr = dt.NewRow();
            dr["id"] = i.ToString();
            dr["name"] = "Mr. xyz";
            dr["Age"] = (24 + i).ToString();
            dr["Country"] = "India";
            dr["Address"] = "H no- 456" + i;
            dr["Phone"] = "125896" + i;
            dt.Rows.Add(dr);
        }
        return JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
    }

I want to fill this data into jsgrid , sample code is below from their website

    $(function() {

    $("#jsGrid").jsGrid({
        height: "90%",
        width: "100%",

        filtering: true,
        editing: true,
        sorting: true,
        paging: true,
        autoload: true,

        pageSize: 15,
        pageButtonCount: 5,

        deleteConfirm: "Do you really want to delete the client?",

        controller: db,

        fields: [
            { name: "Name", type: "text", width: 150 },
            { name: "Age", type: "number", width: 50 },
            { name: "Address", type: "text", width: 200 },
            { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" },
            { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
            { type: "control" }
        ]
    });

});

after consuming the webservice

Body:
$(function() {

    $("#jsGrid").jsGrid({
        height: "90%",
        width: "100%",

        filtering: true,
        editing: true,
        sorting: true,
        paging: true,
        autoload: true,

        pageSize: 15,
        pageButtonCount: 5,

        deleteConfirm: "Do you really want to delete the client?",
       controller: {
                loadData: function (filter) {
                    var d1 = $.Deferred();
                    $.ajax({
                       type: "POST",
                       url: "http://localhost:50015/WebService1.asmx/json_Getdata",
                       data: '{}',
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                    }).done(function (response) {
                        d1.resolve(jQuery.parseJSON(response.d));
                    });

                    return d1.promise();
                },
            },
        fields: [
            { name: "Name", type: "text", width: 150 },
            { name: "Age", type: "number", width: 50 },
            { name: "Address", type: "text", width: 200 },
            { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" },
            { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
            { type: "control" }
        ]
    });
});

Please try this to get data from web method.


问:
SQL Server - time stamp declaration
I have to create a table. I have 10-15 columns which need to be declared as time stamps in SQL Server, but I get an error that SQL will allow only one timestamp per table. Could you please let me know how do I declare all these 10-15 columns as time stamps in one table creation.

Rgds.,
Sajan.

答: Have you tried using DATETIME? As far as I know, perhaps SQL server doesn't have TIMESTAMP. If really needed, use VARCHAR to store the values, but that'd be a very cheap approach!</p>

Title: SQL Server - time stamp declaration


问:
combine two ranges (single cell and range) from multiple workbooks to worksheet
I got some script here to open up multiple workbooks with a worksheet and then copy it to a worksheet as a loop, but I need an additional cell (the date) from another worksheet in the multiple workbooks because the output I got cannot be changed and just added to the same sheet.

What I need is for this code to include a single cell range from another sheet on the workbook and then fill it to the bottom of the range per workbook.

I cant use UNION as it's not the same length, and I looked up merging ranges into one, but I get type mismatch errors.

VBA: How to combine two ranges on different sheets into one, to loop through I tried this but I can't figure out how to put it into my code.

Here is the code I have that works so far for just the one range. The rngdate copies over but does not leave a gap or autofill to the next loop, it just pastes under each other, so maybe this code will work but I'm missing something basic like autofill?

```<code>Dim vFileNames As Variant
Dim y As Long
Dim wbTemp As Workbook
Dim wbNew As Workbook
Dim blHeader As Boolean
Dim Rng As Range
Dim rngDate As Range

Application.ScreenUpdating = False
Set wbNew = Workbooks("master_timesheet") '.Add
blHeader = False
vFileNames = Application.GetOpenFilename(Title:="Select all workbooks to copy", _
MultiSelect:=True)
 'Will not be array if no file is selected
 'If user selects one or more files, files will be stored as an array
If Not IsArray(vFileNames) Then GoTo ConsolidateWB_End
For y = LBound(vFileNames) To UBound(vFileNames)
     'Open each wb selected
    Set wbTemp = Workbooks.Open(vFileNames(y))
    Set rngDate = wbTemp.Worksheets("Communications Unlimited Inc").Range("A5").CurrentRegion
    Set Rng = wbTemp.Worksheets("Export").Range("A1").CurrentRegion

     'If header row already copied, then offset by 1 to exclude header
    If blHeader Then
        Set Rng = Rng.Offset(1, 0).Resize(Rng.Rows.Count - 1)
         'If header row not already copied, keep rng as is and change blHeader to true
    Else
        blHeader = True
    End If
     'Paste to next row on new wb

    Rng.Copy Destination:=wbNew.Sheets(1).Range("A65536").End(xlUp).Offset(1, 0)
    rngDate.Copy Destination:=wbNew.Sheets(1).Range("P65536").End(xlUp).Offset(1, 0)

    wbTemp.Close SaveChanges:=False
Next y
    ConsolidateWB_End:
        Application.ScreenUpdating = True
End Sub
</code>```

答:
If I read your problem correctly you want the date, rngdate, pasted adjacent to each and every line of data you have just copied.   However your current code only puts the data on the first row.  Below is an adaptation of how I have solved this problem myself, taking account of your existing code.  (My guess is that there is a much more elegant solution than this which I'm just not aware.)

```<code>Dim pasterangefirstrow As Integer
</code>```

...

```<code>pasterangefirstrow = wbNew.Sheets(1).Range("D65536").End(xlUp).Offset(1, 0).Row
</code>```

...

```<code>With wbNewSheets(1)
    Rng.Copy Destination:=.Range("D65536").End(xlUp).Offset(1, 0)
    rngdate.Copy Destination:=.Range("P" & pasterangefirstrow & ":P" & pasterangefirstrow + Rng.Rows.Count - 1)
End With
</code>```

Body:
I got some script here to open up multiple workbooks with a worksheet and then copy it to a worksheet as a loop, but I need an additional cell (the date) from another worksheet in the multiple workbooks because the output I got cannot be changed and just added to the same sheet.

What I need is for this code to include a single cell range from another sheet on the workbook and then fill it to the bottom of the range per workbook.

I cant use UNION as it's not the same length, and I looked up merging ranges into one, but I get type mismatch errors.

VBA: How to combine two ranges on different sheets into one, to loop through I tried this but I can't figure out how to put it into my code.

Here is the code I have that works so far for just the one range. The rngdate copies over but does not leave a gap or autofill to the next loop, it just pastes under each other, so maybe this code will work but I'm missing something basic like autofill?

Dim vFileNames As Variant
Dim y As Long
Dim wbTemp As Workbook
Dim wbNew As Workbook
Dim blHeader As Boolean
Dim Rng As Range
Dim rngDate As Range

Application.ScreenUpdating = False
Set wbNew = Workbooks("master_timesheet") '.Add
blHeader = False
vFileNames = Application.GetOpenFilename(Title:="Select all workbooks to copy", _
MultiSelect:=True)
 'Will not be array if no file is selected
 'If user selects one or more files, files will be stored as an array
If Not IsArray(vFileNames) Then GoTo ConsolidateWB_End
For y = LBound(vFileNames) To UBound(vFileNames)
     'Open each wb selected
    Set wbTemp = Workbooks.Open(vFileNames(y))
    Set rngDate = wbTemp.Worksheets("Communications Unlimited Inc").Range("A5").CurrentRegion
    Set Rng = wbTemp.Worksheets("Export").Range("A1").CurrentRegion

     'If header row already copied, then offset by 1 to exclude header
    If blHeader Then
        Set Rng = Rng.Offset(1, 0).Resize(Rng.Rows.Count - 1)
         'If header row not already copied, keep rng as is and change blHeader to true
    Else
        blHeader = True
    End If
     'Paste to next row on new wb

    Rng.Copy Destination:=wbNew.Sheets(1).Range("A65536").End(xlUp).Offset(1, 0)
    rngDate.Copy Destination:=wbNew.Sheets(1).Range("P65536").End(xlUp).Offset(1, 0)

    wbTemp.Close SaveChanges:=False
Next y
    ConsolidateWB_End:
        Application.ScreenUpdating = True
End Sub

Body:
If I read your problem correctly you want the date, rngdate, pasted adjacent to each and every line of data you have just copied.   However your current code only puts the data on the first row.  Below is an adaptation of how I have solved this problem myself, taking account of your existing code.  (My guess is that there is a much more elegant solution than this which I'm just not aware.)

Dim pasterangefirstrow As Integer

...

pasterangefirstrow = wbNew.Sheets(1).Range("D65536").End(xlUp).Offset(1, 0).Row

...

With wbNewSheets(1)
    Rng.Copy Destination:=.Range("D65536").End(xlUp).Offset(1, 0)
    rngdate.Copy Destination:=.Range("P" & pasterangefirstrow & ":P" & pasterangefirstrow + Rng.Rows.Count - 1)
End With