答:
The SQL below using the xml path trick to fold the Id's into a list, grouped by quarter.

```<code>select
stuff(
 (select concat(',',tid.ID)
  from PeriodTable tid
  where datepart(quarter,tid.Startdate) = datepart(quarter,t.Startdate)
    and datepart(year,tid.Startdate) = datepart(year,t.Startdate)
  for xml path(''), type).value('.', 'varchar(max)')
 ,1,1,'') IdList,
min(StartDate) as FirstStartDate, max(EndDate) as LastEndDate
from PeriodTable t
group by datepart(year,Startdate), datepart(quarter,Startdate)
order by FirstStartDate;
</code>```

Or this variation of the method that uses a CROSS APPLY:

```<code>select
stuff(max(Ids),1,1,'') as IdList, min(StartDate) as FirstStartDate, max(EndDate) as LastEndDate
from PeriodTable t
cross apply (
   select concat(',',tid.ID)
   from PeriodTable tid
   where datepart(quarter,tid.Startdate) = datepart(quarter,t.Startdate)
     and datepart(year,tid.Startdate) = datepart(year,t.Startdate)
   for xml path('')) List(Ids)
group by datepart(year,Startdate), datepart(quarter,Startdate)
order by FirstStartDate;
</code>```

Try it here on rextester

Title: SQL query to return quarterly dates from list of dates

Body:
Can someone help me with the SQL query? I have a table with has data like this

Periodtable:

ID
StartDate
EndDate

The data will look like this:

1 1/3/2017 2/2/2017
2 2/3/2017 3/2/2017
3 3/3/2017 4/2/207
4 4/3/2017 5/2/2017
5 5/3/2017 6/2/2017
6 6/3/2017 7/2/2017
7 7/3/2017 8/2/2017
8 8/3/2017 9/2/2017
9 9/3/2017 10/2/2017

...

I want to write a SQL query which returns the following 3 columns:

9,8,7 | 7/3/2017 | 10/2/2017
6,5,4 | 4/3/2017 | 7/2/2017
3,2,1 | 1/3/2017 | 4/2/2017

Body:
The SQL below using the xml path trick to fold the Id's into a list, grouped by quarter.

select
stuff(
 (select concat(',',tid.ID)
  from PeriodTable tid
  where datepart(quarter,tid.Startdate) = datepart(quarter,t.Startdate)
    and datepart(year,tid.Startdate) = datepart(year,t.Startdate)
  for xml path(''), type).value('.', 'varchar(max)')
 ,1,1,'') IdList,
min(StartDate) as FirstStartDate, max(EndDate) as LastEndDate
from PeriodTable t
group by datepart(year,Startdate), datepart(quarter,Startdate)
order by FirstStartDate;

Or this variation of the method that uses a CROSS APPLY:

select
stuff(max(Ids),1,1,'') as IdList, min(StartDate) as FirstStartDate, max(EndDate) as LastEndDate
from PeriodTable t
cross apply (
   select concat(',',tid.ID)
   from PeriodTable tid
   where datepart(quarter,tid.Startdate) = datepart(quarter,t.Startdate)
     and datepart(year,tid.Startdate) = datepart(year,t.Startdate)
   for xml path('')) List(Ids)
group by datepart(year,Startdate), datepart(quarter,Startdate)
order by FirstStartDate;

Try it here on rextester


来源: stackexchange

问:
Using _beginthreadex/_endthreadex functions
I checked the source code of a project with an analyzer. I am new to C++.

It tells me that I should use Use _beginthreadex/_endthreadex functions instead of CreateThread/ExitThread functions

```<code>std::unique_ptr<Thread> Thread::Create(CreationParameters params,
                                   std::function<void()> start_routine) {
auto start_data = new ThreadStartData({std::move(start_routine)});
HANDLE handle =
  CreateThread(NULL, params.stack_size, ThreadStartRoutine, start_data,
               params.create_suspended ? CREATE_SUSPENDED : 0, NULL);
if (handle == INVALID_HANDLE_VALUE) {

void Thread::Exit(int exit_code) { ExitThread(exit_code); }
</code>```

答:
It really depends on what you are doing. If you are only calling Windows API functions in the new thread then CreateThread is fine but if you are calling C standard library functions in the thread then you are supposed to use _beginthreadex. _beginthreadex will call CreateThread internally but it might also allocate and initialize some per-thread CRT state.

I see someone in the comments claiming that the CRT no longer assigns CRT state this way. I don't know if that's true and either way, it is a implementation detail and could change depending on the compiler version. _beginthreadex will never be wrong so there is no reason not to use it.

ContentLicense: CC BY-SA 3.0

Body:
I checked the source code of a project with an analyzer. I am new to C++.

It tells me that I should use Use _beginthreadex/_endthreadex functions instead of CreateThread/ExitThread functions

std::unique_ptr<Thread> Thread::Create(CreationParameters params,
                                   std::function<void()> start_routine) {
auto start_data = new ThreadStartData({std::move(start_routine)});
HANDLE handle =
  CreateThread(NULL, params.stack_size, ThreadStartRoutine, start_data,
               params.create_suspended ? CREATE_SUSPENDED : 0, NULL);
if (handle == INVALID_HANDLE_VALUE) {

void Thread::Exit(int exit_code) { ExitThread(exit_code); }


问:
current date with delay
I writing application using vb .net.
In my application I got text box displaying current date.
As usually after midnight date is changing.
There is any chance  to set delay that date will change after 02:00 am next day ?

For example:

Today is 09/07/17 and I need that after midnight textbox will still show this date. But after 02:00 am ( 10/07/117 ) date will change for 10/07/17.

My current code:

```<code>  Private Sub HOMESCREEN_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SMARTSCREEN.MdiParent = Me
    SMARTSCREEN.StartPosition = FormStartPosition.CenterScreen
    SMARTSCREEN.Show()
    SMARTSCREEN.datee.Text = Date.Today()
    SMARTSCREEN.NOWEEK.Text = (DatePart("WW", Now))
</code>```

Thanks,

答:
The big (actually huge) question is, in what time zone is that 2:00 am you're talking about? You can easily achieve that by simply changing the time zone.

Say your time zone is US Eastern Time -5, then setting the time zone in your code to US Mountain Time -7 will effectively give you the result you want.

EDIT: This is trivial, but since you mentioned that you're in UK, then I assume that your time zone is London 0, so set to Coordinated Universal Time -2 to achieve what you want.

Alternatively, it can be simpler in your code to just subtract two hours:

```<code>SMARTSCREEN.datee.Text = DateTime.Now.AddHours(-2).ToString("d")
</code>```

Title: current date with delay

Body:
I writing application using vb .net.
In my application I got text box displaying current date.
As usually after midnight date is changing.
There is any chance  to set delay that date will change after 02:00 am next day ?

For example:

Today is 09/07/17 and I need that after midnight textbox will still show this date. But after 02:00 am ( 10/07/117 ) date will change for 10/07/17.

My current code:

  Private Sub HOMESCREEN_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SMARTSCREEN.MdiParent = Me
    SMARTSCREEN.StartPosition = FormStartPosition.CenterScreen
    SMARTSCREEN.Show()
    SMARTSCREEN.datee.Text = Date.Today()
    SMARTSCREEN.NOWEEK.Text = (DatePart("WW", Now))

Thanks,

Body:
The big (actually huge) question is, in what time zone is that 2:00 am you're talking about? You can easily achieve that by simply changing the time zone.

Say your time zone is US Eastern Time -5, then setting the time zone in your code to US Mountain Time -7 will effectively give you the result you want.

EDIT: This is trivial, but since you mentioned that you're in UK, then I assume that your time zone is London 0, so set to Coordinated Universal Time -2 to achieve what you want.

Alternatively, it can be simpler in your code to just subtract two hours:

SMARTSCREEN.datee.Text = DateTime.Now.AddHours(-2).ToString("d")


问:
How do I initialize a value that's based on a Recursive Type Alias?
How do I initialize a value that's based on a Recursive Type Alias?

```<code>type alias ContentProvider =
    { profile : Profile
    , topics : List Topic
    , links : Links
    , subscribers : Subscribers
    }

type Subscribers
    = Subscribers (List ContentProvider)
</code>```

My attempt to initialize the value fails:

```<code>contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2, contentProvider3 ])
</code>```

Note that the last argument is causing the error:

```<code>(Subscribers [ contentProvider2, contentProvider3 ])
</code>```

contentProvider1 is defined in terms of itself in a sneaky way,
  causing an infinite loop. - The following definitions depend directly
  on each other:

```<code>┌─────┐
│    contentProvider1
│     ↓
│    contentProvider2
│     ↓
│    contentProvider3
└─────┘
</code>```

I'm referencing this documentation. However, I do not understand why I am still getting a compiler error.

Appendix:

```<code>contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2 ])

contentProvider2 : ContentProvider
contentProvider2 =
    ContentProvider profile2 topics contentProvider2Links (Subscribers [ contentProvider1, contentProvider3 ])

contentProvider3 : ContentProvider
contentProvider3 =
    ContentProvider profile3 topics contentProvider3Links (Subscribers [ contentProvider1, contentProvider2 ])
</code>```

答:
Your code is syntactically correct, and prior to Elm 0.18, it would have compiled. But when you ran the program you would have ended up in either a stack overflow, an infinite loop (because of tail call recursion optimization), or a runtime exception because of a compiler bug that has since been fixed.

Consider what the runtime would have to go through to expand contentProvider1:

Expand contentProvider1, which has a reference to contentProvider2

Expand contentProvider2, which has a reference to contentProvider1

Expand contentProvider1, which has a reference to contentProvider2

and so on, to eternity

What you are experiencing is Elm's super helpful compiler saving you from code that wouldn't have worked anyway. It is still possible to write a non-halting function (and always will be), but Elm's compiler now checks for some common cases that would have otherwise blown up at runtime.

Here is some documentation that more thoroughly explains the reasoning behind this compiler error.

Body:
How do I initialize a value that's based on a Recursive Type Alias?

type alias ContentProvider =
    { profile : Profile
    , topics : List Topic
    , links : Links
    , subscribers : Subscribers
    }

type Subscribers
    = Subscribers (List ContentProvider)

My attempt to initialize the value fails:

contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2, contentProvider3 ])

Note that the last argument is causing the error:

(Subscribers [ contentProvider2, contentProvider3 ])

contentProvider1 is defined in terms of itself in a sneaky way,
  causing an infinite loop. - The following definitions depend directly
  on each other:

┌─────┐
│    contentProvider1
│     ↓
│    contentProvider2
│     ↓
│    contentProvider3
└─────┘

I'm referencing this documentation. However, I do not understand why I am still getting a compiler error.

Appendix:

contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2 ])

contentProvider2 : ContentProvider
contentProvider2 =
    ContentProvider profile2 topics contentProvider2Links (Subscribers [ contentProvider1, contentProvider3 ])

contentProvider3 : ContentProvider
contentProvider3 =
    ContentProvider profile3 topics contentProvider3Links (Subscribers [ contentProvider1, contentProvider2 ])


问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答:
The one that the authors of Design Patterns themselves most worried about was the "Visitor" pattern.

It's a "necessary evil" - but is often over used and the need for it often reveals a more fundamental flaw in your design.

An alternative name for the "Visitor" pattern is "Multi-dispatch", because the Visitor pattern is what you end up with when you wish to use a single-type dispatch OO language to select the code to use based on the type of two (or more) different objects.

The classic example being that you have the intersection between two shapes, but there's an even simpler case that's often overlooked: comparing the equality of two heterogeneous objects.

Anyway, often you end up with something like this:

```<code>interface IShape
{
    double intersectWith(Triangle t);
    double intersectWith(Rectangle r);
    double intersectWith(Circle c);
}
</code>```

The problem with this is that you have coupled together all of your implementations of "IShape". You've implied that whenever you wish to add a new shape to the hierarchy you will need to change all the other "Shape" implementations too.

Sometimes, this is the correct minimal design - but think it through. Does your design really mandate that you need to dispatch on two types? Are you willing to write each of the combinatorial explosion of multi-methods?

Often, by introducing another concept you can reduce the number of combinations that you're actually going to have to write:

```<code>interface IShape
{
    Area getArea();
}

class Area
{
    public double intersectWith(Area otherArea);
    ...
}
</code>```

Of course, it depends - sometimes you really do need to write code to handle all of those different cases - but it's worth taking pause and having a think before taking the plunge and using Visitor. It might save you a lot of pain later on.

OwnerDisplayName: Brian Rasmussen

ContentLicense: CC BY-SA 2.5

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn

Body:
The one that the authors of Design Patterns themselves most worried about was the "Visitor" pattern.

It's a "necessary evil" - but is often over used and the need for it often reveals a more fundamental flaw in your design.

An alternative name for the "Visitor" pattern is "Multi-dispatch", because the Visitor pattern is what you end up with when you wish to use a single-type dispatch OO language to select the code to use based on the type of two (or more) different objects.

The classic example being that you have the intersection between two shapes, but there's an even simpler case that's often overlooked: comparing the equality of two heterogeneous objects.

Anyway, often you end up with something like this:

interface IShape
{
    double intersectWith(Triangle t);
    double intersectWith(Rectangle r);
    double intersectWith(Circle c);
}

The problem with this is that you have coupled together all of your implementations of "IShape". You've implied that whenever you wish to add a new shape to the hierarchy you will need to change all the other "Shape" implementations too.

Sometimes, this is the correct minimal design - but think it through. Does your design really mandate that you need to dispatch on two types? Are you willing to write each of the combinatorial explosion of multi-methods?

Often, by introducing another concept you can reduce the number of combinations that you're actually going to have to write:

interface IShape
{
    Area getArea();
}

class Area
{
    public double intersectWith(Area otherArea);
    ...
}

Of course, it depends - sometimes you really do need to write code to handle all of those different cases - but it's worth taking pause and having a think before taking the plunge and using Visitor. It might save you a lot of pain later on.

OwnerDisplayName: Paul Hollingsworth

LastEditorDisplayName: Paul Hollingsworth


问:
getting node value exception
```<code><amount currency="USD">1000500</amount>
</code>```

while parsing above string i am getting only attribute value .when i try to get node value null pointer exception

for getting node value using

```<code> NodeList amountList= estimateElement.getElementsByTagName("amount");
 Element amtElement= (Element)amountList.item(0);
 String amount=amtElement.getFirstChild().getnodevalue()
</code>```

Thanks in advance

Aswan

答:
Please try this. I assume that it is true:

```<code> NodeList list = estimateElement.getElementsByTagName("amount").item(0).getChildNodes();
 Node node = (Node) list.item(0);

 String value  = node.getNodeValue();
</code>```

Source : DOM parser

Title: getting node value exception

Body:
<amount currency="USD">1000500</amount>

while parsing above string i am getting only attribute value .when i try to get node value null pointer exception

for getting node value using

 NodeList amountList= estimateElement.getElementsByTagName("amount");
 Element amtElement= (Element)amountList.item(0);
 String amount=amtElement.getFirstChild().getnodevalue()

Thanks in advance

Aswan

Body:
Please try this. I assume that it is true:

 NodeList list = estimateElement.getElementsByTagName("amount").item(0).getChildNodes();
 Node node = (Node) list.item(0);

 String value  = node.getNodeValue();

Source : DOM parser


问:
My registration page has constant error with undefined constant and unknown functions
I am creating a register page for a website.

here is my sql code :

```<code>| Field    | Type         | Null | Key | Default | Extra          |

| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(50)  | NO   |     | NULL    |                |
| course   | varchar(50)  | NO   |     | NULL    |                |
| year     | int(1)       | NO   |     | NULL    |                |
| password | varchar(500) | NO   |     | NULL    |                |
| contact  | int(20)      | NO   |     | NULL    |                |
| email    | varchar(200) | NO   |     | NULL    |                |
</code>```

php file is :

```<code>    <div class="container" style="padding:20px">
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading"><h2>Registration Form</h2>
                </div>
                <div class="panel-body">
                    <div class="col-lg-6">
                        <form>
                    <div class="form-group">
                    <label>Name :</label>
                            <input class="form-control" type="string"
                            id="inputname" name="name" placeholder="Your Name" required>
                    </div>
                     <div class="form-group">
                           <label for="sel1">Select Course :</label>
                              <select class="form-control" id="course" name="course" required>
                                <option>B.A. Programme </option>
                                <option>B.Com </option>
                                <option>B.Com(Hons.)</option>
                                <option>B.A.(Hons) Economics</option>
                                <option>B.A. (Hons.) English</option>
                                <option>B.A. (Hons.) History</option>
                                <option>B.A. (Hons.) Hindi</option>
                                <option>B.A. (Hons.) Political Science</option>
                                <option>B.A. (Hons.) Sanskrit</option>
                                <option>B.Sc. (Hons.) Mathematics</option>
                                <option>B.Sc.(Hons) Statistics</option>
                                <option>B.Sc.(Hons) Computer Science</option>
                                <option>B.Sc. Mathematical Science</option>
                              </select>
                    </div>
                    <div class="form-group">
                           <label for="sel1">Year :</label>
                              <select class="form-control" id="year" name="year" required>
                                <option>1 </option>
                                <option>2</option>
                                <option>3</option>
                              </select>
                    </div>
                    <div class="form-group">
                    <label>Password : </label>
                            <input class="form-control" type="password"
                            id="password" name="password" placeholder="Password" autocomplete="off" required>
                    </div>
                    <div class="form-group">
                    <label>Confirm Password  : </label>
                            <input class="form-control" type="text"
                            id="confirm_password" name="confirm_password" placeholder="Confirm password" required>
                    </div>
                    <div class="form-group">
                    <label>Contact No. : </label>
                            <input class="form-control" type="phonenum"
                            id="inputnumber" name="contact" placeholder="Your Contact Number" required>
                    </div>
                    <div class="form-group">
                    <label>Email : </label>
                            <input class="form-control" type="email"
                            id="inputname" name="email" placeholder="Your Email Id" required>
                    </div>
                    <input type="submit" name="submit" value="Register" class="btn btn-default" required>
                    </form>
                    </div>

                    <div class="col-lg-6" style="margin-top:10px">
                        <div class="panel panel-warning" >
                              <div class="panel-heading"><h3>Information</h3></div>
                              <div class="panel-body">
                                <ul>
                                <li>Complete the from to register with us.</li>
                                <li>Fill out the Details carefully.</li>
                                <li>Fill in your name as it is in your college ID.</li>
                                <li>Use your correct Email ID and Conatct No. so that we can contact to you.</li>
                                </ul>
                              </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
        var password = document.getElementById("password")
      , confirm_password = document.getElementById("confirm_password");

    function validatePassword(){
      if(password.value != confirm_password.value) {
        confirm_password.setCustomValidity("Passwords Don't Match");
      } else {
        confirm_password.setCustomValidity('');
      }
    }

    password.onchange = validatePassword;
    confirm_password.onkeyup = validatePassword;
</script>
<?php
    include "assets/backend/db.php";
    if(isset($_POST['name'])) {
        $name=$_POST['name'];
    }
    $name = $mysqli->escape_string($_POST['name']);
    if(isset($_POST['course'])) {
        $course=$_POST['course'];
    }
    if(isset($_POST['year'])) {
        $year=$_POST['year'];
    }
    if(isset($_POST['password'])) {
        $password=$_POST['password'];
    }
    $password = $mysqli->escape_string(password_hash($_POST['password'], md5));
    if(isset($_POST['contact'])) {
        $contact=$_POST['contact'];
    }
        $contact = $mysqli->escape_string($_POST['contact']);
    if(isset($_POST['email'])) {
        $email=$_POST['email'];
    }
    $email = $mysqli->escape_string($_POST['email']);
    // Check if user with that email already exists
    $result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());
    // We know user email exists if the rows returned are more than 0
    if ( $result->num_rows > 0 ) {
    echo  'User with this email already exists!';
    header("location: error.php");
    }
    else { // Email doesn't already exist in a database, proceed...
        $sql="INSERT INTO `user`(`name`, `course`, `year`, `password`, `contact`, `email`) VALUES ('$name','$course','$year','$password','$contact','$email')";
         // Add user to the database
        if ( $mysqli->query($sql) ){
            echo "You are successfully registered";
        }
        else {
            echo "Registration failed";
            header("location:join.php");
        }
    }

?>
</code>```

Errors that I get:

```<code>Notice: Undefined index: name in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 103

Notice: Undefined index: password in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 113

Notice: Use of undefined constant md5 - assumed 'md5' in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 113

Warning: password_hash() expects parameter 2 to be long, string given in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 113

Notice: Undefined index: contact in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 117

Notice: Undefined index: email in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 121

Fatal error: Call to undefined method mysqli::error() in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 123
</code>```

Help me fix this: :)

答:
Okay, I finally got everything working.

Some issues wore : I was typing the name of my table wrong. I was using "users" on the place of "user"

Some semicolon mistake and some brackets mistake but I was finally able to correct them all.

Here is my Code:

```<code>    <div class="container" style="padding:20px">
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading"><h2>Registration Form</h2>
                </div>
                <div class="panel-body">
                    <div class="col-lg-6">
                        <form action="" method="post">
                    <div class="form-group">
                    <label>Name :</label>
                            <input class="form-control" type="string"
                            id="inputname" name="name" placeholder="Your Name" required>
                    </div>
                     <div class="form-group">
                           <label for="sel1">Select Course :</label>
                              <select class="form-control" id="course" name="course" required>
                                <option>B.A. Programme </option>
                                <option>B.Com </option>
                                <option>B.Com(Hons.)</option>
                                <option>B.A.(Hons) Economics</option>
                                <option>B.A. (Hons.) English</option>
                                <option>B.A. (Hons.) History</option>
                                <option>B.A. (Hons.) Hindi</option>
                                <option>B.A. (Hons.) Political Science</option>
                                <option>B.A. (Hons.) Sanskrit</option>
                                <option>B.Sc. (Hons.) Mathematics</option>
                                <option>B.Sc.(Hons) Statistics</option>
                                <option>B.Sc.(Hons) Computer Science</option>
                                <option>B.Sc. Mathematical Science</option>
                              </select>
                    </div>
                    <div class="form-group">
                           <label for="sel1">Year :</label>
                              <select class="form-control" id="year" name="year" required>
                                <option>1 </option>
                                <option>2</option>
                                <option>3</option>
                              </select>
                    </div>
                    <div class="form-group">
                    <label>Password : </label>
                            <input class="form-control" type="password"
                            id="password" name="password" placeholder="Password" autocomplete="off" required>
                    </div>
                    <div class="form-group">
                    <label>Confirm Password  : </label>
                            <input class="form-control" type="text"
                            id="confirm_password" name="confirm_password" placeholder="Confirm password" required>
                    </div>
                    <div class="form-group">
                    <label>Contact No. : </label>
                            <input class="form-control" type="phonenum"
                            id="inputnumber" name="contact" placeholder="Your Contact Number" required>
                    </div>
                    <div class="form-group">
                    <label>Email : </label>
                            <input class="form-control" type="email"
                            id="inputname" name="email" placeholder="Your Email Id" required>
                    </div>
                    <input type="submit" name="submit" value="Register" class="btn btn-default" required>
                    </form>
                    </div>

                    <div class="col-lg-6" style="margin-top:10px">
                        <div class="panel panel-warning" >
                              <div class="panel-heading"><h3>Information</h3></div>
                              <div class="panel-body">
                                <ul>
                                <li>Complete the from to register with us.</li>
                                <li>Fill out the Details carefully.</li>
                                <li>Fill in your name as it is in your college ID.</li>
                                <li>Use your correct Email ID and Conatct No. so that we can contact to you.</li>
                                </ul>
                              </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
        var password = document.getElementById("password")
      , confirm_password = document.getElementById("confirm_password");

    function validatePassword(){
      if(password.value != confirm_password.value) {
        confirm_password.setCustomValidity("Passwords Don't Match");
      } else {
        confirm_password.setCustomValidity('');
      }
    }

    password.onchange = validatePassword;
    confirm_password.onkeyup = validatePassword;
</script>

<?php
    include "assets/backend/db.php";
    if(isset($_POST['name'])) {
        $name=$_POST['name'];

    $name = $mysqli->escape_string($_POST['name']);
    if(isset($_POST['course'])) {
        $course=$_POST['course'];

    if(isset($_POST['year'])) {
        $year=$_POST['year'];

    if(isset($_POST['password'])) {
        $password=$_POST['password'];

    $password = $mysqli->escape_string( password_hash( "$password" , PASSWORD_BCRYPT));
    if(isset($_POST['contact'])) {
        $contact=$_POST['contact'];

        $contact = $mysqli->escape_string($_POST['contact']);
    if(isset($_POST['email'])) {
        $email=$_POST['email'];

    $email = $mysqli->escape_string($_POST['email']);
    // Check if user with that email already exists
    $result = $mysqli->query("SELECT * FROM user WHERE email='$email'") or die($mysqli->error());
    $result->num_rows;
    // We know user email exists if the rows returned are more than 0
    if ( $result->num_rows > 0 ) {
    echo  'User with this email already exists!';

    }
    else { // Email doesn't already exist in a database, proceed...
        $sql="INSERT INTO `user`(`name`, `course`, `year`, `password`, `contact`, `email`) VALUES ('$name','$course','$year','$password','$contact','$email')";
         // Add user to the database
        if ( $mysqli->query($sql) ){
            echo "You are successfully registered";
        }
        else {
            echo "Registration failed";
            header("location:join.php");
        }
    }
    }
    }
    }
    }
    }
    }

?>
</code>```

This was a fun learning process.

Body:
I am creating a register page for a website.

here is my sql code :

| Field    | Type         | Null | Key | Default | Extra          |

| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(50)  | NO   |     | NULL    |                |
| course   | varchar(50)  | NO   |     | NULL    |                |
| year     | int(1)       | NO   |     | NULL    |                |
| password | varchar(500) | NO   |     | NULL    |                |
| contact  | int(20)      | NO   |     | NULL    |                |
| email    | varchar(200) | NO   |     | NULL    |                |

php file is :

Registration Form

                        <form>

                    Name :
                            <input class="form-control" type="string"
                            id="inputname" name="name" placeholder="Your Name" required>

                           Select Course :
                              <select class="form-control" id="course" name="course" required>
                                <option>B.A. Programme </option>
                                <option>B.Com </option>
                                <option>B.Com(Hons.)</option>
                                <option>B.A.(Hons) Economics</option>
                                <option>B.A. (Hons.) English</option>
                                <option>B.A. (Hons.) History</option>
                                <option>B.A. (Hons.) Hindi</option>
                                <option>B.A. (Hons.) Political Science</option>
                                <option>B.A. (Hons.) Sanskrit</option>
                                <option>B.Sc. (Hons.) Mathematics</option>
                                <option>B.Sc.(Hons) Statistics</option>
                                <option>B.Sc.(Hons) Computer Science</option>
                                <option>B.Sc. Mathematical Science</option>
                              </select>

                           Year :
                              <select class="form-control" id="year" name="year" required>
                                <option>1 </option>
                                <option>2</option>
                                <option>3</option>
                              </select>

                    Password :
                            <input class="form-control" type="password"
                            id="password" name="password" placeholder="Password" autocomplete="off" required>

                    Confirm Password  :
                            <input class="form-control" type="text"
                            id="confirm_password" name="confirm_password" placeholder="Confirm password" required>

                    Contact No. :
                            <input class="form-control" type="phonenum"
                            id="inputnumber" name="contact" placeholder="Your Contact Number" required>

                    Email :
                            <input class="form-control" type="email"
                            id="inputname" name="email" placeholder="Your Email Id" required>

                    <input type="submit" name="submit" value="Register" class="btn btn-default" required>
                    </form>

Information

Complete the from to register with us.

Fill out the Details carefully.

Fill in your name as it is in your college ID.

Use your correct Email ID and Conatct No. so that we can contact to you.

<?php
    include "assets/backend/db.php";
    if(isset($_POST['name'])) {
        $name=$_POST['name'];
    }
    $name = $mysqli->escape_string($_POST['name']);
    if(isset($_POST['course'])) {
        $course=$_POST['course'];
    }
    if(isset($_POST['year'])) {
        $year=$_POST['year'];
    }
    if(isset($_POST['password'])) {
        $password=$_POST['password'];
    }
    $password = $mysqli->escape_string(password_hash($_POST['password'], md5));
    if(isset($_POST['contact'])) {
        $contact=$_POST['contact'];
    }
        $contact = $mysqli->escape_string($_POST['contact']);
    if(isset($_POST['email'])) {
        $email=$_POST['email'];
    }
    $email = $mysqli->escape_string($_POST['email']);
    // Check if user with that email already exists
    $result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());
    // We know user email exists if the rows returned are more than 0
    if ( $result->num_rows > 0 ) {
    echo  'User with this email already exists!';
    header("location: error.php");
    }
    else { // Email doesn't already exist in a database, proceed...
        $sql="INSERT INTO `user`(`name`, `course`, `year`, `password`, `contact`, `email`) VALUES ('$name','$course','$year','$password','$contact','$email')";
         // Add user to the database
        if ( $mysqli->query($sql) ){
            echo "You are successfully registered";
        }
        else {
            echo "Registration failed";
            header("location:join.php");
        }
    }

?>

Errors that I get:

Notice: Undefined index: name in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 103

Notice: Undefined index: password in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 113

Notice: Use of undefined constant md5 - assumed 'md5' in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 113

Warning: password_hash() expects parameter 2 to be long, string given in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 113

Notice: Undefined index: contact in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 117

Notice: Undefined index: email in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 121

Fatal error: Call to undefined method mysqli::error() in C:\xampp\htdocs\PlacementCell\assets\php\register_form.php on line 123

Help me fix this: :)

Body:
Okay, I finally got everything working.

Some issues wore : I was typing the name of my table wrong. I was using "users" on the place of "user"

Some semicolon mistake and some brackets mistake but I was finally able to correct them all.

Here is my Code:

    <div class="container" style="padding:20px">
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading"><h2>Registration Form</h2>
                </div>
                <div class="panel-body">
                    <div class="col-lg-6">
                        <form action="" method="post">
                    <div class="form-group">
                    <label>Name :</label>
                            <input class="form-control" type="string"
                            id="inputname" name="name" placeholder="Your Name" required>
                    </div>
                     <div class="form-group">
                           <label for="sel1">Select Course :</label>
                              <select class="form-control" id="course" name="course" required>
                                <option>B.A. Programme </option>
                                <option>B.Com </option>
                                <option>B.Com(Hons.)</option>
                                <option>B.A.(Hons) Economics</option>
                                <option>B.A. (Hons.) English</option>
                                <option>B.A. (Hons.) History</option>
                                <option>B.A. (Hons.) Hindi</option>
                                <option>B.A. (Hons.) Political Science</option>
                                <option>B.A. (Hons.) Sanskrit</option>
                                <option>B.Sc. (Hons.) Mathematics</option>
                                <option>B.Sc.(Hons) Statistics</option>
                                <option>B.Sc.(Hons) Computer Science</option>
                                <option>B.Sc. Mathematical Science</option>
                              </select>
                    </div>
                    <div class="form-group">
                           <label for="sel1">Year :</label>
                              <select class="form-control" id="year" name="year" required>
                                <option>1 </option>
                                <option>2</option>
                                <option>3</option>
                              </select>
                    </div>
                    <div class="form-group">
                    <label>Password : </label>
                            <input class="form-control" type="password"
                            id="password" name="password" placeholder="Password" autocomplete="off" required>
                    </div>
                    <div class="form-group">
                    <label>Confirm Password  : </label>
                            <input class="form-control" type="text"
                            id="confirm_password" name="confirm_password" placeholder="Confirm password" required>
                    </div>
                    <div class="form-group">
                    <label>Contact No. : </label>
                            <input class="form-control" type="phonenum"
                            id="inputnumber" name="contact" placeholder="Your Contact Number" required>
                    </div>
                    <div class="form-group">
                    <label>Email : </label>
                            <input class="form-control" type="email"
                            id="inputname" name="email" placeholder="Your Email Id" required>
                    </div>
                    <input type="submit" name="submit" value="Register" class="btn btn-default" required>
                    </form>
                    </div>

                    <div class="col-lg-6" style="margin-top:10px">
                        <div class="panel panel-warning" >
                              <div class="panel-heading"><h3>Information</h3></div>
                              <div class="panel-body">
                                <ul>
                                <li>Complete the from to register with us.</li>
                                <li>Fill out the Details carefully.</li>
                                <li>Fill in your name as it is in your college ID.</li>
                                <li>Use your correct Email ID and Conatct No. so that we can contact to you.</li>
                                </ul>
                              </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
        var password = document.getElementById("password")
      , confirm_password = document.getElementById("confirm_password");

    function validatePassword(){
      if(password.value != confirm_password.value) {
        confirm_password.setCustomValidity("Passwords Don't Match");
      } else {
        confirm_password.setCustomValidity('');
      }
    }

    password.onchange = validatePassword;
    confirm_password.onkeyup = validatePassword;
</script>

<?php
    include "assets/backend/db.php";
    if(isset($_POST['name'])) {
        $name=$_POST['name'];

    $name = $mysqli->escape_string($_POST['name']);
    if(isset($_POST['course'])) {
        $course=$_POST['course'];

    if(isset($_POST['year'])) {
        $year=$_POST['year'];

    if(isset($_POST['password'])) {
        $password=$_POST['password'];

    $password = $mysqli->escape_string( password_hash( "$password" , PASSWORD_BCRYPT));
    if(isset($_POST['contact'])) {
        $contact=$_POST['contact'];

        $contact = $mysqli->escape_string($_POST['contact']);
    if(isset($_POST['email'])) {
        $email=$_POST['email'];

    $email = $mysqli->escape_string($_POST['email']);
    // Check if user with that email already exists
    $result = $mysqli->query("SELECT * FROM user WHERE email='$email'") or die($mysqli->error());
    $result->num_rows;
    // We know user email exists if the rows returned are more than 0
    if ( $result->num_rows > 0 ) {
    echo  'User with this email already exists!';

    }
    else { // Email doesn't already exist in a database, proceed...
        $sql="INSERT INTO `user`(`name`, `course`, `year`, `password`, `contact`, `email`) VALUES ('$name','$course','$year','$password','$contact','$email')";
         // Add user to the database
        if ( $mysqli->query($sql) ){
            echo "You are successfully registered";
        }
        else {
            echo "Registration failed";
            header("location:join.php");
        }
    }
    }
    }
    }
    }
    }
    }

?>

This was a fun learning process.


问:
C# timer and network call in parallel
I would like to have a Timer run for 5 seconds and simultaneously start a network request to a backend. I would like to then wait for both the timer and the request to complete before doing an action.

```<code>private async void doWork()
{
    await Task.Delay(5000);
    await doPostRequest();
    doSomethingElse();
}
</code>```

Something like the above code, except have both of those tasks executing in parallel. How can I do this?

答:
You can use Task.WhenAll for that:

```<code>private async void doWork()
{
    await Task.WhenAll(
      Task.Delay(5000),
      doPostRequest());
    doSomethingElse();
}
</code>```

There is also Task.WhenAny that completes as soon as one of those is completed.

Is it intentional that you don't return a Task from this method? You cannot await doWork itself now.

Title: C# timer and network call in parallel

Body:
I would like to have a Timer run for 5 seconds and simultaneously start a network request to a backend. I would like to then wait for both the timer and the request to complete before doing an action.

private async void doWork()
{
    await Task.Delay(5000);
    await doPostRequest();
    doSomethingElse();
}

Something like the above code, except have both of those tasks executing in parallel. How can I do this?

Body:
You can use Task.WhenAll for that:

private async void doWork()
{
    await Task.WhenAll(
      Task.Delay(5000),
      doPostRequest());
    doSomethingElse();
}

There is also Task.WhenAny that completes as soon as one of those is completed.

Is it intentional that you don't return a Task from this method? You cannot await doWork itself now.


问:
Namespaced object prototype
I'd like to enhance an object with some extra methods, for example add first() or second() methods to arrays but with a namespace so that it is called in the way [1, 2].item.second(), not [1, 2].second(). I got code like below but I'm getting undefined.

```<code>Array.prototype.item = {
    first: function () {
        return this[0];
    },
    second: function () {
        return this[1];
    }
};

[1, 2].item.second()
// undefined
// I don't want to use [1, 2].second()
</code>```

答:
The this in your first() and second() functions refers to the item property of the array, not to the array itself and that's why you're getting undefined.

The easiest way would be to capture the correct context by turning item into a method, as follows:

```<code>Array.prototype.item = function() {
  var _this = this;

  return {
    first: function() {
      return _this[0];
    },
    second: function() {
      return _this[1];
    }
  };
};
</code>```

Then:

```<code>[1, 2].item().first(); // 1
[1, 2].item().second(); // 2
</code>```

As per your update, if you insist on the original property syntax, you can try the following:

```<code>Object.defineProperty(Array.prototype, 'item', {
  get: function() {
    var _this = this;

    return {
      first: function() {
        return _this[0];
      },
      second: function() {
        return _this[1];
      }
    };
  }
});
</code>```

Then:

```<code>[1, 2].item.first(); // 1
[1, 2].item.second(); // 2
</code>```

See MDN

Title: Namespaced object prototype

Body:
I'd like to enhance an object with some extra methods, for example add first() or second() methods to arrays but with a namespace so that it is called in the way [1, 2].item.second(), not [1, 2].second(). I got code like below but I'm getting undefined.

Array.prototype.item = {
    first: function () {
        return this[0];
    },
    second: function () {
        return this[1];
    }
};

[1, 2].item.second()
// undefined
// I don't want to use [1, 2].second()

Body:
The this in your first() and second() functions refers to the item property of the array, not to the array itself and that's why you're getting undefined.

The easiest way would be to capture the correct context by turning item into a method, as follows:

Array.prototype.item = function() {
  var _this = this;

  return {
    first: function() {
      return _this[0];
    },
    second: function() {
      return _this[1];
    }
  };
};

Then:

[1, 2].item().first(); // 1
[1, 2].item().second(); // 2

As per your update, if you insist on the original property syntax, you can try the following:

Object.defineProperty(Array.prototype, 'item', {
  get: function() {
    var _this = this;

    return {
      first: function() {
        return _this[0];
      },
      second: function() {
        return _this[1];
      }
    };
  }
});

Then:

[1, 2].item.first(); // 1
[1, 2].item.second(); // 2

See MDN


问:
How to run 'sudo' command in windows
How would I run the following command in windows:

```<code>$ sudo django-admin.py startproject NEW
</code>```

?

答:
I think I tried steps below after doing some research & succeeded

1.Install scoop using powershell 3 (iex (new-object net.webclient).downloadstring('https://get.scoop.sh'))
2. do scoop install --global sudo
3. make sure paths (C:\Users\\scoop\shims & C:\ProgramData\scoop\shims) added in environmental path variable.

Title: How to run 'sudo' command in windows

Body:
How would I run the following command in windows:

$ sudo django-admin.py startproject NEW

?


问:
Pivot a dataframe in python
I have the below csv file

And after reading it with python in a DataFrame,I want to reshape it as

country,year1,value

country,year2,value

Taking into account only the country the year and the value.. So I will end up with 3 variables.

You can find the data set here:

http://data.worldbank.org/indicator/NY.GDP.MKTP.KD.ZG

答:
You can use:

read_csv with omit first 4 rows by skiprows

check if last column has all NaN values by isnull with all

all values are NaNs, so you can omit it, one possible solution is use iloc for select first 61 columns

reshape by set_index with unstack

last reset_index with rename column by dict

```<code>df = pd.read_csv('API_NY.GDP.MKTP.KD.ZG_DS2_en_csv_v2.csv', skiprows=4)
print (df.head())
  Country Name Country Code         Indicator Name     Indicator Code  1960  \
0        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
1  Afghanistan          AFG  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
2       Angola          AGO  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
3      Albania          ALB  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
4      Andorra          AND  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN

   1961  1962  1963  1964  1965     ...            2008       2009      2010  \
0   NaN   NaN   NaN   NaN   NaN     ...       -6.881302  -5.653502       NaN
1   NaN   NaN   NaN   NaN   NaN     ...        3.611368  21.020649  8.433290
2   NaN   NaN   NaN   NaN   NaN     ...       13.817146   2.412870  3.407655
3   NaN   NaN   NaN   NaN   NaN     ...        7.530000   3.350000  3.710000
4   NaN   NaN   NaN   NaN   NaN     ...       -8.594256  -3.817986 -5.347977

       2011       2012      2013      2014      2015      2016  Unnamed: 61
0       NaN        NaN       NaN       NaN       NaN       NaN          NaN
1  6.113685  14.434741  1.959123  1.312531  1.112558  2.232272          NaN
2  3.918597   5.155441  6.813586  4.804473  3.006981  0.000000          NaN
3  2.550000   1.420000  1.110000  1.800000  2.590000  3.460000          NaN
4 -4.802675  -1.760010 -0.063514       NaN       NaN       NaN          NaN
</code>```

```<code>cols = ['Country Name','Country Code','Indicator Name','Indicator Code']

print (df.iloc[:, 61].isnull().all())
True

d = {'level_4':'year'}
df = df.iloc[:, :60]
       .set_index(cols)
       .stack()
       .reset_index(name='vals')
       .rename(columns=d)
print (df.head())
  Country Name Country Code         Indicator Name     Indicator Code  year  \
0        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1995
1        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1996
2        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1997
3        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1998
4        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1999

       vals
0  1.245086
1  7.814432
2  6.666622
3  1.154469
4  4.514062
</code>```

For 3 columns is solution very similar, for remove columns use drop:

```<code>df = pd.read_csv('API_NY.GDP.MKTP.KD.ZG_DS2_en_csv_v2.csv', skiprows=4)

d = {'level_1':'year'}
df= df.drop(['Country Code','Indicator Name','Indicator Code', 'Unnamed: 61'], axis=1)
df = df.set_index('Country Name').stack().reset_index(name='vals').rename(columns=d)
print (df.head())
  Country Name  year      vals
0        Aruba  1995  1.245086
1        Aruba  1996  7.814432
2        Aruba  1997  6.666622
3        Aruba  1998  1.154469
4        Aruba  1999  4.514062
</code>```

Title: Pivot a dataframe in python

Body:
You can use:

read_csv with omit first 4 rows by skiprows

check if last column has all NaN values by isnull with all

all values are NaNs, so you can omit it, one possible solution is use iloc for select first 61 columns

reshape by set_index with unstack

last reset_index with rename column by dict

df = pd.read_csv('API_NY.GDP.MKTP.KD.ZG_DS2_en_csv_v2.csv', skiprows=4)
print (df.head())
  Country Name Country Code         Indicator Name     Indicator Code  1960  \
0        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
1  Afghanistan          AFG  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
2       Angola          AGO  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
3      Albania          ALB  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN
4      Andorra          AND  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG   NaN

   1961  1962  1963  1964  1965     ...            2008       2009      2010  \
0   NaN   NaN   NaN   NaN   NaN     ...       -6.881302  -5.653502       NaN
1   NaN   NaN   NaN   NaN   NaN     ...        3.611368  21.020649  8.433290
2   NaN   NaN   NaN   NaN   NaN     ...       13.817146   2.412870  3.407655
3   NaN   NaN   NaN   NaN   NaN     ...        7.530000   3.350000  3.710000
4   NaN   NaN   NaN   NaN   NaN     ...       -8.594256  -3.817986 -5.347977

       2011       2012      2013      2014      2015      2016  Unnamed: 61
0       NaN        NaN       NaN       NaN       NaN       NaN          NaN
1  6.113685  14.434741  1.959123  1.312531  1.112558  2.232272          NaN
2  3.918597   5.155441  6.813586  4.804473  3.006981  0.000000          NaN
3  2.550000   1.420000  1.110000  1.800000  2.590000  3.460000          NaN
4 -4.802675  -1.760010 -0.063514       NaN       NaN       NaN          NaN

cols = ['Country Name','Country Code','Indicator Name','Indicator Code']

print (df.iloc[:, 61].isnull().all())
True

d = {'level_4':'year'}
df = df.iloc[:, :60]
       .set_index(cols)
       .stack()
       .reset_index(name='vals')
       .rename(columns=d)
print (df.head())
  Country Name Country Code         Indicator Name     Indicator Code  year  \
0        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1995
1        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1996
2        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1997
3        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1998
4        Aruba          ABW  GDP growth (annual %)  NY.GDP.MKTP.KD.ZG  1999

       vals
0  1.245086
1  7.814432
2  6.666622
3  1.154469
4  4.514062

For 3 columns is solution very similar, for remove columns use drop:

df = pd.read_csv('API_NY.GDP.MKTP.KD.ZG_DS2_en_csv_v2.csv', skiprows=4)

d = {'level_1':'year'}
df= df.drop(['Country Code','Indicator Name','Indicator Code', 'Unnamed: 61'], axis=1)
df = df.set_index('Country Name').stack().reset_index(name='vals').rename(columns=d)
print (df.head())
  Country Name  year      vals
0        Aruba  1995  1.245086
1        Aruba  1996  7.814432
2        Aruba  1997  6.666622
3        Aruba  1998  1.154469
4        Aruba  1999  4.514062


问:
Unable to search for '\\n' using regular expressions in python3
```<code>>>> import re
>>> a='''\\n5
... 8'''
>>> b=re.findall('\\n[0-9]',a)
>>> print(b)
['\n8']
</code>```

Why does it show \n8 and not \n5?
I used a \ in front of \n the first time.
I am finding the use of raw string in regex in python a bit confusing. To me it does not seem to be making any changes to the result

答: because \\n5 is not valid new line, it will print \n5

Body:
>>> import re
>>> a='''\\n5
... 8'''
>>> b=re.findall('\\n[0-9]',a)
>>> print(b)
['\n8']

Why does it show \n8 and not \n5?
I used a \ in front of \n the first time.
I am finding the use of raw string in regex in python a bit confusing. To me it does not seem to be making any changes to the result


问:
how to parse json into php
i have a json data retrieved from data base i.e```<code>$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);</code>```
and this give me the result ```[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]```

but from another page when i call this json data i.e```$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;```

it give me the error

```Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0```

答:
try this first:

```<code>echo $json;
</code>```

to check if you got valid json.
Eventually, the php in fish-json.php was not executed.

Title: how to parse json into php

Body:
i have a json data retrieved from data base i.e
$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);

and this give me the result
[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]

but from another page when i call this json data i.e
$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;

it give me the error

Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0

Body:
try this first:

echo $json;

to check if you got valid json.
Eventually, the php in fish-json.php was not executed.


问:
Iframe doesn't stop from reloading in Angular loop
I'm working on a comments section of a forums page where I've used tinyMCE to supply the content. The content or the comment is being added asynchronously in a loop (*ngFor) of pre-existing comments object after being added to the database. The content is being rendered by the innerHTML property that calls a method that returns a decoded html content.

html code:

```<code><div [innerHTML]="trustContent(comment)">
</code>```

the method return:

```<code>this.sanitizer.bypassSecurityTrustHtml(content);
</code>```

The issue however is that every time I add or embed a media (iframes), e.g. youtube video using the editor, all the videos/iframes flickers and reloads endlessly. Any ideas, suggestion and solution are welcomed and appreciated! Thanks :)

答:
First of all, apologies for the late posting. Been very busy these past few weeks and I didn't have the luxury of time to post my answer up until now. Anyways... For the benefit of the those that might encounter this exact same issue, what worked for me was through the use of a pipe. So I've created a simple, custom pipe that transforms the given content and returns a safe and trusted html.

The Pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safe_html' })
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(content) {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }
}
</code>```

and then on the view, the content/comments are rendered as

```<code><div [innerHTML]="comment.content  | safe_html"></div>
</code>```

Just to reiterate, the comments were outputted inside a loop.

Body:
I'm working on a comments section of a forums page where I've used tinyMCE to supply the content. The content or the comment is being added asynchronously in a loop (*ngFor) of pre-existing comments object after being added to the database. The content is being rendered by the innerHTML property that calls a method that returns a decoded html content.

html code:

the method return:

this.sanitizer.bypassSecurityTrustHtml(content);

The issue however is that every time I add or embed a media (iframes), e.g. youtube video using the editor, all the videos/iframes flickers and reloads endlessly. Any ideas, suggestion and solution are welcomed and appreciated! Thanks :)

Body:
First of all, apologies for the late posting. Been very busy these past few weeks and I didn't have the luxury of time to post my answer up until now. Anyways... For the benefit of the those that might encounter this exact same issue, what worked for me was through the use of a pipe. So I've created a simple, custom pipe that transforms the given content and returns a safe and trusted html.

The Pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safe_html' })
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(content) {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }
}

and then on the view, the content/comments are rendered as

<div [innerHTML]="comment.content  | safe_html"></div>

Just to reiterate, the comments were outputted inside a loop.