问:
PHP fatal error - Call to a member function prepare() on resource
I have looked at other questions but i can't see a link between mine and others issues so i was wondering if i could get some advice on where i am going wrong.

I read about not mixing API's but im not sure if i am or not?

submitNoteText.php:

```<code>?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{
    var_dump($_POST['notetext1']);

    $stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
    $stmt->bind_param("si", $notetext2, $noteid2);

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];
    $stmt->execute();

    $stmt->close();
}
else
{
    if (isset($_POST['notetext1'])) {
        var_dump($notetext2);
    }
    else
    {
        echo "Test";
    }

}

?>
</code>```

connectionDetails.php:

```<code><?php
$myServer = "test ip";
$connectionInfo = array('Database' => 'DiscoverThePlanet', 'UID' => 'Test', 'PWD' => 'Test');

//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
  or die("Couldn't connect to SQL Server on $myServer");

//Test connection to server
// if ($conn)
// {
//     echo "connection successful";    # code...
// }

?>
</code>```

The error is in the submitNoteText.php and is this line:

```<code>$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
</code>```

答:
The sqlsrv_* API doesn't have a prepare() method. You're mixing database APIs.

Either use PDO or use sqlsrv_query()

Body:
I have looked at other questions but i can't see a link between mine and others issues so i was wondering if i could get some advice on where i am going wrong.

I read about not mixing API's but im not sure if i am or not?

submitNoteText.php:

?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{
    var_dump($_POST['notetext1']);

    $stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");
    $stmt->bind_param("si", $notetext2, $noteid2);

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];
    $stmt->execute();

    $stmt->close();
}
else
{
    if (isset($_POST['notetext1'])) {
        var_dump($notetext2);
    }
    else
    {
        echo "Test";
    }

}

?>

connectionDetails.php:

<?php
$myServer = "test ip";
$connectionInfo = array('Database' => 'DiscoverThePlanet', 'UID' => 'Test', 'PWD' => 'Test');

//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
  or die("Couldn't connect to SQL Server on $myServer");

//Test connection to server
// if ($conn)
// {
//     echo "connection successful";    # code...
// }

?>

The error is in the submitNoteText.php and is this line:

$stmt = $conn->prepare("UPDATE Notes SET Note = ? WHERE NoteID = ?");


来源: stackexchange

问:
C# how to "register" class "plug-ins" into a service class?
Update#2 as of year 2022

All these years have passed and still no good answer.
Decided to revive this question.

I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).

Everything is coded from the abstract class Base till the DoSomething classes.

My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:

```<code>public async Task<Obj1<XXXX>> DoSomething1(....params....)
        {
            var action = new DoSomething1(contructParams);
            return await action.Go(....params....);
        }
</code>```

I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.

Update#1
After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.

My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.

Example:
I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc....
Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:

```<code>var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);
</code>```

And I want to offer intellisense when I use the "CarService"....

In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.

In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:

```<code>// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
    // NO NEED OF EXTRA LINES....
}
</code>```

答:
At this point I am really tempted to do the following:

Make my own Class Attribute RegisterAction (just like I wrote on my "Theoretical" example)

Extend the Visual Studio Build Process

Then on my public class LazyProgrammerSolutionTask: Microsoft.Build.Utilities.Task try to find the service classes and identify the RegisterAction attributes.

Then per each one, I will inject using reflection my own method (the one that I am always copying paste)... and of course get the "signature" from the corresponding target "action" class.

In the end, compile everything again.

Then my "next project" that will consume this project (library) will have the intellisence that I am looking for....

One thing, that I am really not sure, it how the "debug" would work on this....

Since this is also still a theoretically (BUT POSSIBLE) solution, I do not have yet a source code to share.

Meanwhile, I will leave this question open for other possible approaches.

ContentLicense: CC BY-SA 4.0

Body:
Update#2 as of year 2022

All these years have passed and still no good answer.
Decided to revive this question.

I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).

Everything is coded from the abstract class Base till the DoSomething classes.

My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:

public async Task<Obj1<XXXX>> DoSomething1(....params....)
        {
            var action = new DoSomething1(contructParams);
            return await action.Go(....params....);
        }

I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.

Update#1
After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.

My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.

Example:
I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc....
Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:

var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);

And I want to offer intellisense when I use the "CarService"....

In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.

In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:

// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
    // NO NEED OF EXTRA LINES....
}

ContentLicense: CC BY-SA 3.0


问:
Requesting an API with jQuery .ajax() PUT is not working
Hi I have a problem with making a PUT request to an api with jquery.

This is my JavaScript:

```<code>var access_token = "##token##";
var service_url = "##url##";

var data = {
    access_token: access_token,
    id: this.getId(),
    content: this.getContent()
};
return $.ajax({
    method: 'PUT',
    url: service_url,
    data: data,
});
</code>```

When I monitor the incoming calls on the Server this PUT Call will be received as an OPTIONS call.

```<code>OPTIONS /##url### HTTP/1.1.
Host: ##host##.
Connection: keep-alive.
Pragma: no-cache.
Cache-Control: no-cache.
</code>```

GET and POST calls working in this way.
If I do the same PUT call with Postman everything works without problems.

I tested some stuff like:
contentType: 'text/json'
headers: {"X-HTTP-Method-Override": "PUT"}
parameters as a query
parameters as JSON

Nothing works. Need some help. :)

The CORS headers are set on the Server.
Access-Control-Allow-Origin → *

UPDATE
I found the solution here:
AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Chrome makes a preflight request(OPTIONS) before the real request to check for the cors headers. In my case this call was not handled correct.

I added some code to my NGINX on the server and then everything works.

```<code>if ($request_method = 'OPTIONS') {
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'Content-Type';
  add_header 'Content-Type' 'text/plain charset=UTF-8';
  add_header 'Content-Length' 0;
  return 204;
}
</code>```

答:
try this :</p>

```<code>$.ajax({
method: 'PUT',
url: service_url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
});
</code>```

Body:
Hi I have a problem with making a PUT request to an api with jquery.

This is my JavaScript:

var access_token = "##token##";
var service_url = "##url##";

var data = {
    access_token: access_token,
    id: this.getId(),
    content: this.getContent()
};
return $.ajax({
    method: 'PUT',
    url: service_url,
    data: data,
});

When I monitor the incoming calls on the Server this PUT Call will be received as an OPTIONS call.

OPTIONS /##url### HTTP/1.1.
Host: ##host##.
Connection: keep-alive.
Pragma: no-cache.
Cache-Control: no-cache.

GET and POST calls working in this way.
If I do the same PUT call with Postman everything works without problems.

I tested some stuff like:
contentType: 'text/json'
headers: {"X-HTTP-Method-Override": "PUT"}
parameters as a query
parameters as JSON

Nothing works. Need some help. :)

The CORS headers are set on the Server.
Access-Control-Allow-Origin → *

UPDATE
I found the solution here:
AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Chrome makes a preflight request(OPTIONS) before the real request to check for the cors headers. In my case this call was not handled correct.

I added some code to my NGINX on the server and then everything works.

if ($request_method = 'OPTIONS') {
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'Content-Type';
  add_header 'Content-Type' 'text/plain charset=UTF-8';
  add_header 'Content-Length' 0;
  return 204;
}

Body:
try this :

$.ajax({
method: 'PUT',
url: service_url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
});


问:
Facebook Like button issue where "like" occurs on different page than currently viewing in Wordpress
I'm having an issue where facebook "like" buttons are liking a category page rather than a single post in wordpress. I've tried using both the "Facebook Likes it!" plugin (currently using this one) and the "Easy Facebook Like Button" plugin.

Initially the like button would "like" the single post page and send it to facebook, but now it is "liking" the category url instead on some posts.

Here are URL's for example:

1)Main category page for one Artist. Note the like button on the left. It "likes" the artist.
http://envisionart.org/category/artists/christian/

2)Click on the first post, and it will automatically have you like the "post" if you already liked the artist, and it sends the "like" information to facebook as the same information as in #1 above
http://envisionart.org/artists/christian/atmospheric-perspective-3/

3)Same artist, third post. This post allows the end-user to "like" the post vs. the artist. I'm stumped as to why.
http://envisionart.org/artists/christian/bat-artist-trading-card/

Any help would be wonderful. I'll gladly post some code on request.

Also, check out these pages to cross-reference. Same setup, but I have no issues with the like buttons:
http://envisionart.org/category/programs/camps/

I'm stumped

答:
```<code>href=<?php echo urlencode(get_permalink()); ?>
</code>```

Example..

```<code><iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink()); ?>&layout=standard&show_faces=true&width=450&action=like&colorscheme=light&height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
href=<?php echo urlencode(get_permalink()); ?>

Example..

<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink()); ?>&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>


问:
How to pass a value from one component to another component Angular 2 (No parent child relationship)
Hi i have two components, component1 and component2. And i have a value, lets say x, and i want to pass the value to one of my component in my app, both have no parent-child or any relationship each other. How can i get the value x in component2 which is been set or created in component1? I know i can use local storage to set the value and get anywhere. Other than that is there any other way to do this? Sorry am new to Angular. Any idea guys? Thanks in advance.
currently what i have done in my component1:

```<code>window.localStorage.setItem('myVal', JSON.stringify(x));
</code>```

and in my component2:

```<code>let getmyVal: any = JSON.parse(localStorage.getItem("myVal"));
</code>```

答:
Since there is no relationship between the components, the easiest approach is to go for a publisher-subscriber model. Any component can publish any message, and any other component can subscribe to the said message, using the Observable.

Here is a sample Alert Service we created in one of our application

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AlertService {
    private subject = new Subject<any>();

    constructor() {
    }

    alert(alertType: string, objData: any) {
        this.subject.next({ type: alertType, data: objData });
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }

}```
</div>
</div>
</p>

<p>Now, to use it between Component1 and Component2 you can do the following. </p>

<p>Component1:</p>

<ol>
<li>Import the service, ask it to be injected by Angular and use it. Here is the code for Component 1. </li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component} from "@angular/core";
import { AlertService } from "../../../services/common/alert.service";

@Component({
    selector: 'c1',
    templateUrl: 'app/components/controls/Note/ComponentOne.component.html'
})

export class ComponentOne implements OnInit {

    constructor(private _alertService: AlertService) {
    }

    AlertMyMessage(): void {
        this._alertService.alert("SampleAlertType", "ComponentOneAlert");
    }
}</code>```

Component 2:

Now, component 2 subscribes to the message. Here is the code:

import { Component, OnInit} from "@angular/core";
import { AlertService } from "../../../services/common/alert.service";

@Component({
    selector: 'C2',
    templateUrl: 'app/components/ComponentTwo.component.html'
})

export class ComponentTwo implements OnInit {
constructor(private _alertService: AlertService) {
    }

    //Subscribing to the alert service on component initialization by providing an handler.
 ngOnInit(): void {
        this._alertService.getMessage().subscribe(data => this.alertReceived(data));
    }

    //This method is the event handler.
   private alertReceived(data: any) {
   console.log(data.data);
   }
}```

Body:
Hi i have two components, component1 and component2. And i have a value, lets say x, and i want to pass the value to one of my component in my app, both have no parent-child or any relationship each other. How can i get the value x in component2 which is been set or created in component1? I know i can use local storage to set the value and get anywhere. Other than that is there any other way to do this? Sorry am new to Angular. Any idea guys? Thanks in advance.
currently what i have done in my component1:

window.localStorage.setItem('myVal', JSON.stringify(x));

and in my component2:

let getmyVal: any = JSON.parse(localStorage.getItem("myVal"));

Body:
Since there is no relationship between the components, the easiest approach is to go for a publisher-subscriber model. Any component can publish any message, and any other component can subscribe to the said message, using the Observable.

Here is a sample Alert Service we created in one of our application

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AlertService {
    private subject = new Subject<any>();

    constructor() {
    }

    alert(alertType: string, objData: any) {
        this.subject.next({ type: alertType, data: objData });
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }

}

Now, to use it between Component1 and Component2 you can do the following.

Component1:

Import the service, ask it to be injected by Angular and use it. Here is the code for Component 1.

import { Component} from "@angular/core";
import { AlertService } from "../../../services/common/alert.service";

@Component({
    selector: 'c1',
    templateUrl: 'app/components/controls/Note/ComponentOne.component.html'
})

export class ComponentOne implements OnInit {

    constructor(private _alertService: AlertService) {
    }

    AlertMyMessage(): void {
        this._alertService.alert("SampleAlertType", "ComponentOneAlert");
    }
}

Component 2:

Now, component 2 subscribes to the message. Here is the code:

import { Component, OnInit} from "@angular/core";
import { AlertService } from "../../../services/common/alert.service";

@Component({
    selector: 'C2',
    templateUrl: 'app/components/ComponentTwo.component.html'
})

export class ComponentTwo implements OnInit {
constructor(private _alertService: AlertService) {
    }

    //Subscribing to the alert service on component initialization by providing an handler.
 ngOnInit(): void {
        this._alertService.getMessage().subscribe(data => this.alertReceived(data));
    }

    //This method is the event handler.
   private alertReceived(data: any) {
   console.log(data.data);
   }
}


问:
What is the relationship between a thread and its parent stack?
pthreads all have their own stack and share the heap. They inherit various aspects of the parent at creation time (sig masks, fpenv etc.). There seems to be little said about the relationship between the child thread and the parents stack.

So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work? Is the child thread able to see the stack of the parent process? Does the childs stack get populated with a copy of the parent stack at creation time?

It's useful to me to know what is guaranteed by the standard and what practically works.

答:
So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work?

Only if you ensure that the something on the parent stack is within scope while the child thread might access it.

For example, let's say you have a function that uses a fixed number of threads to perform some task. You can store a structure that describes the work for each thread on the parent stack, if, for example, the parent stays in the same scope (say, function), for the lifetime of the threads.

It may sound simple, but it is an easy source of bugs (kind of similar to use-after-free, except here the free part is having the variable or object referred to pass out of scope).

In general, it is much easier to allocate the structure describing the work dynamically, separately for each thread, rather than using a local variable (array). It lets you do things like

```<code>struct thread_work {
    struct thread_work *next;    /* Singly linked list */
    pthread_t           id;      /* Thread ID */
    /* Threads may NOT change the above, shouldn't even access them */

    /* Stuff that describes the work each thread should do */
};

void cancel_threads(struct thread_work *list)
{
    while (list) {
        struct thread_work *curr = list;

        list = list->next;

        curr->next = NULL;
        if (!pthread_cancel(curr->id))
             pthread_join(curr->id, NULL);
        free(curr);
    }
}

struct work_item *create_threads(void *(*worker)(struct work_item *),
                                 size_t count,
                                 size_t stacksize)
{
    struct work_item *list = NULL;
    struct work_item *curr;
    pthread_attr_t    attrs;
    int               result;

    pthread_attr_init(&attrs);
    if (stacksize > 0)
        pthread_attr_setstacksize(&attrs, stacksize);

    while (n-->0) {

        curr = malloc(sizeof *curr);
        if (!curr) {
            cancel_threads(list);
            pthread_attr_destroy(&attrs);
            errno = ENOMEM;
            return NULL;
        }

        /* TODO: Set up work-specific fields in curr */

        /* Chain items into an easily managed linked list */
        curr->next = list;
        list = curr;

        /* Create the worker thread */
        result = pthread_create(&(curr->id), &attrs,
                                (void *(*)(void *))worker,
                                curr);
        if (result) {
            cancel_threads(list);
            pthread_attr_destroy(&attrs);
            errno = result;
            return NULL;
        }
    }

    pthread_attr_destroy(&attrs);

    errno = 0;
    return list;
}
</code>```

In general, there is rarely any sane reason why you would use a local (stack) variable rather than a dynamically allocated one as the thread parameter.

Is the child thread able to see the stack of the parent process?

Process is the entity the threads belong to. What you call "parent process" is just the initial thread. In POSIX (pthreads), the initial thread has no special properties other than it being the only one in the process, initially.

Threads can see all memory belonging to the process, including stack areas. However, it is rarely useful, because a thread accessing the stack belonging to another thread only makes sense if you ensure (using e.g. a mutex) that the thread whose stack will be examined is in the appropriate scope (running a specific function or code).

In general, you should consider stack being a churning region of memory used for internal bookkeeping, where local variables live only for the short duration they are in scope; and therefore completely unsuitable for cross-thread data sharing.

Does the childs stack get populated with a copy of the parent stack at creation time?

No. That is, you cannot assume that happens.

(While some architectures or operating systems might do that, I don't know of any current ones supporting pthreads that actually do that.)

Body:
So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work?

Only if you ensure that the something on the parent stack is within scope while the child thread might access it.

For example, let's say you have a function that uses a fixed number of threads to perform some task. You can store a structure that describes the work for each thread on the parent stack, if, for example, the parent stays in the same scope (say, function), for the lifetime of the threads.

It may sound simple, but it is an easy source of bugs (kind of similar to use-after-free, except here the free part is having the variable or object referred to pass out of scope).

In general, it is much easier to allocate the structure describing the work dynamically, separately for each thread, rather than using a local variable (array). It lets you do things like

struct thread_work {
    struct thread_work *next;    /* Singly linked list */
    pthread_t           id;      /* Thread ID */
    /* Threads may NOT change the above, shouldn't even access them */

    /* Stuff that describes the work each thread should do */
};

void cancel_threads(struct thread_work *list)
{
    while (list) {
        struct thread_work *curr = list;

        list = list->next;

        curr->next = NULL;
        if (!pthread_cancel(curr->id))
             pthread_join(curr->id, NULL);
        free(curr);
    }
}

struct work_item *create_threads(void *(*worker)(struct work_item *),
                                 size_t count,
                                 size_t stacksize)
{
    struct work_item *list = NULL;
    struct work_item *curr;
    pthread_attr_t    attrs;
    int               result;

    pthread_attr_init(&attrs);
    if (stacksize > 0)
        pthread_attr_setstacksize(&attrs, stacksize);

    while (n-->0) {

        curr = malloc(sizeof *curr);
        if (!curr) {
            cancel_threads(list);
            pthread_attr_destroy(&attrs);
            errno = ENOMEM;
            return NULL;
        }

        /* TODO: Set up work-specific fields in curr */

        /* Chain items into an easily managed linked list */
        curr->next = list;
        list = curr;

        /* Create the worker thread */
        result = pthread_create(&(curr->id), &attrs,
                                (void *(*)(void *))worker,
                                curr);
        if (result) {
            cancel_threads(list);
            pthread_attr_destroy(&attrs);
            errno = result;
            return NULL;
        }
    }

    pthread_attr_destroy(&attrs);

    errno = 0;
    return list;
}

In general, there is rarely any sane reason why you would use a local (stack) variable rather than a dynamically allocated one as the thread parameter.

Is the child thread able to see the stack of the parent process?

Process is the entity the threads belong to. What you call "parent process" is just the initial thread. In POSIX (pthreads), the initial thread has no special properties other than it being the only one in the process, initially.

Threads can see all memory belonging to the process, including stack areas. However, it is rarely useful, because a thread accessing the stack belonging to another thread only makes sense if you ensure (using e.g. a mutex) that the thread whose stack will be examined is in the appropriate scope (running a specific function or code).

In general, you should consider stack being a churning region of memory used for internal bookkeeping, where local variables live only for the short duration they are in scope; and therefore completely unsuitable for cross-thread data sharing.

Does the childs stack get populated with a copy of the parent stack at creation time?

No. That is, you cannot assume that happens.

(While some architectures or operating systems might do that, I don't know of any current ones supporting pthreads that actually do that.)


问:
Content Management System or Any other suggestions
I'm working on a website right now, and i'm wondering on how can my client edit the content of the website without looking at the html files cause they really don't know how to use those, or should i say, can they edit the content from the website's interface itself by just typing something that will enable admin control or something like that? is it possible? </p>

答:
You can code in php for a client's interface to add content to the website. It sis possible but have limited expansions in future.

OR

You can choose a CMS(preferably Wordpress) to achieve this. It has good user interface without any hassle and less codes. Easy to use too.


问:
Response for preflight has invalid HTTP status code 400 Web API MVC
We have created a web api, and trying to post data from ajax using that api.
web api is working for post request when i am trying from Postman plugin, but not working when we are posting through ajax call using json data.

We are getting Error of XMLHttpRequest cannot load http://localhost:922/api/leaddetails/createlead. Response for preflight has invalid HTTP status code 400

Here is the ajax call code:

```<code>function SaveLead() {

        var Lead = {
            "lead_owner": "Pritam",
            "company_name": "C",
            "title": "T",
            "first_name": "Santosh",
            "last_name": "M",
            "address1": "Rajasthan",
            "address2": "d",
            "city": "d",
            "state": "d",
            "country": "d",
            "postal_code": "d",
            "email": "vaya@gmail.com",
            "phone": "d",
            "website": "d",
            "mobile": "8787878787",
            "lead_status": "d",
            "lead_source": "d",
            "industry": "d",
            "annual_revenue": "d",
            "skype_id": "d",
            "campaign_source": "d",
            "description": "d",
            "created_by": "A",
            "updated_by": "a"
        };

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: 'http://localhost:922/api/leaddetails/createlead',
            data: JSON.stringify(Lead),
            crossOrigin: true,
            dataType: "json",
            success: function (res) {
                alert("The result is : " + res);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        })

    }
</code>```

Here is my web.config file:

```<code><handlers>
  <remove name="WebDAV"/>
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
</handlers>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
</code>```

I have tried to post from Postman plugin. From there it is posting data perfectly.

答:
Finally got the answer from a friend. I don't know this is the solution or not but changing ajax syntax worked for me.

```<code>    var apiurl = 'http://localhost:922/api/leaddetails/createlead';
    var a = new XMLHttpRequest();
    function SaveLead() {
    var Lead = {
            "lead_owner": "Pritam",
            "company_name": "C",
            "title": "T",
            "first_name": "Sourav",
            "last_name": "M",
            "address1": "Bhilai",
            "address2": "d",
            "city": "d",
            "state": "d",
            "country": "d",
            "postal_code": "d",
            "email": "vaya@gmail.com",
            "phone": "d",
            "website": "d",
            "mobile": "8787878787",
            "lead_status": "d",
            "lead_source": "d",
            "industry": "d",
            "annual_revenue": "d",
            "skype_id": "d",
            "campaign_source": "d",
            "description": "d",
            "created_by": "A",
            "updated_by": "a"
        };

        a.open('POST',apiurl,true),
         $.ajax({

             url: apiurl,
             type: "POST",
             ContentType: "application/json; charset=utf-8",
             data: Lead,
             crossOrigin: true,
             dataType: "json",
             cache: false,
             complete: function (res) {
                 alert("Data Added Successfully");
             },
             error: function (xhr) {
                 alert("Error");
             }
         })

    }
</code>```

Thanks all for replying.

Body:
We have created a web api, and trying to post data from ajax using that api.
web api is working for post request when i am trying from Postman plugin, but not working when we are posting through ajax call using json data.

We are getting Error of XMLHttpRequest cannot load http://localhost:922/api/leaddetails/createlead. Response for preflight has invalid HTTP status code 400

Here is the ajax call code:

function SaveLead() {

        var Lead = {
            "lead_owner": "Pritam",
            "company_name": "C",
            "title": "T",
            "first_name": "Santosh",
            "last_name": "M",
            "address1": "Rajasthan",
            "address2": "d",
            "city": "d",
            "state": "d",
            "country": "d",
            "postal_code": "d",
            "email": "vaya@gmail.com",
            "phone": "d",
            "website": "d",
            "mobile": "8787878787",
            "lead_status": "d",
            "lead_source": "d",
            "industry": "d",
            "annual_revenue": "d",
            "skype_id": "d",
            "campaign_source": "d",
            "description": "d",
            "created_by": "A",
            "updated_by": "a"
        };

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: 'http://localhost:922/api/leaddetails/createlead',
            data: JSON.stringify(Lead),
            crossOrigin: true,
            dataType: "json",
            success: function (res) {
                alert("The result is : " + res);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        })

    }

Here is my web.config file:

<handlers>
  <remove name="WebDAV"/>
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
</handlers>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

I have tried to post from Postman plugin. From there it is posting data perfectly.

Body:
Finally got the answer from a friend. I don't know this is the solution or not but changing ajax syntax worked for me.

    var apiurl = 'http://localhost:922/api/leaddetails/createlead';
    var a = new XMLHttpRequest();
    function SaveLead() {
    var Lead = {
            "lead_owner": "Pritam",
            "company_name": "C",
            "title": "T",
            "first_name": "Sourav",
            "last_name": "M",
            "address1": "Bhilai",
            "address2": "d",
            "city": "d",
            "state": "d",
            "country": "d",
            "postal_code": "d",
            "email": "vaya@gmail.com",
            "phone": "d",
            "website": "d",
            "mobile": "8787878787",
            "lead_status": "d",
            "lead_source": "d",
            "industry": "d",
            "annual_revenue": "d",
            "skype_id": "d",
            "campaign_source": "d",
            "description": "d",
            "created_by": "A",
            "updated_by": "a"
        };

        a.open('POST',apiurl,true),
         $.ajax({

             url: apiurl,
             type: "POST",
             ContentType: "application/json; charset=utf-8",
             data: Lead,
             crossOrigin: true,
             dataType: "json",
             cache: false,
             complete: function (res) {
                 alert("Data Added Successfully");
             },
             error: function (xhr) {
                 alert("Error");
             }
         })

    }

Thanks all for replying.


问:
How can I change the source folder for a PHP project in NetBeans?
I'd like to change the Source Folder for a PHP project that I have set up in NetBeans 6.9. It doesn't look like NetBeans offers any easy way to do this. Does anybody know a way to make this happen?

Thanks...

答: WARNING: Please note that changing src.dir re-opening and rescanning will cause all Netbeans file change history to be lost! Depending on your work style this can cause quite some loss of history, which might or might not be important to you, especially when you don't frequently submit changes to your repository.


问:
Laravel hasMany with multiple constraints
I have query that I run on my ServiceController

```<code>return Service::with('contacts', 'locations.datetimes')->find($service->id);
</code>```

This works great perfectly, but I need to change it. The relationships are defined as follows:

```<code>class Service extends Model
{
  public function locations()
  {
    return $this->belongsToMany('App\Models\Service_location', 'service_location_service');
  }
}

class Service_location extends Model
{
  public function datetimes()
  {
    return $this->hasMany('App\Models\Service_detail');
  }
}
</code>```

I need a second constraint on the datetimes where I need the relationship to be along the lines of

```<code>return $this->hasMany('App\Models\Service_detail')->where('service_id', $service->id);
</code>```

The problem is I can't find a way to pass through the $service_id. How do you handle two constraints on a hasMany relationship?

答:
Let try this. Change Service_location to this

```<code> class Service_location extends Model
 {
      public function datetimes()
      {
          return $this->hasMany('App\Models\Service_detail');
      }

      public function scopeServiceId($query)
      {
          return $query->where('service_id', $service->id);
      }
}
</code>```

Now your query will be

```<code> Service::with(['contacts', 'locations.datetimes' =>function($q) use($serviceId){
     $q->serviceId($serviceId);
 }])->find($service->id);
</code>```

There is no way to pass argument to a relationship function. If you do its highly likely that you will run into the N+1 query problem.

Body:
I have query that I run on my ServiceController

return Service::with('contacts', 'locations.datetimes')->find($service->id);

This works great perfectly, but I need to change it. The relationships are defined as follows:

class Service extends Model
{
  public function locations()
  {
    return $this->belongsToMany('App\Models\Service_location', 'service_location_service');
  }
}

class Service_location extends Model
{
  public function datetimes()
  {
    return $this->hasMany('App\Models\Service_detail');
  }
}

I need a second constraint on the datetimes where I need the relationship to be along the lines of

return $this->hasMany('App\Models\Service_detail')->where('service_id', $service->id);

The problem is I can't find a way to pass through the $service_id. How do you handle two constraints on a hasMany relationship?

Body:
Let try this. Change Service_location to this

 class Service_location extends Model
 {
      public function datetimes()
      {
          return $this->hasMany('App\Models\Service_detail');
      }

      public function scopeServiceId($query)
      {
          return $query->where('service_id', $service->id);
      }
}

Now your query will be

 Service::with(['contacts', 'locations.datetimes' =>function($q) use($serviceId){
     $q->serviceId($serviceId);
 }])->find($service->id);

There is no way to pass argument to a relationship function. If you do its highly likely that you will run into the N+1 query problem.


问:
What is recommended way to compare ReflectionOnlyType with Type?
I have realized that I cannot directly compare types from reflection only loaded assemblies with types resolved by typeof, even they both are from the same assembly.

I am currently using:
 reflectionOnlyType.AssemblyQualifiedName == type.AssemblyQualifiedName.

What is the recommended way?

答:
I solved it by loading the System.ReflectionOnly type using the runtime type I have. That seems to be the safest way:

```<code>// Comes from an assembly loaded as reflection only
var reflectionOnlyTypeFromSomeAssembly = GetItFromSomewhere();

// Comes from an assembly that is running
var reflectionOnlyTypeFromRuntimeType =
        Type.ReflectionOnlyGetType(typeof(myType).AssemblyQualifiedName, false, true);

// Now you can compare
if (reflectionOnlyTypeFromSomeAssembly == reflectionOnlyTypeFromRuntimeType)
{
  // do something?
}
</code>```

Body:
I solved it by loading the System.ReflectionOnly type using the runtime type I have. That seems to be the safest way:

// Comes from an assembly loaded as reflection only
var reflectionOnlyTypeFromSomeAssembly = GetItFromSomewhere();

// Comes from an assembly that is running
var reflectionOnlyTypeFromRuntimeType =
        Type.ReflectionOnlyGetType(typeof(myType).AssemblyQualifiedName, false, true);

// Now you can compare
if (reflectionOnlyTypeFromSomeAssembly == reflectionOnlyTypeFromRuntimeType)
{
  // do something?
}


问:
Is Scrapy compatible with Python 3 on Windows?
Is 'scrapy' compatible with Python 3(or later) on Windows?
If not, then is the only option to use it with Python 2.7?
I need this for a project I need to do.
Thank you.</p>

答:
Scrapy runs on Python 2.7 and Python 3.3 or above.

Scrapy is being ported to Python 3 using the single-codebase approach.
  The goal is to make Scrapy work in both Python 2.7 and 3.3+ using the
  six library to smooth differences between Python 2.x and 3.x.

Installing scrapy in Windows 64 bit.

You can check this site to use scrappy Python 3 in pycharm :

http://www.jianshu.com/p/54c906b18a42


问:
fast unitary matrix multiplication with block acceleration
Assume I have a very fast subroutine for fixed size unitary matrix multiplication. (The subroutine may involve hardware acceleration) Say, a function called quantum_unmm_256(A, U, m) right-multiplies a m by 256 matrix A with a 256 by 256 unitary matrix U.

Now I want multiply something with a unitary matrix whose size is multiples of 256, say, a 1280x1280 unitary matrix. What would be a fast algorithm that make best use of the fast subroutine?

All matrices are assumed dense, with 64 or 128 bit float complex type.

答:
Have a look at parallel matrix multiplication algorithms. You can always divide the matrix in blocks, and multiply it in pieces. You can even reduce the amount of operations needed.

For example, reading Wikipedia:


问:
'Login as another user' MVC 4 Windows Authentication
I have an intranet project written in MVC 4 which uses Windows Authentication to authorise and authenticate users.

I need to add a 'Login as another user' functionality.

After some searching I found this solution which suggests returning a 401, and created the following Action (which is called using a form):

```<code>    //
    // POST: /Home/LogOut

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOut()
    {
        return new HttpUnauthorizedResult();
    }
</code>```

The Action gets called, and the browser pops up a username and password window, however as the result redirects back to the Action, a 401 is always returned.

How do I redirect the user back to the previous action, once they have logged in with the new credentials?

Is there a way to invalidate the credentials on the server side instead of just returning a 401?

答:
This method will always log the user out and redirect to the home page. I also added [AllowAnonymous] to make sure everybody can access this method.

```<code>    [AllowAnonymous]
    public ActionResult LogOut()
    {
        HttpCookie cookie = Request.Cookies["TSWA-Last-User"];

        cookie = new HttpCookie("TSWA-Last-User", string.Empty)
        {
            Expires = DateTime.Now.AddYears(-5)
        };
        Response.Cookies.Set(cookie);

        Response.AppendHeader("Connection", "close");
        Response.StatusCode = 401; // Unauthorized;
        Response.Clear();

        // redirect to home
        Response.Write("<script type='text/javascript'>");
        Response.Write("var getUrl = window.location; var baseUrl = getUrl.protocol + " +
           "'//' + getUrl.host + '/' + getUrl.pathname.split('/')[1]; window.location.href = baseUrl; ");
        Response.Write("</script>");
        Response.End();

        return RedirectToAction("Index");

    }
</code>```

Body:
I have an intranet project written in MVC 4 which uses Windows Authentication to authorise and authenticate users.

I need to add a 'Login as another user' functionality.

After some searching I found this solution which suggests returning a 401, and created the following Action (which is called using a form):

    //
    // POST: /Home/LogOut

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOut()
    {
        return new HttpUnauthorizedResult();
    }

The Action gets called, and the browser pops up a username and password window, however as the result redirects back to the Action, a 401 is always returned.

How do I redirect the user back to the previous action, once they have logged in with the new credentials?

Is there a way to invalidate the credentials on the server side instead of just returning a 401?

Body:
This method will always log the user out and redirect to the home page. I also added [AllowAnonymous] to make sure everybody can access this method.

    [AllowAnonymous]
    public ActionResult LogOut()
    {
        HttpCookie cookie = Request.Cookies["TSWA-Last-User"];

        cookie = new HttpCookie("TSWA-Last-User", string.Empty)
        {
            Expires = DateTime.Now.AddYears(-5)
        };
        Response.Cookies.Set(cookie);

        Response.AppendHeader("Connection", "close");
        Response.StatusCode = 401; // Unauthorized;
        Response.Clear();

        // redirect to home
        Response.Write("<script type='text/javascript'>");
        Response.Write("var getUrl = window.location; var baseUrl = getUrl.protocol + " +
           "'//' + getUrl.host + '/' + getUrl.pathname.split('/')[1]; window.location.href = baseUrl; ");
        Response.Write("</script>");
        Response.End();

        return RedirectToAction("Index");

    }


问:
How we select date from date picker using javascript in protractor tool? can you suggest solutions?
I have write code for select date from date picker in protractor.But this code not working.Unable to select date   </p>

```<code> var tbl = element(by.xpath(".//*[@id='content-wrapper']/div/div/div/div  /div[1]/div/form/div[4]/div/p/div/ul"));
var rows=tbl.element(by.tagName("tr"));

var columns=rows.element(by.tagName("td"));

  for(var i=0;i<columns.length;i++)

  {
    var st=columns.get(i).getText();
     if(st.toEqual("13")){
     columns.get(i).sendKeys(protractor.Key.ENTER);
    }
 console.log(st);
 browser.sleep(3000);
   }
</code>```

答:
All lines of code you placed are promises, so you first need to resolve each of them before you can use the result. For example, columns.get(i).getText() is a Promise, you first need to do the following before you can use the value

```<code>columns.get(i).getText()
    .then(function(tdText){
        console.log('tdText = ',tdText);
    });
</code>```

You can also use a filter method on all the td's like this, see the Protractor documentation:

```<code>// Get all the columns in a table, this will resolve in a ElementArrayFinder
// The filter will loop over each element in the ElementArrayFinder
$$('table td').filter(function(elem, index) {
  // For each found td, get the text
  return elem.getText().then(function(text) {
    // when a match is found, return it, else go to the next element
    return text === '13';
  });
// If an element is found based on the text it will return an ElementArrayFinder
// with 1 result, get the first element and for example click on it
}).first().click();
</code>```

Hope this helps

Body:
I have write code for select date from date picker in protractor.But this code not working.Unable to select date

 var tbl = element(by.xpath(".//*[@id='content-wrapper']/div/div/div/div  /div[1]/div/form/div[4]/div/p/div/ul"));
var rows=tbl.element(by.tagName("tr"));

var columns=rows.element(by.tagName("td"));

  for(var i=0;i<columns.length;i++)

  {
    var st=columns.get(i).getText();
     if(st.toEqual("13")){
     columns.get(i).sendKeys(protractor.Key.ENTER);
    }
 console.log(st);
 browser.sleep(3000);
   }

Body:
All lines of code you placed are promises, so you first need to resolve each of them before you can use the result. For example, columns.get(i).getText() is a Promise, you first need to do the following before you can use the value

columns.get(i).getText()
    .then(function(tdText){
        console.log('tdText = ',tdText);
    });

You can also use a filter method on all the td's like this, see the Protractor documentation:

// Get all the columns in a table, this will resolve in a ElementArrayFinder
// The filter will loop over each element in the ElementArrayFinder
$$('table td').filter(function(elem, index) {
  // For each found td, get the text
  return elem.getText().then(function(text) {
    // when a match is found, return it, else go to the next element
    return text === '13';
  });
// If an element is found based on the text it will return an ElementArrayFinder
// with 1 result, get the first element and for example click on it
}).first().click();

Hope this helps


问:
How to force keyboard with numbers in mobile website in Android
I have a mobile website and it has some HTML input elements in it, like this:

<input type="text" name="txtAccessoryCost" size="6" />
```

I have embedded the site into a WebView for possible Android 2.1 consumption, so that it will also be an Android application.

Is it possible to get the keyboard with numbers instead of the default one with letters when this HTML input element is focused?

Or, is it possible to set it for the whole application (maybe something in the Manifest file), if it is not feasible for an HTML element?

答:
```<code><input type="number" />
<input type="tel" />
</code>```

Both of these present the numeric keypad when the input gains focus.

<input type="search" />
shows a normal keyboard with an extra search button

Everything else seems to bring up the standard keyboard.

Body:
I have a mobile website and it has some HTML input elements in it, like this:

<input type="text" name="txtAccessoryCost" size="6" />

I have embedded the site into a WebView for possible Android 2.1 consumption, so that it will also be an Android application.

Is it possible to get the keyboard with numbers instead of the default one with letters when this HTML input element is focused?

Or, is it possible to set it for the whole application (maybe something in the Manifest file), if it is not feasible for an HTML element?

Body:
<input type="number" />
<input type="tel" />

Both of these present the numeric keypad when the input gains focus.

<input type="search" />
shows a normal keyboard with an extra search button

Everything else seems to bring up the standard keyboard.


问:
How do i find the selected id and name of radiobutton list
How do I find the selected id of radiobutton in list.

Here is the radiobutton:

```<code><input name="1" id="1" type="radio">
</code>```

Radiobutton are dynamics.

Here is the dynamic radio button list.

```<code><div class="row">
  <div class="form-group">
      <div class="col-md-12">
          <label>1. Here is the question??</label>
          <div class="icheck-list">
              <label class="icheck-list" id="1">

                  <input name="1" id="1" type="radio">Strongly Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="2">
                  <input name="1" id="2" type="radio">Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="3">
                  <input name="1" id="3" type="radio">Neither Agree or Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="4">
                  <input name="1" id="4" type="radio">Agree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="5">
                  <input name="1" id="5" type="radio">Strongly Agree
                  <span></span>
              </label>
          </div>
      </div>
  </div>
</div>
</code>```

There is 5 possible answers for a question.

I am using mvc 4.

For next question the i.e. for question 2.

The answer radiobutton is just like

```<code><input name="2" id="11" type="radio">Strongly Disagree
</code>```

So how do I find the selected radio button id and name???

here is the html i am using in view page.

```<code>        <div class="tab-pane active" id="tab1">

                                        @foreach (var items in Model.ParentList)
                                        {
                                            <div class="row">

                                                <div class="form-group">

                                                    <div class="col-md-12">

                                                        <label>@items.QuestionText</label>

                                                        @foreach (var ch in Model.ChildList)
                                                        {
                                                            if (items.QuestionId == ch.QuestionId)
                                                            {

                                                                <div class="icheck-list">
                                                                    <label class="icheck-list" id="@ch.AnswerId">
                                                                        @*<input type="checkbox"> @Html.DisplayFor(model => model.Answers[j].AnswerText)*@
                                                                        <input name="@ch.QuestionId" id="@ch.AnswerId" type="radio">@ch.AnswerText
                                                                        <span></span>
                                                                    </label> </div>
 }

                                                        }
 </div>
</div>
 }
</div>
</code>```

there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??

答:
Please use value instead of id with each input, then you can try below code</p>

```<code>$('input[type=radio]').on('change',function(event){
    console.log($(this).val());
});
</code>```

Body:
How do I find the selected id of radiobutton in list.

Here is the radiobutton:

<input name="1" id="1" type="radio">

Radiobutton are dynamics.

Here is the dynamic radio button list.

          1. Here is the question??

                  <input name="1" id="1" type="radio">Strongly Disagree

                  <input name="1" id="2" type="radio">Disagree

                  <input name="1" id="3" type="radio">Neither Agree or Disagree

                  <input name="1" id="4" type="radio">Agree

                  <input name="1" id="5" type="radio">Strongly Agree

There is 5 possible answers for a question.

I am using mvc 4.

For next question the i.e. for question 2.

The answer radiobutton is just like

<input name="2" id="11" type="radio">Strongly Disagree

So how do I find the selected radio button id and name???

here is the html i am using in view page.

                                        @foreach (var items in Model.ParentList)
                                        {

                                                        @items.QuestionText

                                                        @foreach (var ch in Model.ChildList)
                                                        {
                                                            if (items.QuestionId == ch.QuestionId)
                                                            {

                                                                        @*<input type="checkbox"> @Html.DisplayFor(model => model.Answers[j].AnswerText)*@
                                                                        <input name="@ch.QuestionId" id="@ch.AnswerId" type="radio">@ch.AnswerText

 }

                                                        }

 }

there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??

Body:
Please use value instead of id with each input, then you can try below code

$('input[type=radio]').on('change',function(event){
    console.log($(this).val());
});


问:
Programmatically logout an ASP.NET user
My app allows an admin to suspend/unsuspend user accounts. I do this with the following code:

```<code>MembershipUser user = Membership.GetUser(Guid.Parse(userId));
user.IsApproved = false;
Membership.UpdateUser(user);
</code>```

The above works fine to suspend the user, but it does not revoke their session. Consequently, the suspended user can remain with access to the application as long as their session cookie remains. Any fix/

答:
When you log out a user, it is also a good idea to overwrite the FormsAuthenticationTicket.

```<code>HttpContext context = HttpContext.Current;

//overwrite the authentication cookie
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, context.User.Identity.Name, DateTime.Now, DateTime.Now.AddDays(-1), false, Guid.NewGuid().ToString());
string encrypted_ticket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted_ticket);
cookie.Expires = ticket.Expiration;
context.Response.Cookies.Add(cookie);

//clear all the sessions
context.Session.Abandon();

//sign out and go to the login page
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
</code>```

Title: Programmatically logout an ASP.NET user

Body:
My app allows an admin to suspend/unsuspend user accounts. I do this with the following code:

MembershipUser user = Membership.GetUser(Guid.Parse(userId));
user.IsApproved = false;
Membership.UpdateUser(user);

The above works fine to suspend the user, but it does not revoke their session. Consequently, the suspended user can remain with access to the application as long as their session cookie remains. Any fix/

Body:
When you log out a user, it is also a good idea to overwrite the FormsAuthenticationTicket.

HttpContext context = HttpContext.Current;

//overwrite the authentication cookie
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, context.User.Identity.Name, DateTime.Now, DateTime.Now.AddDays(-1), false, Guid.NewGuid().ToString());
string encrypted_ticket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted_ticket);
cookie.Expires = ticket.Expiration;
context.Response.Cookies.Add(cookie);

//clear all the sessions
context.Session.Abandon();

//sign out and go to the login page
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();


问:
Looping inside an object
I had encountered something unclear to me in the for loop:

```<code>var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe"
    }
};
</code>```

I'm looping through this object with this loop:

```<code>var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '<li>' +
        '<a href = "' + info.links[key] +
        '">' + key + '</a>' +
        '</li>';
        console.log(key);
    }
}
var update = document.getElementById('links');
update.innerHTML = output;
</code>```

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?

答:
Go thorough this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

```<code>for (variable in object) { ...
}
</code>```

Variable "A different property name is assigned to variable on each iteration."
In your case "facebook", "twitter" , etc are your property names in object

Title: Looping inside an object

Body:
I had encountered something unclear to me in the for loop:

var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe"
    }
};

I'm looping through this object with this loop:

var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '
' +
        '' + key + '' +
        '
';
        console.log(key);
    }
}
var update = document.getElementById('links');
update.innerHTML = output;

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?

Body:
Go thorough this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for (variable in object) { ...
}

Variable "A different property name is assigned to variable on each iteration."
In your case "facebook", "twitter" , etc are your property names in object


问:
JMeter saving test results into file. CLI
I added 'Simple Data Writer' to my test plan with the next filename path:

```<code>${__time(Y-MM-dd)}/${__time(HH-mm)}.jtl
</code>```

It works perfectly when I run script from UI but not from command line (script doesn't create folder and saves results into incorrectly named file).

Any ideas how to create folder with date in the name and time in name of .jtl file using Simple Data Writer ?

I'm using windows 10.

Thank you

答:
For some reason when running from cli on windows, jmeter doesn't adapt file separators for current os. This solution works for me:</p>

```<code>${__time(Y-MM-dd)}\\${__time(HH-mm)}.jtl
</code>```

Body:
I added 'Simple Data Writer' to my test plan with the next filename path:

${__time(Y-MM-dd)}/${__time(HH-mm)}.jtl

It works perfectly when I run script from UI but not from command line (script doesn't create folder and saves results into incorrectly named file).

Any ideas how to create folder with date in the name and time in name of .jtl file using Simple Data Writer ?

I'm using windows 10.

Thank you

Body:
For some reason when running from cli on windows, jmeter doesn't adapt file separators for current os. This solution works for me:

${__time(Y-MM-dd)}\\${__time(HH-mm)}.jtl


问:
How to compare same column in the same table in SQL?
Let's say I have a table with following records

```<code>Name             Seq                  Join                     Resign
---------------- ---------------------------------------- ----------------------------
Joe              1                    2001-11-04 00:00:00.000  2005-03-31 00:00:00.000
Joe              2                    2005-04-01 00:00:00.000  NULL
Jane             1                    2011-12-04 00:00:00.000  2013-02-01 00:00:00.000
Jane             2                    2015-05-01 00:00:00.000  NULL
Jack             1                    2001-01-01 00:00:00.000  2002-01-01 00:00:00.000
Jack             2                    2002-01-02 00:00:00.000  2003-01-01 00:00:00.000
Jack             3                    2005-01-01 00:00:00.000  2006-01-01 00:00:00.000
Jack             4                    2006-01-02 00:00:00.000  NULL
</code>```

So I'm trying to find out Employee Join Date, Seq represents hire number, so if an Employee resign and later rejoin the company, the Seq will increase. But the problem is Seq will also increase when Employee get a promotion or move to another department.

In my case, Joe has 2 Seq but he never resigned because his 2nd Join Date = Resign Date + 1. So my final expected result is

Joe, 2001-11-04

Jane, 2015-05-01

Jack, 2005-01-01 (because he resigned after 2nd hire)

Any idea how to get this result without looping?

Note: Seq can be 1,2,3,4 and so on depends on how many promotion or resign/rejoin on each employee

Jack expected result is 2005-01-01 because from 1st hire to 2nd is not an actual resignation because 2nd hire JoinDate = 1st hire ResignDate + 1 2002-01-01 = 2002-01-02 + 1. But from 2nd hire to 3rd hire is an actually resignation because 2003-01-01 != 2005-01-01 + 1. I hope that make sense.

答:
I think you can try this:

```<code>SELECT B.NAME, JJOIN
FROM (SELECT *
    , LAG(DD1) OVER (PARTITION BY NAME ORDER BY RMAX) AS DD1_PREC
   FROM
    (
    SELECT *
        , ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY SEQ DESC) AS RMAX
        , LEAD(RESIGN) OVER (PARTITION BY NAME ORDER BY SEQ DESC) AS PREC_RESIGN
        ,  DATEDIFF(dd,LEAD(RESIGN) OVER (PARTITION BY NAME ORDER BY SEQ DESC),JJOIN) AS DD1
    FROM TABLEX) A
    ) B
WHERE (RMAX =1 AND DD1>1 )
     OR (RMAX = 2 AND DD1_PREC<=1)
</code>```

Output:

```<code>NAME                 JJOIN
-------------------- -----------------------
Jack                 2005-01-01 00:00:00.000
Jane                 2015-05-01 00:00:00.000
Joe                  2010-11-04 00:00:00.000
</code>```

Body:
Let's say I have a table with following records

Name             Seq                  Join                     Resign
---------------- ---------------------------------------- ----------------------------
Joe              1                    2001-11-04 00:00:00.000  2005-03-31 00:00:00.000
Joe              2                    2005-04-01 00:00:00.000  NULL
Jane             1                    2011-12-04 00:00:00.000  2013-02-01 00:00:00.000
Jane             2                    2015-05-01 00:00:00.000  NULL
Jack             1                    2001-01-01 00:00:00.000  2002-01-01 00:00:00.000
Jack             2                    2002-01-02 00:00:00.000  2003-01-01 00:00:00.000
Jack             3                    2005-01-01 00:00:00.000  2006-01-01 00:00:00.000
Jack             4                    2006-01-02 00:00:00.000  NULL

So I'm trying to find out Employee Join Date, Seq represents hire number, so if an Employee resign and later rejoin the company, the Seq will increase. But the problem is Seq will also increase when Employee get a promotion or move to another department.

In my case, Joe has 2 Seq but he never resigned because his 2nd Join Date = Resign Date + 1. So my final expected result is

Joe, 2001-11-04

Jane, 2015-05-01

Jack, 2005-01-01 (because he resigned after 2nd hire)

Any idea how to get this result without looping?

Note: Seq can be 1,2,3,4 and so on depends on how many promotion or resign/rejoin on each employee

Jack expected result is 2005-01-01 because from 1st hire to 2nd is not an actual resignation because 2nd hire JoinDate = 1st hire ResignDate + 1 2002-01-01 = 2002-01-02 + 1. But from 2nd hire to 3rd hire is an actually resignation because 2003-01-01 != 2005-01-01 + 1. I hope that make sense.

Body:
I think you can try this:

SELECT B.NAME, JJOIN
FROM (SELECT *
    , LAG(DD1) OVER (PARTITION BY NAME ORDER BY RMAX) AS DD1_PREC
   FROM
    (
    SELECT *
        , ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY SEQ DESC) AS RMAX
        , LEAD(RESIGN) OVER (PARTITION BY NAME ORDER BY SEQ DESC) AS PREC_RESIGN
        ,  DATEDIFF(dd,LEAD(RESIGN) OVER (PARTITION BY NAME ORDER BY SEQ DESC),JJOIN) AS DD1
    FROM TABLEX) A
    ) B
WHERE (RMAX =1 AND DD1>1 )
     OR (RMAX = 2 AND DD1_PREC<=1)

Output:

NAME                 JJOIN
-------------------- -----------------------
Jack                 2005-01-01 00:00:00.000
Jane                 2015-05-01 00:00:00.000
Joe                  2010-11-04 00:00:00.000


问:
async process dialog not showing in application in android
async process dialog is not showing in application in android. Can anybody tell me what the problem is?

My code

```<code>public void onClick(View v)
{
  new FetchTask(getBaseContext()).execute(null);
}

 public class FetchTask extends AsyncTask<Object, ArrayList,ArrayList>
 {

     private ProgressDialog dlg;
     private Context ctx;

     public FetchTask(Context context) {
         ctx = context;
     }

     @Override
     protected void onPreExecute() {
         dlg = new ProgressDialog(ctx);
         dlg.setMessage("Loading....");
         dlg.show();
         super.onPreExecute();
     }

     @Override
     protected void onPostExecute(ArrayList parserValue) {
         dlg.dismiss();

           for(int i=0;i<parservalue.size();i++)
             {
                DomParserDataSet dataset=(DomParserDataSet)parservalue.get(i);
                 if(dataset.getToken_string().length()>1)
                      {

                  Intent homeIntent=new Intent(ctx,HelloTabWidget.class);
                  homeIntent.putExtra("strUserName", username);
                  homeIntent.putExtra("strPassword",password );
                  homeIntent.putExtra("questGroupId",dataset.getQuest_group_id());
                  homeIntent.putExtra("userid",dataset.getUser_id());
                  homeIntent.putExtra("systemuserid", dataset.getSystem_user_id());
                  homeIntent.putExtra("providerid",dataset.getIndex_provider_id());
                       startActivity(homeIntent);
                   //startActivity(new Intent(this,HelloTabWidget.class));

                   }
                   else
                   {

                     DomParserDataSet dataset1=(DomParserDataSet)parservalue.get(i);
                     AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx);
                      alertbox.setMessage(dataset1.getError_value());
                         alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

                           public void onClick(DialogInterface dialog, int arg1) {
                               // the button was clicked

                            dialog.cancel();

                           }
                       });

                       // show it
                       alertbox.show();
                   }

             }

             // display data
         }

  @Override
  protected ArrayList doInBackground(Object... arg0) {

   try
      {
          username=edtUserName.getText().toString();
          password=edtPassword.getText().toString();
          WebService service=new WebService();
          String webservicevalue=service.callServer(SOAP_ACTION,"", username,password,URL);
            webservicevalue=decodeXMLData(webservicevalue);
            DomParser xmlParser=new DomParser();
           parservalue=xmlParser.parseXmlFile(webservicevalue);

           String parservalue1=Integer.toString(parservalue.size());

           Log.d("parser value size is",parservalue1);

            }
             catch (Exception e) {
       // TODO: handle exception
              e.printStackTrace();
      }

             return parservalue;
       }

 }
</code>```

Can anybody tell me what I have to change?

答:
As pointed out by Arhimed, this isn't correct. Leaving the answer for future references though.

I think you need to move super.onPreExecute(); to the first line in onPreExecute(), like this:

```<code> @Override
 protected void onPreExecute() {
     super.onPreExecute();
     dlg = new ProgressDialog(ctx);
     dlg.setMessage("Loading....");
     dlg.show();
 }
</code>```

Body:
async process dialog is not showing in application in android. Can anybody tell me what the problem is?

My code

public void onClick(View v)
{
  new FetchTask(getBaseContext()).execute(null);
}

 public class FetchTask extends AsyncTask<Object, ArrayList,ArrayList>
 {

     private ProgressDialog dlg;
     private Context ctx;

     public FetchTask(Context context) {
         ctx = context;
     }

     @Override
     protected void onPreExecute() {
         dlg = new ProgressDialog(ctx);
         dlg.setMessage("Loading....");
         dlg.show();
         super.onPreExecute();
     }

     @Override
     protected void onPostExecute(ArrayList parserValue) {
         dlg.dismiss();

           for(int i=0;i<parservalue.size();i++)
             {
                DomParserDataSet dataset=(DomParserDataSet)parservalue.get(i);
                 if(dataset.getToken_string().length()>1)
                      {

                  Intent homeIntent=new Intent(ctx,HelloTabWidget.class);
                  homeIntent.putExtra("strUserName", username);
                  homeIntent.putExtra("strPassword",password );
                  homeIntent.putExtra("questGroupId",dataset.getQuest_group_id());
                  homeIntent.putExtra("userid",dataset.getUser_id());
                  homeIntent.putExtra("systemuserid", dataset.getSystem_user_id());
                  homeIntent.putExtra("providerid",dataset.getIndex_provider_id());
                       startActivity(homeIntent);
                   //startActivity(new Intent(this,HelloTabWidget.class));

                   }
                   else
                   {

                     DomParserDataSet dataset1=(DomParserDataSet)parservalue.get(i);
                     AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx);
                      alertbox.setMessage(dataset1.getError_value());
                         alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

                           public void onClick(DialogInterface dialog, int arg1) {
                               // the button was clicked

                            dialog.cancel();

                           }
                       });

                       // show it
                       alertbox.show();
                   }

             }

             // display data
         }

  @Override
  protected ArrayList doInBackground(Object... arg0) {

   try
      {
          username=edtUserName.getText().toString();
          password=edtPassword.getText().toString();
          WebService service=new WebService();
          String webservicevalue=service.callServer(SOAP_ACTION,"", username,password,URL);
            webservicevalue=decodeXMLData(webservicevalue);
            DomParser xmlParser=new DomParser();
           parservalue=xmlParser.parseXmlFile(webservicevalue);

           String parservalue1=Integer.toString(parservalue.size());

           Log.d("parser value size is",parservalue1);

            }
             catch (Exception e) {
       // TODO: handle exception
              e.printStackTrace();
      }

             return parservalue;
       }

 }

Can anybody tell me what I have to change?

Body:
As pointed out by Arhimed, this isn't correct. Leaving the answer for future references though.

I think you need to move super.onPreExecute(); to the first line in onPreExecute(), like this:

 @Override
 protected void onPreExecute() {
     super.onPreExecute();
     dlg = new ProgressDialog(ctx);
     dlg.setMessage("Loading....");
     dlg.show();
 }


问:
Error message from filter array
So I have tried to get the error message from a filter array in a logic app workflow, this is what i have tried:

```<code>@body('Filter_array')['error']

@actions('Filter_array')['outputs']['body']['error']
</code>```

Am I missing something or doing something wrong here?

Thanks.

UPDATE:

It says: "cannot be evaluated because property 'error' cannot be selected. ".

But i can clearly see the "error" in the body object in the output.

答:
Can you try with @actions('Filter_array')['error'] ?

You have to distinguish 2 types of errors.

First error can occur during execution of your connector. Eg. The filter did not match. In this case, the connector executed and returns an output with an error-message.

Second error is a runtime error that can occur on the connector. For example if the input of your connector is invalid and the executing of the connector can't be triggered. In this case, the connector does not generate an output or result. In that case, you have to catch the exception with @actions('Filter_array')['error']

Title: Error message from filter array

Body:
So I have tried to get the error message from a filter array in a logic app workflow, this is what i have tried:

@body('Filter_array')['error']

@actions('Filter_array')['outputs']['body']['error']

Am I missing something or doing something wrong here?

Thanks.

UPDATE:

It says: "cannot be evaluated because property 'error' cannot be selected. ".

But i can clearly see the "error" in the body object in the output.


问:
How do I set the min attribute for <input type="date"> via h:inputText?
I have the following HTML calendar:

```<code><h:inputText t:type="date" value="#{data.dueDate}">
    <f:convertDateTime pattern="yyyy-MM-dd"/>
</h:inputText>
</code>```

How can I add the min attribute for this?

t refers to xmlns:t="http://xmlns.jcp.org/jsf/passthrough"

答:
With input type date you can use min and max attributes. You can set the min attribute the same way you used passthrough to set the type="date" attribute. So, for example:

```<code><h:inputText t:type="date" t:min="2016-12-31" value="#{data.dueDate}">
  <f:convertDateTime pattern="yyyy-MM-dd"/>
</h:inputText>
</code>```

See also:

https://www.w3.org/TR/html5/forms.html#date-state-(type=date)

https://www.w3.org/TR/html5/infrastructure.html#valid-date-string

min/max attribute with type = date on HTML5

http://caniuse.com/#feat=input-datetime

Body:
I have the following HTML calendar:

<h:inputText t:type="date" value="#{data.dueDate}">
    <f:convertDateTime pattern="yyyy-MM-dd"/>
</h:inputText>

How can I add the min attribute for this?

t refers to xmlns:t="http://xmlns.jcp.org/jsf/passthrough"

Body:
With input type date you can use min and max attributes. You can set the min attribute the same way you used passthrough to set the type="date" attribute. So, for example:

<h:inputText t:type="date" t:min="2016-12-31" value="#{data.dueDate}">
  <f:convertDateTime pattern="yyyy-MM-dd"/>
</h:inputText>

See also:

https://www.w3.org/TR/html5/forms.html#date-state-(type=date)

https://www.w3.org/TR/html5/infrastructure.html#valid-date-string

min/max attribute with type = date on HTML5

http://caniuse.com/#feat=input-datetime


问:
Laravel comments and user relationship returns null
I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code:
Post.php

```<code>    class Post extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['title','created_at','username','image'];
    public function user()
    {
      return $this->belongsTo(User::class,'username');
    }
    public function votes()
    {
      //Quick note: Id refers to the post id.
      return $this->hasMany(PostVotes::class,'post_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class,'post_id');
    }
}
</code>```

User.php

```<code>class User extends Model implements Authenticatable
{
  use AuthenticableTrait;
  protected $primaryKey = 'username';
  public $incrementing = false;
  public $timestamps = false;
  protected $fillable = ['username','email','password','created_at','avatar','about'];
  // Gets avatar to display on navbar.
  public function posts()
  {
    return $this->hasMany(Post::class,'username');
  }
  public function comments()
  {
    return $this->hasMany(Comment::class,'username');
  }
  public static function getAvatar()
  {
     return self::Where('username', '=', Session::get('username'))->value('avatar');
  }

}
</code>```

Comment.php

```<code>    class Comment extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['comment','created_at','post_id','username'];
    public function user()
    {
        $this->belongsTo(User::class,'username') ;
    }
    public function post()
    {
        $this->belongsTo(Post::class,'post_id');
    }
}
public function view($post_id)
   {
      $post = Post::with('comments')->findOrFail($post_id);
      return view('posts.view',compact('post'));
   }
  @foreach($post->comments as $comment)
 // null
 {{dd($comment->user())}}
@endforeach
</code>```

答:
Use missed the return keyword

```<code>public function user()
{
    return $this->belongsTo(User::class,'username') ;
}

public function post()
{
    return $this->belongsTo(Post::class,'post_id');
}
</code>```

Body:
I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code:
Post.php

    class Post extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['title','created_at','username','image'];
    public function user()
    {
      return $this->belongsTo(User::class,'username');
    }
    public function votes()
    {
      //Quick note: Id refers to the post id.
      return $this->hasMany(PostVotes::class,'post_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class,'post_id');
    }
}

User.php

class User extends Model implements Authenticatable
{
  use AuthenticableTrait;
  protected $primaryKey = 'username';
  public $incrementing = false;
  public $timestamps = false;
  protected $fillable = ['username','email','password','created_at','avatar','about'];
  // Gets avatar to display on navbar.
  public function posts()
  {
    return $this->hasMany(Post::class,'username');
  }
  public function comments()
  {
    return $this->hasMany(Comment::class,'username');
  }
  public static function getAvatar()
  {
     return self::Where('username', '=', Session::get('username'))->value('avatar');
  }

}

Comment.php

    class Comment extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['comment','created_at','post_id','username'];
    public function user()
    {
        $this->belongsTo(User::class,'username') ;
    }
    public function post()
    {
        $this->belongsTo(Post::class,'post_id');
    }
}
public function view($post_id)
   {
      $post = Post::with('comments')->findOrFail($post_id);
      return view('posts.view',compact('post'));
   }
  @foreach($post->comments as $comment)
 // null
 {{dd($comment->user())}}
@endforeach

Body:
Use missed the return keyword

public function user()
{
    return $this->belongsTo(User::class,'username') ;
}

public function post()
{
    return $this->belongsTo(Post::class,'post_id');
}


问:
How to enable all the disable rows in jQuery
I'm new to jQuery and I'm confuse how to enable all the rows that I disabled. I was able to make it disable but I don't know how to enable all the rows again. I have a code here, but what happens is that at first all rows are disabled. But when I try to click the tr that is responsible for enabling all disabled rows nothing happens.

HTML

```<code><tr class ="${fn:substring(monthInfo.month, 0, 3)}">
    <c:if test="${stat.first}">
        <td class="monthName" rowspan="6" value = "${fn:substring(monthInfo.month, 0, 3)}">
         <div class="vertical-text">
           ${fn:substring(monthInfo.month, 0, 3)}
          </div>
         </td>
       </c:if>
       <td><img class="editButt" src="resources/images/edit.png" href="#"/></td>
       <td>${weekInfo.weekStart}</td>
       <td>${weekInfo.weekEnd}</td>
       <c:forEach items="${weekInfo.weeklyData}" var="week" >
            <td><input type="text" name="cell" class="hours" maxlength="2" value="${week}"></td>
        </c:forEach>
        <td class="weekTotal ibm-bgcolor-green-10 ">${weekInfo.totalHrs}</td>
        <td class="holidayTotal">${weekInfo.totalHo}</td>
        <td class="vacationTotal">${weekInfo.totalVl}</td>
        <td class="sickTotal">${weekInfo.totalSl}</td>
        <td><input type="text" name="cell" class="remarks" value="${weekInfo.remarks}"></td>
      </tr>
</code>```

jQuery

```<code>function disableRows(){
    $("#test1table tbody tr").each(function() {
        $(this).find('input:text').prop('disabled', true);
    });
}

$(document).ready(function() {
  calculateTargetHours();
  calculateActualHours();
  calculateUtilization();
  disableRows();
  $(".hours").blur(function() {
    checkValidInput($(this));
    calculateActualHours();
  });
  $('.editButt').click(function(){
      disableRows();
      $(this).closest('tr').find('input:text').prop('disabled', false);
  });
  $('.monthName').click(function(){
     disableRows();
     var className = $(this).closest('tr').find('td:first').text();
     alert(className);
     $('.'+className).find('input:text').prop('disabled', false);
    });
  });
</code>```

答: I just added .trim to after .text() so that all unnecessary characters</p>

Body:
I'm new to jQuery and I'm confuse how to enable all the rows that I disabled. I was able to make it disable but I don't know how to enable all the rows again. I have a code here, but what happens is that at first all rows are disabled. But when I try to click the tr that is responsible for enabling all disabled rows nothing happens.

HTML

    <c:if test="${stat.first}">

           ${fn:substring(monthInfo.month, 0, 3)}

       </c:if>

       ${weekInfo.weekStart}
       ${weekInfo.weekEnd}
       <c:forEach items="${weekInfo.weeklyData}" var="week" >
            <input type="text" name="cell" class="hours" maxlength="2" value="${week}">
        </c:forEach>
        ${weekInfo.totalHrs}
        ${weekInfo.totalHo}
        ${weekInfo.totalVl}
        ${weekInfo.totalSl}
        <input type="text" name="cell" class="remarks" value="${weekInfo.remarks}">

jQuery

function disableRows(){
    $("#test1table tbody tr").each(function() {
        $(this).find('input:text').prop('disabled', true);
    });
}

$(document).ready(function() {
  calculateTargetHours();
  calculateActualHours();
  calculateUtilization();
  disableRows();
  $(".hours").blur(function() {
    checkValidInput($(this));
    calculateActualHours();
  });
  $('.editButt').click(function(){
      disableRows();
      $(this).closest('tr').find('input:text').prop('disabled', false);
  });
  $('.monthName').click(function(){
     disableRows();
     var className = $(this).closest('tr').find('td:first').text();
     alert(className);
     $('.'+className).find('input:text').prop('disabled', false);
    });
  });