问:
How to calculate the time span in Tcl using clock commands
I need to calculate the time difference between two periods of a day in a 24:00 hr format clock using Tcl.

Let's say my start time is 06:30:00 in the morning and end time is 18:30:00 in the evening. I've tried the following in using Active Tcl 8.5 and 8.6 in windows.

```<code>set morn [clock scan 06:30:00 -format %H:%M:%S]
set even [clock scan 18:30:00 -format %H:%M:%S]
set diff [clock format [expr $even - $morn ] -format %H:%M:%S]
</code>```

The answer is supposed to be 12:00:00 which is the actual difference but, I get the answer as 17:30:00 which is totally confusing.

I presume that the GMT time difference of 05:30:00 is being added to the difference as I'm in a GMT+5:30 time zone (IST).

How do I get the exact difference?

答:
The clock command doesn't have anything in it to convert time intervals into human-readable form, as it focuses on handling time instants.

You're correct that the timezone you're in caused that time interval to come out strange. Passing the -gmt 1 option would have helped a bit, but only until you got a time interval of 24 hours or more. At that point, it would have looped round and looked very strange.

The way to deal with this is to do the formatting directly. This isn't very hard.

```<code>proc formatTimeInterval {intervalSeconds} {
    # *Assume* that the interval is positive
    set s [expr {$intervalSeconds % 60}]
    set i [expr {$intervalSeconds / 60}]
    set m [expr {$i % 60}]
    set i [expr {$i / 60}]
    set h [expr {$i % 24}]
    set d [expr {$i / 24}]
    return [format "%+d:%02d:%02d:%02d" $d $h $m $s]
}
</code>```

```<code>puts [formatTimeInterval [expr {$even - $morn}]]
#==> +0:12:00:00
</code>```

Body:
I need to calculate the time difference between two periods of a day in a 24:00 hr format clock using Tcl.

Let's say my start time is 06:30:00 in the morning and end time is 18:30:00 in the evening. I've tried the following in using Active Tcl 8.5 and 8.6 in windows.

set morn [clock scan 06:30:00 -format %H:%M:%S]
set even [clock scan 18:30:00 -format %H:%M:%S]
set diff [clock format [expr $even - $morn ] -format %H:%M:%S]

The answer is supposed to be 12:00:00 which is the actual difference but, I get the answer as 17:30:00 which is totally confusing.

I presume that the GMT time difference of 05:30:00 is being added to the difference as I'm in a GMT+5:30 time zone (IST).

How do I get the exact difference?

Body:
The clock command doesn't have anything in it to convert time intervals into human-readable form, as it focuses on handling time instants.

You're correct that the timezone you're in caused that time interval to come out strange. Passing the -gmt 1 option would have helped a bit, but only until you got a time interval of 24 hours or more. At that point, it would have looped round and looked very strange.

The way to deal with this is to do the formatting directly. This isn't very hard.

proc formatTimeInterval {intervalSeconds} {
    # *Assume* that the interval is positive
    set s [expr {$intervalSeconds % 60}]
    set i [expr {$intervalSeconds / 60}]
    set m [expr {$i % 60}]
    set i [expr {$i / 60}]
    set h [expr {$i % 24}]
    set d [expr {$i / 24}]
    return [format "%+d:%02d:%02d:%02d" $d $h $m $s]
}

puts [formatTimeInterval [expr {$even - $morn}]]
#==> +0:12:00:00


来源: stackexchange

问:
public HttpResponseMessage Post([FromBody]product pro)
I have this controller which I have Post Method.. but this method doesn't insert the value in database.. I can't resolve this.. need help

```<code>public HttpResponseMessage Post([FromBody]product pro)
{
        try
        {
            using (project_smartEntities entities = new project_smartEntities())
            {
                entities.products.Add(pro);
                entities.SaveChanges();

                var message = Request.CreateResponse(HttpStatusCode.Created, pro);
                message.Headers.Location = new Uri(Request.RequestUri + pro.product_id.ToString());
                return message;
            }

        }

        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
}
</code>```

Host: localhost:52442 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64;
  rv:53.0) Gecko/20100101 Firefox/53.0 Accept: application/json
  Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate
  Connection: keep-alive Upgrade-Insecure-Requests: 1 Content-Type:
  application/json

I want to insert these values in my product table

{"product_name":Maria
  B","barcode":123456789,"expiry_dates":"2022-05-12T00:00:00","unit":"3pc","tax":500.0,"cost":8000.0,"size":"Medium","quantity":2,"category_id":7,"locations":[],"product_category":null,"purchase_line":[],"sales_line":[]}

答: You can check if there are any constraints on Product Table in Db if  entities.SaveChanges(); is failing.

ContentLicense: CC BY-SA 3.0

Body:
I have this controller which I have Post Method.. but this method doesn't insert the value in database.. I can't resolve this.. need help

public HttpResponseMessage Post([FromBody]product pro)
{
        try
        {
            using (project_smartEntities entities = new project_smartEntities())
            {
                entities.products.Add(pro);
                entities.SaveChanges();

                var message = Request.CreateResponse(HttpStatusCode.Created, pro);
                message.Headers.Location = new Uri(Request.RequestUri + pro.product_id.ToString());
                return message;
            }

        }

        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
}

Host: localhost:52442 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64;
  rv:53.0) Gecko/20100101 Firefox/53.0 Accept: application/json
  Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate
  Connection: keep-alive Upgrade-Insecure-Requests: 1 Content-Type:
  application/json

I want to insert these values in my product table

{"product_name":Maria
  B","barcode":123456789,"expiry_dates":"2022-05-12T00:00:00","unit":"3pc","tax":500.0,"cost":8000.0,"size":"Medium","quantity":2,"category_id":7,"locations":[],"product_category":null,"purchase_line":[],"sales_line":[]}


问:
infinite scroll in React + Meteor
I'm using Meteor with React. I cannot implement infinite scrolling. I have tried different npm and Meteor packages and it's still not working. "createContainer" subscribes to the whole dataset of "links", which is then rendered in the app. How can subscribe to just 9 entries and load more whenever a user is at the end of the page?
I have spent the whole day on it, please help me!</p>

```<code>class DealsList extends Component {

    renderList() {
        return this.props.links.map(link => {
        const url = `/travels/${link._id}`;

        return (
            <div className="col-md-4" key={link._id}>
            <Link  to={url} id={link._id}>
                <div className="thumbnail">

                <div className="imageProp">
                    <div className="caption readMore">SHOW DEAL <span className="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></div>
                    <img src={link.image} alt="Just another travel deal" />
                </div>

                <div className="caption">
                    <h4>{link.title}</h4>
                    {/*<p className="card-description"><strong>Bootstrap Thumbnail</strong> Customization Example. Here are customized <strong>bootstrap cards</strong>. We just apply some box shadow and remove border radius.</p>
                    <p><a href="#" className="btn btn-primary" role="button">Button</a></p>*/}
                </div>

                </div>
            </Link>
            </div>

        );
        });
    }

    render() {

        return (
          <div>
          <FirstCarousel />
          <div className="container-fluid containerPadding cards-row">
              <div className="row">

              <div className="col-lg-12">
                  <div className="row grid">
                      {this.renderList()}
                  </div>
              </div>

              </div>

          </div>
          </div>
        );
    }
}

export default createContainer(() => {

Meteor.subscribe('links');

return { links: Links.find({}).fetch() };
}, DealsList);
</code>```

答:
There's a good chapter about pagination and infinite scroll in the Meteor Guide, you should check it out. In essence, what you need to do, is give your lists publication a parameter to specify the number of items that will be fetched, like so:

```<code>Meteor.publish('links', (limit) => {
  const options = {
    sort: {time: -1}, // Or some other relevant sorting
    limit
  };
  return Links.find({}, options);
};
</code>```

Now your the parent component that contains your DealsList, you need to do two things: 1. Hold a state variable for the limit, with some appropriate initial value, that is passed down to your DealsList. 2. Increase this limit by some amount when the user reaches the bottom of the page. You can find multiple guides on how to do that if you search, for example you can look at this.

Once those are done, you can simply use the limit parameter in the subscription like this:

```<code>export default createContainer((props) => {
  Meteor.subscribe('links', props.limit);
  return { links: Links.find({}).fetch() };
}, DealsList);
</code>```

Title: infinite scroll in React + Meteor

Body:
I'm using Meteor with React. I cannot implement infinite scrolling. I have tried different npm and Meteor packages and it's still not working. "createContainer" subscribes to the whole dataset of "links", which is then rendered in the app. How can subscribe to just 9 entries and load more whenever a user is at the end of the page?
I have spent the whole day on it, please help me!

class DealsList extends Component {

    renderList() {
        return this.props.links.map(link => {
        const url = `/travels/${link._id}`;

        return (

            <Link  to={url} id={link._id}>

SHOW DEAL

{link.title}

                    {/*
Bootstrap Thumbnail Customization Example. Here are customized bootstrap cards. We just apply some box shadow and remove border radius.

Button
*/}

            </Link>

        );
        });
    }

    render() {

        return (

          <FirstCarousel />

                      {this.renderList()}

        );
    }
}

export default createContainer(() => {

Meteor.subscribe('links');

return { links: Links.find({}).fetch() };
}, DealsList);

Body:
There's a good chapter about pagination and infinite scroll in the Meteor Guide, you should check it out. In essence, what you need to do, is give your lists publication a parameter to specify the number of items that will be fetched, like so:

Meteor.publish('links', (limit) => {
  const options = {
    sort: {time: -1}, // Or some other relevant sorting
    limit
  };
  return Links.find({}, options);
};

Now your the parent component that contains your DealsList, you need to do two things: 1. Hold a state variable for the limit, with some appropriate initial value, that is passed down to your DealsList. 2. Increase this limit by some amount when the user reaches the bottom of the page. You can find multiple guides on how to do that if you search, for example you can look at this.

Once those are done, you can simply use the limit parameter in the subscription like this:

export default createContainer((props) => {
  Meteor.subscribe('links', props.limit);
  return { links: Links.find({}).fetch() };
}, DealsList);

ContentLicense: CC BY-SA 4.0


问:
Access protected const from base class in attribute
I have a base class with a constant

```<code>public class TestClassBase
{
    protected const string Foo = "Bar";
}
</code>```

which I can consume in C# as follows

```<code>[Trait(Foo, "")]
public class MyCSharpTestClass : TestClassBase
{
}
</code>```

How do I consume it in a F# class? Foo is not recognized by the compiler.

```<code>[<Trait(Foo, "")>]
type MyFSharpTestClass() =
  inherit TestClassBase()
</code>```

The error I get is: FS0267 This is not a valid constant expression or custom attribute value.

EDIT

[<Trait(Foo, "")>] yields: FS0039 The value or constructor 'Foo' is not defined. Maybe you want one of the following: floor.

[<Trait(this.Foo, "")>] yields FS0039 The value, namespace, type or module 'this' is not defined. Maybe you want one of the following: ThisAssembly.

[<Trait(base.Foo, "")>] yields FS0039 The value, namespace, type or module 'base' is not defined. Maybe you want one of the following: Base.

[<Trait(TestClassBase.Foo, "")>] yields FS0039 The field, constructor or member 'Foo' is not defined.

答: This issue was classified as a bug on the Github site.</p>

Body:
I have a base class with a constant

public class TestClassBase
{
    protected const string Foo = "Bar";
}

which I can consume in C# as follows

[Trait(Foo, "")]
public class MyCSharpTestClass : TestClassBase
{
}

How do I consume it in a F# class? Foo is not recognized by the compiler.

[<Trait(Foo, "")>]
type MyFSharpTestClass() =
  inherit TestClassBase()

The error I get is: FS0267 This is not a valid constant expression or custom attribute value.

EDIT

[<Trait(Foo, "")>] yields: FS0039 The value or constructor 'Foo' is not defined. Maybe you want one of the following: floor.

[<Trait(this.Foo, "")>] yields FS0039 The value, namespace, type or module 'this' is not defined. Maybe you want one of the following: ThisAssembly.

[<Trait(base.Foo, "")>] yields FS0039 The value, namespace, type or module 'base' is not defined. Maybe you want one of the following: Base.

[<Trait(TestClassBase.Foo, "")>] yields FS0039 The field, constructor or member 'Foo' is not defined.


答:
You should refactor to the more recent api abstractions of web api 2

```<code>public IHttpActionResult Post([FromBody]product pro) {
    try {
        using (var entities = new project_smartEntities()) {
            entities.products.Add(pro);
            entities.SaveChanges();
            return CreatedAtRoute(
                routeName: "DefaultApi",
                routeValues: new { id = pro.product_id, controller = "products" }, //assuming route template "api/{controller}/{id}" other properties
                content: pro);
        }
    } catch (Exception ex) {
        return BadRequest();
    }
}
</code>```

Since there are no indications of attribute routing the assumption is that you are using the default convention-based route DefaultApi

To debug why entity is not saving put a break point in the exception handler and review the cause of the exception.

Title: public HttpResponseMessage Post([FromBody]product pro)

Body:
You should refactor to the more recent api abstractions of web api 2

public IHttpActionResult Post([FromBody]product pro) {
    try {
        using (var entities = new project_smartEntities()) {
            entities.products.Add(pro);
            entities.SaveChanges();
            return CreatedAtRoute(
                routeName: "DefaultApi",
                routeValues: new { id = pro.product_id, controller = "products" }, //assuming route template "api/{controller}/{id}" other properties
                content: pro);
        }
    } catch (Exception ex) {
        return BadRequest();
    }
}

Since there are no indications of attribute routing the assumption is that you are using the default convention-based route DefaultApi

To debug why entity is not saving put a break point in the exception handler and review the cause of the exception.


问:
Advanced boosting of angular digest loop
I'm researching my options for boosting angular's digest loop.

I have a fairly complex app with tens of thousands active watchers at any given time.

As part of the functionality of the app I'm registering on scroll events (and handling them in an animation frame), so the digest is basically executed on each scroll, which results in an occasional drop in fps.

I've reduced the watchers count by one-time bindings and I'm now left with a few thousands watchers.

Currently I'm attempting to write a directive to suspend all watchers of out of viewport elements.

So I started playing with angular internals and came up with the following directive:

```<code>app.directive('ngSuspendable', function () {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attr) {
            var _watchersMap = {};
            var _suspended = true;
            suspendWatchersTree();

            function suspendWatchersTreeRecursive(currentScope, includeSiblings) {
                while (currentScope != null) {
                    if ((currentScope.$$watchers != null) &&
                        (currentScope.$$watchers.length > 0) &&
                        (typeof _watchersMap[currentScope.$id] == "undefined")) {
                        _watchersMap[currentScope.$id] = currentScope.$$watchers;
                        currentScope.$$watchers = [];
                    }

                    if (currentScope.$$childHead != null) {
                        suspendWatchersTreeRecursive(currentScope.$$childHead, true);
                    }

                    if (includeSiblings) {
                        currentScope = currentScope.$$nextSibling;
                    }

                    else {
                        currentScope = null;
                    }
                }
            }

            function unsuspendWatchersTreeRecursive(currentScope, includeSiblings) {
                while (currentScope != null) {
                    if ((typeof _watchersMap[currentScope.$id] != "undefined") &&
                        (_watchersMap[currentScope.$id].length > 0)) {
                        if ((currentScope.$$watchers != null) &&
                            (currentScope.$$watchers.length > 0)) {
                            currentScope.$$watchers = currentScope.$$watchers.concat(_watchersMap[currentScope.$id]);
                        }

                        else {
                            currentScope.$$watchers = _watchersMap[currentScope.$id];
                        }
                    }

                    if (currentScope.$$childHead != null) {
                        unsuspendWatchersTreeRecursive(currentScope.$$childHead, true);
                    }

                    if (includeSiblings) {
                        currentScope = currentScope.$$nextSibling;
                    }

                    else {
                        currentScope = null;
                    }
                }
            }

            function suspendWatchersTree() {
                suspendWatchersTreeRecursive(scope, false);
            }

            function unsuspendWatchersTree() {
                unsuspendWatchersTreeRecursive(scope, false);
            }

            scope.inView = function(evnt, model, htmlElementId, triggeringEvent, isInView, inViewPart) {
                if (!isInView) {
                    suspendWatchersTree();
                    _suspended = true;
                }

                if ((isInView) && (_suspended)) {
                    unsuspendWatchersTree();
                    _watchersMap = {};
                    _suspended = false;
                }
            }
        }
    }
});
</code>```

Upon initialization this directive removes all watchers from current scope and all child scopes (not sure if it captures also isolated scopes).
Then, when the element is in view it adds back the watchers, and removes them when out of view.

I know that it doesn't necessarily captures all watchers, as some watchers might be added post linking, but that seems negligible, and they will be removed once the element comes in view and out of view again. If I could somehow hook to the watchers addition and add them to the map when suspsended that could be nice but I guess its not a must.

This seems to be working well but I'm not sure what are the caveats for such approach. I'm uncomfortable with playing around with angular internals and messing up things and reaching unstable conditions.

Any ideas and remarks will be greatly appreciated.

答:
I've updated the above code with the most recent changes.
Further testing showed it works fairly well, some watches might not be suspended at initialization but that's a price I can live with. It greatly enhanced my digest loop and boosted the app performance by removing unrequired watches for out of viewport elements.</p>

Body:
I'm researching my options for boosting angular's digest loop.

I have a fairly complex app with tens of thousands active watchers at any given time.

As part of the functionality of the app I'm registering on scroll events (and handling them in an animation frame), so the digest is basically executed on each scroll, which results in an occasional drop in fps.

I've reduced the watchers count by one-time bindings and I'm now left with a few thousands watchers.

Currently I'm attempting to write a directive to suspend all watchers of out of viewport elements.

So I started playing with angular internals and came up with the following directive:

app.directive('ngSuspendable', function () {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attr) {
            var _watchersMap = {};
            var _suspended = true;
            suspendWatchersTree();

            function suspendWatchersTreeRecursive(currentScope, includeSiblings) {
                while (currentScope != null) {
                    if ((currentScope.$$watchers != null) &&
                        (currentScope.$$watchers.length > 0) &&
                        (typeof _watchersMap[currentScope.$id] == "undefined")) {
                        _watchersMap[currentScope.$id] = currentScope.$$watchers;
                        currentScope.$$watchers = [];
                    }

                    if (currentScope.$$childHead != null) {
                        suspendWatchersTreeRecursive(currentScope.$$childHead, true);
                    }

                    if (includeSiblings) {
                        currentScope = currentScope.$$nextSibling;
                    }

                    else {
                        currentScope = null;
                    }
                }
            }

            function unsuspendWatchersTreeRecursive(currentScope, includeSiblings) {
                while (currentScope != null) {
                    if ((typeof _watchersMap[currentScope.$id] != "undefined") &&
                        (_watchersMap[currentScope.$id].length > 0)) {
                        if ((currentScope.$$watchers != null) &&
                            (currentScope.$$watchers.length > 0)) {
                            currentScope.$$watchers = currentScope.$$watchers.concat(_watchersMap[currentScope.$id]);
                        }

                        else {
                            currentScope.$$watchers = _watchersMap[currentScope.$id];
                        }
                    }

                    if (currentScope.$$childHead != null) {
                        unsuspendWatchersTreeRecursive(currentScope.$$childHead, true);
                    }

                    if (includeSiblings) {
                        currentScope = currentScope.$$nextSibling;
                    }

                    else {
                        currentScope = null;
                    }
                }
            }

            function suspendWatchersTree() {
                suspendWatchersTreeRecursive(scope, false);
            }

            function unsuspendWatchersTree() {
                unsuspendWatchersTreeRecursive(scope, false);
            }

            scope.inView = function(evnt, model, htmlElementId, triggeringEvent, isInView, inViewPart) {
                if (!isInView) {
                    suspendWatchersTree();
                    _suspended = true;
                }

                if ((isInView) && (_suspended)) {
                    unsuspendWatchersTree();
                    _watchersMap = {};
                    _suspended = false;
                }
            }
        }
    }
});

Upon initialization this directive removes all watchers from current scope and all child scopes (not sure if it captures also isolated scopes).
Then, when the element is in view it adds back the watchers, and removes them when out of view.

I know that it doesn't necessarily captures all watchers, as some watchers might be added post linking, but that seems negligible, and they will be removed once the element comes in view and out of view again. If I could somehow hook to the watchers addition and add them to the map when suspsended that could be nice but I guess its not a must.

This seems to be working well but I'm not sure what are the caveats for such approach. I'm uncomfortable with playing around with angular internals and messing up things and reaching unstable conditions.

Any ideas and remarks will be greatly appreciated.


问:
Registration button enabled only if mail is correct
I have a form for registration with Username, Email, Password and Password confirm with a disabled Submit button. I would like to enable the button only if the email is correct. In my case I allow only email with "@studio.unibo.it" and not other email domains (the prefix email control is done in Javascript). And if a user change, after that the button in enabled, the email, the button must be again disabled. So, only if the user insert an e-mail like peter@studio.unibo.it can be registered.
I already have "required" key in each form fields.

It is possible to do this in javascript or with a php control?

Here is the code:
HTML Form:

```<code><form action="registration.php" method="post" id="fileForm" role="form">
    <div class="form-group">
        <label for="firstname"> Username: </label>
        <input class="form-control" type="text" name="Input_Username" id = "txt" onkeyup = "Validate(this)" placeholder="Username" required />
        <div id="errFirst"></div>
    </div>

    <div class="form-group">
        <label for="email"> Email: </label>
        <input class="form-control" type="text" name="Input_Email" id = "email"  onchange="email_validate(this.value);" placeholder="nome.cognomeX@studio.unibo.it" required />
        <div class="status" id="status"></div>
    </div>

    <div class="form-group">
        <label for="password"> Password: </label>
        <input name="password" type="password" class="form-control inputpass" minlength="4" maxlength="16"  id="pass1" placeholder="Password" required /> </p>

        <label for="password"> Password Confirm: </label>
        <input name="Input_Password" type="password" class="form-control inputpass" minlength="4" maxlength="16" placeholder="Enter again to validate"  id="pass2" onkeyup="checkPass(); return false;" required />
        <span id="confirmMessage" class="confirmMessage"></span>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-default" disabled>Submit</button>
        <button type="reset" class="btn btn-default" value="Reset">Reset</button>
    </div>
</form><!-- ends register form -->
</code>```

Javascript script for password check and email prefix check

```<code> function checkPass()
    {
        //Store the password field objects into variables ...
        var pass1 = document.getElementById('pass1');
        var pass2 = document.getElementById('pass2');
        //Store the Confimation Message Object ...
        var message = document.getElementById('confirmMessage');

        var goodColor = "#66cc66";
        var badColor = "#ff6666";

        if(pass1.value == pass2.value){

            pass2.style.backgroundColor = goodColor;
            message.style.color = goodColor;
            message.innerHTML = "Le password combaciano"
        }else{
            pass2.style.backgroundColor = badColor;
            message.style.color = badColor;
            message.innerHTML = "Le password non combaciano"
        }
    }

    // validates text only
    function Validate(txt) {
        txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
    }
    // validate email
    function email_validate(email)
    {
    var regMail = /^([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@(studio.unibo.it)$/; //ammesse solo le mail che terminano per @studio.unibo.it !!!

        if(regMail.test(email) == false)
        {
        document.getElementById("status").innerHTML    = "<span class='warning'>L'indirizzo email non è valido.</span>";
        }
        else
        {
        document.getElementById("status").innerHTML = "<span class='valid'>L'indirizzo email è valido.</span>";
        }
    }
</code>```

答:
```<code>var email = ...; //get your email input
var submit = ...;//get your submit button
email.onchange = function() {
    submit.disabled = !validate(email.value); //validate - your function validates email address
}
</code>```

Body:
I have a form for registration with Username, Email, Password and Password confirm with a disabled Submit button. I would like to enable the button only if the email is correct. In my case I allow only email with "@studio.unibo.it" and not other email domains (the prefix email control is done in Javascript). And if a user change, after that the button in enabled, the email, the button must be again disabled. So, only if the user insert an e-mail like peter@studio.unibo.it can be registered.
I already have "required" key in each form fields.

It is possible to do this in javascript or with a php control?

Here is the code:
HTML Form:

<form action="registration.php" method="post" id="fileForm" role="form">

         Username:
        <input class="form-control" type="text" name="Input_Username" id = "txt" onkeyup = "Validate(this)" placeholder="Username" required />

         Email:
        <input class="form-control" type="text" name="Input_Email" id = "email"  onchange="email_validate(this.value);" placeholder="nome.cognomeX@studio.unibo.it" required />

         Password:
        <input name="password" type="password" class="form-control inputpass" minlength="4" maxlength="16"  id="pass1" placeholder="Password" required />

         Password Confirm:
        <input name="Input_Password" type="password" class="form-control inputpass" minlength="4" maxlength="16" placeholder="Enter again to validate"  id="pass2" onkeyup="checkPass(); return false;" required />

        <button type="submit" class="btn btn-default" disabled>Submit</button>
        <button type="reset" class="btn btn-default" value="Reset">Reset</button>

</form>

Javascript script for password check and email prefix check

 function checkPass()
    {
        //Store the password field objects into variables ...
        var pass1 = document.getElementById('pass1');
        var pass2 = document.getElementById('pass2');
        //Store the Confimation Message Object ...
        var message = document.getElementById('confirmMessage');

        var goodColor = "#66cc66";
        var badColor = "#ff6666";

        if(pass1.value == pass2.value){

            pass2.style.backgroundColor = goodColor;
            message.style.color = goodColor;
            message.innerHTML = "Le password combaciano"
        }else{
            pass2.style.backgroundColor = badColor;
            message.style.color = badColor;
            message.innerHTML = "Le password non combaciano"
        }
    }

    // validates text only
    function Validate(txt) {
        txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
    }
    // validate email
    function email_validate(email)
    {
    var regMail = /^([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@(studio.unibo.it)$/; //ammesse solo le mail che terminano per @studio.unibo.it !!!

        if(regMail.test(email) == false)
        {
        document.getElementById("status").innerHTML    = "L'indirizzo email non è valido.";
        }
        else
        {
        document.getElementById("status").innerHTML = "L'indirizzo email è valido.";
        }
    }


问:
How number of items in IN clause relates to index usage
I'm trying to optimize a query but I'm seeing a weird behavior I don't understand.

I have a table contains almost 2 million records, with an index on column "status_code" which is tinyint.

When I call the query with 10 numbers in In clause, mysql do a full table scan

```<code>select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9,10);
</code>```

When I call it with 9 numbers in the IN clause, the index is used.

```<code>select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9);
</code>```

Note: Number of rows here is '9' although the query returns only 1 row.

I'm using Amazon RDS, I need to understand why is this behavior, and if there is any kind of configuration that controls this.

答:
Using index is driven by stats. I don't have precise info for MySQL, but PostgreSQL will go seq-scan if calculated result will be bigger then 2% of the table. In your case it can be other value, but mechanism is the same.

DB uses stats to see if your query returns more then small percentage of the table - in that case - sequence read is used. MS SQL Server will not use index if table is smaller then 5MB - that is faster. By that I mean - it is typical, and all RDBMS goes that way. Sometimes that fails - as you can see.

What to do with it? You can analyze table to update stats. You can use hint use_stat_tables to turn off stored stats... In PostgreSQL you could change histograms for the table to have more precise results, but I don't know anything like that for MySQL. Also there are many drivers, and this particular problem can be solved at this level.

Providing explains would not change much here. MySQL has poor explain, also nature of the problem is quite obvious.

As a side note. That is not related to RDS - that is typical problem for RDBMS. Different systems deals with it in different way, and MySQL is not a leader here.

Body:
I'm trying to optimize a query but I'm seeing a weird behavior I don't understand.

I have a table contains almost 2 million records, with an index on column "status_code" which is tinyint.

When I call the query with 10 numbers in In clause, mysql do a full table scan

select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9,10);

When I call it with 9 numbers in the IN clause, the index is used.

select * from `table` as t
where t.code in (1,2,3,4,5,6,7,8,9);

Note: Number of rows here is '9' although the query returns only 1 row.

I'm using Amazon RDS, I need to understand why is this behavior, and if there is any kind of configuration that controls this.


问:
Signing HTTP request in Volley
Is there a way to sign http request in Volley?

As far as I understand SSL connection.

client opens connection

server responds with cert that contains public key

client stores server's public key

client creates request and signs it with server's public key

server verifies request using own private key

If server sends the response, client verifies response with server's public key?

How does ssl pinning fits in this process?

答:
No, it does not work this way. There is no signing of the HTTP request. In short:

client establishes a TLS connection to the server which involves

the server sending a certificate to the client

the client validating this certificate, i.e. that it is trusted, matches the servers name and that the server owns the private key belonging to the certificate. Certificate pinning will be checked in this step too, i.e. if the certificate (or its public key) matches the expected value.

followed by the key exchange which results in keys for encryption and message protection

from then on all data exchanged is encrypted and protected against modification

TLS itself has no idea of HTTP, i.e. does not know what a HTTP request and response is. It only sees a data stream which it protects. HTTP request and response are part of this stream and are thus protected but there is no specific signing of the HTTP request or response.

Title: Signing HTTP request in Volley


问:
Closing a task and checking if its not running before starting a new one
I have an application, when a button is clicked, it starts a task which connects to a specific bluetooth device and then have a continuous stream of data coming in and going out. When the user clicks on the button again, I'd like it to check, if the task I created the first time is running, and if it is, terminate the task.
I was thinking of cancelling the task with CancellationToken, but I can't get passed of checking if the task is running or not. Right now, when I click the button the first time, it creates the task and does everything nicely. When I click the button the second time, it still goes past the if statement, thinking the task isn't running and tries to create the task again and connect the bluetooth device again the then gets stuck.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
using System.Threading;

namespace app
{
class Bluetooth
{
    Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
    public BluetoothClient client;
    BluetoothDeviceInfo[] devices;
    private Task connectionTask;

    private void Connect() //This is called from button click
    {
        if (connectionTask == null ||
            connectionTask.IsCompleted == false &&
            connectionTask.Status != TaskStatus.Running &&
            connectionTask.Status != TaskStatus.WaitingToRun &&
            connectionTask.Status != TaskStatus.WaitingForActivation)
           {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
           }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {
        //Do Bluetooth connection stuff here which, once connected, will stay in an infinite while loop.

    }
 }
}
</code>```

Ive changed the code to the following, but still only get Client connected messagebox. As I understand, because I have Thread.Sleep(100000) the Task should still count as running?

```<code>class Bluetooth
{

    private Task connectionTask;

    public void bluetooth()
    {
        Connect();
    }

    private void Connect()
    {

        if (connectionTask == null ||
        connectionTask.IsCompleted == false &&
        connectionTask.Status != TaskStatus.Running &&
        connectionTask.Status != TaskStatus.WaitingToRun &&
        connectionTask.Status != TaskStatus.WaitingForActivation)
        {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
        }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {

        var form1 = new Form1();
        form1.message("Client connected", 1);
        Thread.Sleep(100000);

    }
}
}
</code>```

答:
As @JanDotNet stated if you initialise the connectionTask variable before the if statement it will not work.

You will have to rewrite your if statement to the following.

```<code>if (connectionTask == null ||
    connectionTask.IsCompleted == false &&
    connectionTask.Status != TaskStatus.Running &&
    connectionTask.Status != TaskStatus.WaitingToRun &&
    connectionTask.Status != TaskStatus.WaitingForActivation)
{
    connectionTask = Task.Factory.StartNew(ConnectionTask);
}
</code>```

Body:
I have an application, when a button is clicked, it starts a task which connects to a specific bluetooth device and then have a continuous stream of data coming in and going out. When the user clicks on the button again, I'd like it to check, if the task I created the first time is running, and if it is, terminate the task.
I was thinking of cancelling the task with CancellationToken, but I can't get passed of checking if the task is running or not. Right now, when I click the button the first time, it creates the task and does everything nicely. When I click the button the second time, it still goes past the if statement, thinking the task isn't running and tries to create the task again and connect the bluetooth device again the then gets stuck.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
using System.Threading;

namespace app
{
class Bluetooth
{
    Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
    public BluetoothClient client;
    BluetoothDeviceInfo[] devices;
    private Task connectionTask;

    private void Connect() //This is called from button click
    {
        if (connectionTask == null ||
            connectionTask.IsCompleted == false &&
            connectionTask.Status != TaskStatus.Running &&
            connectionTask.Status != TaskStatus.WaitingToRun &&
            connectionTask.Status != TaskStatus.WaitingForActivation)
           {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
           }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {
        //Do Bluetooth connection stuff here which, once connected, will stay in an infinite while loop.

    }
 }
}

Ive changed the code to the following, but still only get Client connected messagebox. As I understand, because I have Thread.Sleep(100000) the Task should still count as running?

class Bluetooth
{

    private Task connectionTask;

    public void bluetooth()
    {
        Connect();
    }

    private void Connect()
    {

        if (connectionTask == null ||
        connectionTask.IsCompleted == false &&
        connectionTask.Status != TaskStatus.Running &&
        connectionTask.Status != TaskStatus.WaitingToRun &&
        connectionTask.Status != TaskStatus.WaitingForActivation)
        {
            connectionTask = Task.Factory.StartNew(ConnectionTask);
        }

        else
        {
            var form1 = new Form1();
            form1.message("Client already connected", 3);
        }
    }

    private void ConnectionTask()
    {

        var form1 = new Form1();
        form1.message("Client connected", 1);
        Thread.Sleep(100000);

    }
}
}

Body:
As @JanDotNet stated if you initialise the connectionTask variable before the if statement it will not work.

You will have to rewrite your if statement to the following.

if (connectionTask == null ||
    connectionTask.IsCompleted == false &&
    connectionTask.Status != TaskStatus.Running &&
    connectionTask.Status != TaskStatus.WaitingToRun &&
    connectionTask.Status != TaskStatus.WaitingForActivation)
{
    connectionTask = Task.Factory.StartNew(ConnectionTask);
}


问:
Meaning of memoryTypes in Vulkan
I have used the Vulkan function vkGetPhysicalDeviceMemoryProperties to obtain the memory properties of a specific physical device, i.e. GPU.

I have printed out the returned values from this function (1st column from the left is their enumerated values. Based on this output, I can see there are 2 memory heaps and 11 memoryTypes.

```<code>  Memory:
  -memoryTypeCount: 11
  -memoryTypes[VK_MAX_MEMORY_TYPES]:
    -0, propertyFlags: 0, heapIndex: 1
    -1, propertyFlags: 0, heapIndex: 1
    -2, propertyFlags: 0, heapIndex: 1
    -3, propertyFlags: 0, heapIndex: 1
    -4, propertyFlags: 0, heapIndex: 1
    -5, propertyFlags: 0, heapIndex: 1
    -6, propertyFlags: 0, heapIndex: 1
    -7, propertyFlags: 1, heapIndex: 0
    -8, propertyFlags: 1, heapIndex: 0
    -9, propertyFlags: 6, heapIndex: 1
    -10, propertyFlags: 14, heapIndex: 1
  -memoryHeapCount: 2
  -memoryHeaps[VK_MAX_MEMORY_HEAPS]:
    -0, size: 6442450944, flags: 1
    -1, size: 25186016256, flags: 0
</code>```

Questions:

What does propertyFlags=0 mean ? I can't find it in Vulkan specification.

Does heapIndex=0 and 1 refer to the 1st or 2nd element of memoryHeaps?

What is the advantage of having multiple memoryTypes element? How do I use them in a Vulkan application?

答:
What does propertyFlags=0 means? I can't find it in Vulkan specification.

It means exactly what the Vulkan specification says that it means. This memory type:

is not DEVICE_LOCAL, so it doesn't represent fast device access.

is not HOST_VISIBLE, so you cannot read from/write to it directly from the CPU.

It's a memory type that represents a memory allocation that you cannot directly access, and the GPU won't have the fastest access to either.

Does heapIndex=0 and 1 refers to the 1st or 2nd element of memoryHeaps?

Vulkan is built on C and/or C++. All arrays are zero-based. So heapIndex 0 refers to the initial element in the memoryHeap array.

What is the advantage of having multiple memoryTypes element? How do I use them in a Vulkan application?

Vulkan is an explicit, low-level API. That means you need to make informed decisions about how your application handles things. You ask the hardware what is available, and you adjust your application to the hardware's various features.

The various memory types tell you the ways in which you can allocate memory from various heaps. These control how you can access that memory, as well as describe whether the GPU can access it fast or slow. For a specific use of memory, you must select the memory type most appropriate to that use.

Of course, there's also the fact that buffers and images have restrictions on which memory types they can be allocated from. These restrictions are based on the usage types for those objects (as well as the image format). So you need to check up-front which memory types the buffers and images you intend to use can be allocated through.

Now, why your implementation has multiple copies of the same memory type (memory types with the same flag and memory heap fields), I have no idea.

Title: Meaning of memoryTypes in Vulkan

Body:
I have used the Vulkan function vkGetPhysicalDeviceMemoryProperties to obtain the memory properties of a specific physical device, i.e. GPU.

I have printed out the returned values from this function (1st column from the left is their enumerated values. Based on this output, I can see there are 2 memory heaps and 11 memoryTypes.

  Memory:
  -memoryTypeCount: 11
  -memoryTypes[VK_MAX_MEMORY_TYPES]:
    -0, propertyFlags: 0, heapIndex: 1
    -1, propertyFlags: 0, heapIndex: 1
    -2, propertyFlags: 0, heapIndex: 1
    -3, propertyFlags: 0, heapIndex: 1
    -4, propertyFlags: 0, heapIndex: 1
    -5, propertyFlags: 0, heapIndex: 1
    -6, propertyFlags: 0, heapIndex: 1
    -7, propertyFlags: 1, heapIndex: 0
    -8, propertyFlags: 1, heapIndex: 0
    -9, propertyFlags: 6, heapIndex: 1
    -10, propertyFlags: 14, heapIndex: 1
  -memoryHeapCount: 2
  -memoryHeaps[VK_MAX_MEMORY_HEAPS]:
    -0, size: 6442450944, flags: 1
    -1, size: 25186016256, flags: 0

Questions:

What does propertyFlags=0 mean ? I can't find it in Vulkan specification.

Does heapIndex=0 and 1 refer to the 1st or 2nd element of memoryHeaps?

What is the advantage of having multiple memoryTypes element? How do I use them in a Vulkan application?


问:
Django: namespacing for flatpages?
So I am new to Django (and complete the 7 part tutorial) as well as read the flatpages app documentation.

At the end of which, whoever wrote the Django documentation gives a demonstration as to how one would retrieve all the flatpages:

```<code>{% load flatpages %}
{% get_flatpages as flatpages %}
<ul>
    {% for page in flatpages %}
        <li><a href="{{ page.url }}">{{ page.title }}</a></li>
    {% endfor %}
</ul>
</code>```

I now have flatpages working (e.g. if I go to /pages/my_flatpage/ the default template I have renders. as I have included url(r'^pages/', include('django.contrib.flatpages.urls')) in the urlpatterns.

So I am now in another app of mine and want to link to these flatpages. Using the code above I create the links. However, when I click on them, they do not render as they are routed to /my_flatpage/ rather than /pages/my_flatpage/.

So I tried including the url pattern in my app, but that didnt work. How can I get the to go to the right place?

答:
Since you're not hosting the pages directly at the root, the url attribute doesn't return the whole path. Instead you should use the URL reversing functionality as with any other object:

```<code>{% for page in flatpages %}
    <li><a href="{% url 'django.contrib.flatpages.views.flatpage' page.url %}">{{ page.title }}</a></li>
{% endfor %}
</code>```

Title: Django: namespacing for flatpages?

Body:
So I am new to Django (and complete the 7 part tutorial) as well as read the flatpages app documentation.

At the end of which, whoever wrote the Django documentation gives a demonstration as to how one would retrieve all the flatpages:

{% load flatpages %}
{% get_flatpages as flatpages %}

    {% for page in flatpages %}

{{ page.title }}

    {% endfor %}

I now have flatpages working (e.g. if I go to /pages/my_flatpage/ the default template I have renders. as I have included url(r'^pages/', include('django.contrib.flatpages.urls')) in the urlpatterns.

So I am now in another app of mine and want to link to these flatpages. Using the code above I create the links. However, when I click on them, they do not render as they are routed to /my_flatpage/ rather than /pages/my_flatpage/.

So I tried including the url pattern in my app, but that didnt work. How can I get the to go to the right place?

Body:
Since you're not hosting the pages directly at the root, the url attribute doesn't return the whole path. Instead you should use the URL reversing functionality as with any other object:

{% for page in flatpages %}
    <li><a href="{% url 'django.contrib.flatpages.views.flatpage' page.url %}">{{ page.title }}</a></li>
{% endfor %}


问:
Getting runtime error 1004 after putting error handler?
Why does this not suppress errors?

```<code>For i = 1 To Last_row

    On Error GoTo errorhandler1
    Set wkb = Workbooks.Open(Filename:=l)

    '' my code

errorhandler1:

next I
</code>```

This is what I get:

答:
Not sure why you can't bypass a file not found error...

Try using a sub function to return the open file (if found) instead?

```<code>Function GetWorkBook(ByVal sFullName As String, Optional ReadOnly As Boolean) As Workbook
    Dim sFile As String: sFile = Dir(sFullName)
    On Error Resume Next
    Set GetWorkBook = Workbooks(sFile)
    If GetWorkBook Is Nothing Then Set GetWorkBook = Workbooks.Open(sFullName, ReadOnly:=ReadOnly)
End Function
</code>```

Body:
Why does this not suppress errors?

For i = 1 To Last_row

    On Error GoTo errorhandler1
    Set wkb = Workbooks.Open(Filename:=l)

    '' my code

errorhandler1:

next I

This is what I get:

Body:
Not sure why you can't bypass a file not found error...

Try using a sub function to return the open file (if found) instead?

Function GetWorkBook(ByVal sFullName As String, Optional ReadOnly As Boolean) As Workbook
    Dim sFile As String: sFile = Dir(sFullName)
    On Error Resume Next
    Set GetWorkBook = Workbooks(sFile)
    If GetWorkBook Is Nothing Then Set GetWorkBook = Workbooks.Open(sFullName, ReadOnly:=ReadOnly)
End Function


问:
Swift 3 UISwitch in TableViewCell loses State when scrolling
That's weird: I just set up a new Single-View iOS Project and put a TableView into the Main.storyboard. In this TableView I put a TableViewCell and into this Cell, I put an UILabel and an UISwitch.
For this TableViewCell I created a CocoaTouchClass MyTableViewCell and set this for the TableViewCell's Class in Interfacebuilder.
I connected Outlets for the UILabel and UISwitch to MyTableViewCell, as well as an action for the switch.
Also I connected the TableView's dataSource and delegate to the ViewController.

So, as I think, basic stuff for setting up a table.

My ViewController looks like this:

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableData = [[String: Bool]]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for index in 1...40 {
        self.tableData.append([String(index): index%2 == 0])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
    let object = tableData[indexPath.row].first!

    cell.myLabel.text = object.key
    cell.mySwitch.setOn(object.value, animated: false)

    return cell
}
</code>```

}

So, I populate the Table with some Rows of Data and switch every second UISwitch to on.

The MyTableViewCell-Class is nothing special as well:

```<code>class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func switched(_ sender: UISwitch) {
    print("Switched: \(sender.isOn)")
}
</code>```

}

Ok, fire up the iOS-Simulator and I see the Table as expected. 40 Table-Lines don't fit on one screen, so the TableView makes itself scrollable.

Now: when I change the state of one UISwitch, and drag the TableView so the changed UISwitch gets out of view and then drag the TableView so the changed UISwitch gets visible again, it is changed back to its initial state.
The Switch-event gets fired like it should.

So, what am I doing wrong? Am I missing something?

I recorded a 4-seconds-Screencast to demonstrate, what's going on:
http://b-bereich.de/download/swiftSwitch.mov

答:
TableViewCells are reused.

That means you need to keep track of the data you are using to fill the content of the cells. If the cell content changes - such as when you tap a Switch in the cell - you need to update your datasource. When you scroll, and that row is displayed again, your data will know how to set the state of the Switch.

Here is a simple example:

```<code>//
//  TableWithSwitchTableViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/5/17.
//  Copyright © 2017 DonMag. All rights reserved.
//

import UIKit

class MyTableViewCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var mySwitch: UISwitch!

    var switchTapAction : ((Bool)->Void)?

    @IBAction func switched(_ sender: UISwitch) {
        print("Switched: \(sender.isOn)")

        // send the Switch state in a "call back" to the view controller
        switchTapAction?(sender.isOn)
    }
}

// simple data object
class MyObject: NSObject {
    var theTitle = ""
    var theSwitchState = false

    init(_ title: String) {
        theTitle = title
    }
}

class TableWithSwitchTableViewController: UITableViewController {

    // array of MyObjects
    var myData = [MyObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // just to make it a little easier to see the rows scroll
        tableView.rowHeight = 60

        // create 40 data objects for the table
        for i in 1...40 {
            let d = MyObject("Data Item: \(i)")
            myData.append(d)
        }

        tableView.reloadData()

    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! MyTableViewCell

        // Configure the cell...
        let d = myData[indexPath.row]
        cell.myLabel.text = d.theTitle
        cell.mySwitch.isOn = d.theSwitchState

        // set a "Callback Closure" in the cell
        cell.switchTapAction = {
            (isOn) in
            // update our Data Array to the new state of the switch in the cell
            self.myData[indexPath.row].theSwitchState = isOn
        }

        return cell
    }

}
</code>```

Body:
That's weird: I just set up a new Single-View iOS Project and put a TableView into the Main.storyboard. In this TableView I put a TableViewCell and into this Cell, I put an UILabel and an UISwitch.
For this TableViewCell I created a CocoaTouchClass MyTableViewCell and set this for the TableViewCell's Class in Interfacebuilder.
I connected Outlets for the UILabel and UISwitch to MyTableViewCell, as well as an action for the switch.
Also I connected the TableView's dataSource and delegate to the ViewController.

So, as I think, basic stuff for setting up a table.

My ViewController looks like this:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableData = [[String: Bool]]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for index in 1...40 {
        self.tableData.append([String(index): index%2 == 0])
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyTableViewCell
    let object = tableData[indexPath.row].first!

    cell.myLabel.text = object.key
    cell.mySwitch.setOn(object.value, animated: false)

    return cell
}

}

So, I populate the Table with some Rows of Data and switch every second UISwitch to on.

The MyTableViewCell-Class is nothing special as well:

class MyTableViewCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySwitch: UISwitch!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func switched(_ sender: UISwitch) {
    print("Switched: \(sender.isOn)")
}

}

Ok, fire up the iOS-Simulator and I see the Table as expected. 40 Table-Lines don't fit on one screen, so the TableView makes itself scrollable.

Now: when I change the state of one UISwitch, and drag the TableView so the changed UISwitch gets out of view and then drag the TableView so the changed UISwitch gets visible again, it is changed back to its initial state.
The Switch-event gets fired like it should.

So, what am I doing wrong? Am I missing something?

I recorded a 4-seconds-Screencast to demonstrate, what's going on:
http://b-bereich.de/download/swiftSwitch.mov

Body:
TableViewCells are reused.

That means you need to keep track of the data you are using to fill the content of the cells. If the cell content changes - such as when you tap a Switch in the cell - you need to update your datasource. When you scroll, and that row is displayed again, your data will know how to set the state of the Switch.

Here is a simple example:

//
//  TableWithSwitchTableViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/5/17.
//  Copyright © 2017 DonMag. All rights reserved.
//

import UIKit

class MyTableViewCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var mySwitch: UISwitch!

    var switchTapAction : ((Bool)->Void)?

    @IBAction func switched(_ sender: UISwitch) {
        print("Switched: \(sender.isOn)")

        // send the Switch state in a "call back" to the view controller
        switchTapAction?(sender.isOn)
    }
}

// simple data object
class MyObject: NSObject {
    var theTitle = ""
    var theSwitchState = false

    init(_ title: String) {
        theTitle = title
    }
}

class TableWithSwitchTableViewController: UITableViewController {

    // array of MyObjects
    var myData = [MyObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // just to make it a little easier to see the rows scroll
        tableView.rowHeight = 60

        // create 40 data objects for the table
        for i in 1...40 {
            let d = MyObject("Data Item: \(i)")
            myData.append(d)
        }

        tableView.reloadData()

    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! MyTableViewCell

        // Configure the cell...
        let d = myData[indexPath.row]
        cell.myLabel.text = d.theTitle
        cell.mySwitch.isOn = d.theSwitchState

        // set a "Callback Closure" in the cell
        cell.switchTapAction = {
            (isOn) in
            // update our Data Array to the new state of the switch in the cell
            self.myData[indexPath.row].theSwitchState = isOn
        }

        return cell
    }

}


问:
Add Points to a Point Cloud with User Mouse Clicks
I'm using Three.js to render point cloud data retrieved from a server.

For each data set, I loop over the data points and create a Three.js Vector3 object with x, y & z values corresponding to each data point. I push each of these vertices onto a list which I then pass into the vertices prop of my geometry component within my points component.

```<code>render() {
    this.pointCloudVertices = [];
    if (this.props.points) {
        const points = this.props.points
        for (let i = 0; i < points.x.length; i++) {
            const vertex = new THREE.Vector3();

            vertex.x = points.x[i]
            vertex.y = points.y[i]
            vertex.z = points.z[i]

            this.pointCloudVertices.push(vertex);
        }
    }
    return (<points>
        <geometry vertices={this.pointCloudVertices}/>
        <pointsMaterial
            color={ (Math.floor(Math.random()*16777215)) }
            size={ 0.2 }
        />
    </points>);
}
</code>```

https://github.com/caseysiebel/pc-client/blob/master/src/components/PointCloud.js

I'd like the user to be able to use their mouse to add points to another point cloud (points component) by clicking inside the canvas.

I found a lot of resources pointing to the Three.js' Raycaster, but this tool seems to be more for selecting out objects already in the canvas. In my case I'd like the user to be able to click on and area in the canvas not occupied by an object, have the client work out the x, y & z coordinates of that click and then add a vertex, with those x/y/z values, to a points component (likely empty until the user adds points via this modality).

I'm a little confused as to how I will convert 2D mouse events into a 3D vertex value. If anyone knows any good resources on this subject I'd love to check them out.

答:
With THREE.Raycaster(), I see several solutions:

1. Use the .at() method of the .ray property. Like this:

```<code>raycaster.ray.at(100 + Math.random() * 150, rndPoint);
</code>```

Here you can set the constraints for the distance from the origin of the ray, and it will look like this from your original camera:

and how it will look like from aside:

jsfiddle example. You can switch the lines off there.

2. Use the .intersectObjects() method. Where intersecting objects are planes of constraints. For example, we have planes in the form of a cube. When we cast a ray through them, we always intersect two planes, and the array of intersectec objects will be sorted by distance from the origin of the ray. Thus the first element in this array will be the closest plane. So, when we know it, we can take their points of intersection and sub point1 from point2, getting a new vector (its length and direction). And then we'll just set a point at a random place along the vector from point1 to point2:

```<code>intersected = raycaster.intersectObjects(planes.children);
  if (intersected.length > 0){
    var point1 = intersected[0].point;
    var point2 = intersected[1].point;
    var diff = point2.clone().sub(point1);
    var diffLength = diff.length();
    rndPoint = point1.clone().addScaledVector(diff.normalize(), Math.random() * diffLength);
    . . .
  }
</code>```

It will look like this from the front camera:

and from aside:

jsfiddle example. Lines are switchable here too.

Or you can use THREE.Raycaster() with THREE.OrthographicCamera(). Which is simplier )

Body:
I'm using Three.js to render point cloud data retrieved from a server.

For each data set, I loop over the data points and create a Three.js Vector3 object with x, y & z values corresponding to each data point. I push each of these vertices onto a list which I then pass into the vertices prop of my geometry component within my points component.

render() {
    this.pointCloudVertices = [];
    if (this.props.points) {
        const points = this.props.points
        for (let i = 0; i < points.x.length; i++) {
            const vertex = new THREE.Vector3();

            vertex.x = points.x[i]
            vertex.y = points.y[i]
            vertex.z = points.z[i]

            this.pointCloudVertices.push(vertex);
        }
    }
    return (<points>
        <geometry vertices={this.pointCloudVertices}/>
        <pointsMaterial
            color={ (Math.floor(Math.random()*16777215)) }
            size={ 0.2 }
        />
    </points>);
}

https://github.com/caseysiebel/pc-client/blob/master/src/components/PointCloud.js

I'd like the user to be able to use their mouse to add points to another point cloud (points component) by clicking inside the canvas.

I found a lot of resources pointing to the Three.js' Raycaster, but this tool seems to be more for selecting out objects already in the canvas. In my case I'd like the user to be able to click on and area in the canvas not occupied by an object, have the client work out the x, y & z coordinates of that click and then add a vertex, with those x/y/z values, to a points component (likely empty until the user adds points via this modality).

I'm a little confused as to how I will convert 2D mouse events into a 3D vertex value. If anyone knows any good resources on this subject I'd love to check them out.

Body:
With THREE.Raycaster(), I see several solutions:

1. Use the .at() method of the .ray property. Like this:

raycaster.ray.at(100 + Math.random() * 150, rndPoint);

Here you can set the constraints for the distance from the origin of the ray, and it will look like this from your original camera:

and how it will look like from aside:

jsfiddle example. You can switch the lines off there.

2. Use the .intersectObjects() method. Where intersecting objects are planes of constraints. For example, we have planes in the form of a cube. When we cast a ray through them, we always intersect two planes, and the array of intersectec objects will be sorted by distance from the origin of the ray. Thus the first element in this array will be the closest plane. So, when we know it, we can take their points of intersection and sub point1 from point2, getting a new vector (its length and direction). And then we'll just set a point at a random place along the vector from point1 to point2:

intersected = raycaster.intersectObjects(planes.children);
  if (intersected.length > 0){
    var point1 = intersected[0].point;
    var point2 = intersected[1].point;
    var diff = point2.clone().sub(point1);
    var diffLength = diff.length();
    rndPoint = point1.clone().addScaledVector(diff.normalize(), Math.random() * diffLength);
    . . .
  }

It will look like this from the front camera:

and from aside:

jsfiddle example. Lines are switchable here too.

Or you can use THREE.Raycaster() with THREE.OrthographicCamera(). Which is simplier )


问:
Can't use WC_Order in admin-ajax.php
I'm trying to retrieve order information within the admin-ajax.php request, but it is returning protected objects with no data. Is there a way to access this?

I'm using this:

```<code>$data = new WC_Order($order_id);
var_dump($data);
</code>```

This works when it is run within this:

```<code>add_action('woocommerce_order_status_completed', 'send_documents_to_customer');
</code>```

But I also need to run this as an admin ajax request:

```<code>add_action('wp_ajax_send_documents_to_customer', 'send_documents_to_customer');
</code>```

But it returns protected:

object(WC_Order)#15861 (14) { ["status_transition":protected]=> bool(false) ["data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["items":protected]=> array(1) { ["line_items"]=> array(0) { } } ["items_to_delete":protected]=> array(0) { } ["cache_group":protected]=> string(6) "orders" ["data_store_name":protected]=> string(5) "order" ["object_type":protected]=> string(5) "order" ["id":protected]=> int(0) ["changes":protected]=> array(0) { } ["object_read":protected]=> bool(true) ["extra_data":protected]=> array(0) { } ["default_data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["data_store":protected]=> object(WC_Data_Store)#15862 (4) { ["instance":"WC_Data_Store":private]=> object(WC_Order_Data_Store_CPT)#15863 (3) { ["internal_meta_keys":protected]=> array(49) { [0]=> string(14) "_customer_user" [1]=> string(10) "_order_key" [2]=> string(15) "_order_currency" [3]=> string(19) "_billing_first_name" [4]=> string(18) "_billing_last_name" [5]=> string(16) "_billing_company" [6]=> string(18) "_billing_address_1" [7]=> string(18) "_billing_address_2" [8]=> string(13) "_billing_city" [9]=> string(14) "_billing_state" [10]=> string(17) "_billing_postcode" [11]=> string(16) "_billing_country" [12]=> string(14) "_billing_email" [13]=> string(14) "_billing_phone" [14]=> string(20) "_shipping_first_name" [15]=> string(19) "_shipping_last_name" [16]=> string(17) "_shipping_company" [17]=> string(19) "_shipping_address_1" [18]=> string(19) "_shipping_address_2" [19]=> string(14) "_shipping_city" [20]=> string(15) "_shipping_state" [21]=> string(18) "_shipping_postcode" [22]=> string(17) "_shipping_country" [23]=> string(15) "_completed_date" [24]=> string(10) "_paid_date" [25]=> string(10) "_edit_lock" [26]=> string(10) "_edit_last" [27]=> string(14) "_cart_discount" [28]=> string(18) "_cart_discount_tax" [29]=> string(15) "_order_shipping" [30]=> string(19) "_order_shipping_tax" [31]=> string(10) "_order_tax" [32]=> string(12) "_order_total" [33]=> string(15) "_payment_method" [34]=> string(21) "_payment_method_title" [35]=> string(15) "_transaction_id" [36]=> string(20) "_customer_ip_address" [37]=> string(20) "_customer_user_agent" [38]=> string(12) "_created_via" [39]=> string(14) "_order_version" [40]=> string(19) "_prices_include_tax" [41]=> string(15) "_date_completed" [42]=> string(10) "_date_paid" [43]=> string(15) "_payment_tokens" [44]=> string(22) "_billing_address_index" [45]=> string(23) "_shipping_address_index" [46]=> string(15) "_recorded_sales" [47]=> string(29) "_recorded_coupon_usage_counts" [48]=> string(16) "_shipping_method" } ["meta_type":protected]=> string(4) "post" ["object_id_field_for_meta":protected]=> string(0) "" } ["stores":"WC_Data_Store":private]=> array(18) { ["coupon"]=> string(24) "WC_Coupon_Data_Store_CPT" ["customer"]=> string(22) "WC_Customer_Data_Store" ["customer-download"]=> string(31) "WC_Customer_Download_Data_Store" ["customer-session"]=> string(30) "WC_Customer_Data_Store_Session" ["order"]=> string(23) "WC_Order_Data_Store_CPT" ["order-refund"]=> string(30) "WC_Order_Refund_Data_Store_CPT" ["order-item"]=> string(24) "WC_Order_Item_Data_Store" ["order-item-coupon"]=> string(31) "WC_Order_Item_Coupon_Data_Store" ["order-item-fee"]=> string(28) "WC_Order_Item_Fee_Data_Store" ["order-item-product"]=> string(32) "WC_Order_Item_Product_Data_Store" ["order-item-shipping"]=> string(33) "WC_Order_Item_Shipping_Data_Store" ["order-item-tax"]=> string(28) "WC_Order_Item_Tax_Data_Store" ["payment-token"]=> string(27) "WC_Payment_Token_Data_Store" ["product"]=> string(25) "WC_Product_Data_Store_CPT" ["product-grouped"]=> string(33) "WC_Product_Grouped_Data_Store_CPT" ["product-variable"]=> string(34) "WC_Product_Variable_Data_Store_CPT" ["product-variation"]=> string(35) "WC_Product_Variation_Data_Store_CPT" ["shipping-zone"]=> string(27) "WC_Shipping_Zone_Data_Store" } ["current_class_name":"WC_Data_Store":private]=> string(23) "WC_Order_Data_Store_CPT" ["object_type":"WC_Data_Store":private]=> string(5) "order" } ["meta_data":protected]=> NULL }

答: you can get all your order data by using provided functions from WC Order</p>

Title: Can't use WC_Order in admin-ajax.php

Body:
I'm trying to retrieve order information within the admin-ajax.php request, but it is returning protected objects with no data. Is there a way to access this?

I'm using this:

$data = new WC_Order($order_id);
var_dump($data);

This works when it is run within this:

add_action('woocommerce_order_status_completed', 'send_documents_to_customer');

But I also need to run this as an admin ajax request:

add_action('wp_ajax_send_documents_to_customer', 'send_documents_to_customer');

But it returns protected:

object(WC_Order)#15861 (14) { ["status_transition":protected]=> bool(false) ["data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["items":protected]=> array(1) { ["line_items"]=> array(0) { } } ["items_to_delete":protected]=> array(0) { } ["cache_group":protected]=> string(6) "orders" ["data_store_name":protected]=> string(5) "order" ["object_type":protected]=> string(5) "order" ["id":protected]=> int(0) ["changes":protected]=> array(0) { } ["object_read":protected]=> bool(true) ["extra_data":protected]=> array(0) { } ["default_data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["data_store":protected]=> object(WC_Data_Store)#15862 (4) { ["instance":"WC_Data_Store":private]=> object(WC_Order_Data_Store_CPT)#15863 (3) { ["internal_meta_keys":protected]=> array(49) { [0]=> string(14) "_customer_user" [1]=> string(10) "_order_key" [2]=> string(15) "_order_currency" [3]=> string(19) "_billing_first_name" [4]=> string(18) "_billing_last_name" [5]=> string(16) "_billing_company" [6]=> string(18) "_billing_address_1" [7]=> string(18) "_billing_address_2" [8]=> string(13) "_billing_city" [9]=> string(14) "_billing_state" [10]=> string(17) "_billing_postcode" [11]=> string(16) "_billing_country" [12]=> string(14) "_billing_email" [13]=> string(14) "_billing_phone" [14]=> string(20) "_shipping_first_name" [15]=> string(19) "_shipping_last_name" [16]=> string(17) "_shipping_company" [17]=> string(19) "_shipping_address_1" [18]=> string(19) "_shipping_address_2" [19]=> string(14) "_shipping_city" [20]=> string(15) "_shipping_state" [21]=> string(18) "_shipping_postcode" [22]=> string(17) "_shipping_country" [23]=> string(15) "_completed_date" [24]=> string(10) "_paid_date" [25]=> string(10) "_edit_lock" [26]=> string(10) "_edit_last" [27]=> string(14) "_cart_discount" [28]=> string(18) "_cart_discount_tax" [29]=> string(15) "_order_shipping" [30]=> string(19) "_order_shipping_tax" [31]=> string(10) "_order_tax" [32]=> string(12) "_order_total" [33]=> string(15) "_payment_method" [34]=> string(21) "_payment_method_title" [35]=> string(15) "_transaction_id" [36]=> string(20) "_customer_ip_address" [37]=> string(20) "_customer_user_agent" [38]=> string(12) "_created_via" [39]=> string(14) "_order_version" [40]=> string(19) "_prices_include_tax" [41]=> string(15) "_date_completed" [42]=> string(10) "_date_paid" [43]=> string(15) "_payment_tokens" [44]=> string(22) "_billing_address_index" [45]=> string(23) "_shipping_address_index" [46]=> string(15) "_recorded_sales" [47]=> string(29) "_recorded_coupon_usage_counts" [48]=> string(16) "_shipping_method" } ["meta_type":protected]=> string(4) "post" ["object_id_field_for_meta":protected]=> string(0) "" } ["stores":"WC_Data_Store":private]=> array(18) { ["coupon"]=> string(24) "WC_Coupon_Data_Store_CPT" ["customer"]=> string(22) "WC_Customer_Data_Store" ["customer-download"]=> string(31) "WC_Customer_Download_Data_Store" ["customer-session"]=> string(30) "WC_Customer_Data_Store_Session" ["order"]=> string(23) "WC_Order_Data_Store_CPT" ["order-refund"]=> string(30) "WC_Order_Refund_Data_Store_CPT" ["order-item"]=> string(24) "WC_Order_Item_Data_Store" ["order-item-coupon"]=> string(31) "WC_Order_Item_Coupon_Data_Store" ["order-item-fee"]=> string(28) "WC_Order_Item_Fee_Data_Store" ["order-item-product"]=> string(32) "WC_Order_Item_Product_Data_Store" ["order-item-shipping"]=> string(33) "WC_Order_Item_Shipping_Data_Store" ["order-item-tax"]=> string(28) "WC_Order_Item_Tax_Data_Store" ["payment-token"]=> string(27) "WC_Payment_Token_Data_Store" ["product"]=> string(25) "WC_Product_Data_Store_CPT" ["product-grouped"]=> string(33) "WC_Product_Grouped_Data_Store_CPT" ["product-variable"]=> string(34) "WC_Product_Variable_Data_Store_CPT" ["product-variation"]=> string(35) "WC_Product_Variation_Data_Store_CPT" ["shipping-zone"]=> string(27) "WC_Shipping_Zone_Data_Store" } ["current_class_name":"WC_Data_Store":private]=> string(23) "WC_Order_Data_Store_CPT" ["object_type":"WC_Data_Store":private]=> string(5) "order" } ["meta_data":protected]=> NULL }


问:
Build file bar (Message broker) using Ant?
I am trying create BAR file using ANT by using the command:

```<code>mqsicreatebar -data F:\Code\Broker\workspace -b C:\iib-ci-rep\result.bar -a MY_APP_NAME -skipWSErrorCheck
</code>```

If I use the above command in Command Line Window, it create bar file successful. However if I remove "-skipWSErrorCheck", it will show some error message like that

"Problem 2: Resource - /TTHD_EVN/InsertLog.msgflow; Error message -
  Class  "javaComput.InsertLog_JavaCompute" is not in a Java Compute
  Node project refere nced by "TTHD_EVN"

But I only want to build my app "MY_APP_NAME", not for all projects in workplace, how can I do that ?

Moreover, if I use xml script for building by using Ant & Jenkins, I can't not get "BAR" file, although it returned "BUILD SUCCESSFUL" result. Do you know why ?

```<code><?xml version="1.0"?>
<project name="project" default="run">
  <target name="run" description="">
    <property name="toolkit.home" value="C:\Program Files (x86)\IBM\IntegrationToolkit90" />
    <property name="ant.bars.basedir" value="C:\iib-ci-repo" />
    <property name="bar.name" value="${ant.bars.basedir}\result.bar" />
    <property name="workspace.dir" value="F:\Code\Broker\worksp" />
    <antcall target="build" />
  </target>
  <target name="build">
     <echo message="Building the Message Broker Project @ ${workspace.dir}" />
      <echo message="Output ${bar.name}" />
     <exec executable="${toolkit.home}\mqsicreatebar.exe" spawn="false">
        <!-- <arg value="-data" />
            <arg value="${workspace.dir}" /> -->
        <arg value="-b" />
            <arg value="${bar.name}" />
        <!-- List all the message flow projects -->
        <arg value="-a" />
            <arg value="MY_APP_NAME" />

        <arg value="-skipWSErrorCheck" />
             <arg value="" />

     </exec>
  </target>
</project>
</code>```

答:
If you don't add -skipWSErrorCheck, mqsicreatebar will check for errors in the workspace, it doesn't matter that you build only 1 app in the workspace.

I recommend, that you put only those projects (applications) in a single workspace which you want to build and deploy together.

Body:
I am trying create BAR file using ANT by using the command:

mqsicreatebar -data F:\Code\Broker\workspace -b C:\iib-ci-rep\result.bar -a MY_APP_NAME -skipWSErrorCheck

If I use the above command in Command Line Window, it create bar file successful. However if I remove "-skipWSErrorCheck", it will show some error message like that

"Problem 2: Resource - /TTHD_EVN/InsertLog.msgflow; Error message -
  Class  "javaComput.InsertLog_JavaCompute" is not in a Java Compute
  Node project refere nced by "TTHD_EVN"

But I only want to build my app "MY_APP_NAME", not for all projects in workplace, how can I do that ?

Moreover, if I use xml script for building by using Ant & Jenkins, I can't not get "BAR" file, although it returned "BUILD SUCCESSFUL" result. Do you know why ?

<?xml version="1.0"?>
<project name="project" default="run">
  <target name="run" description="">
    <property name="toolkit.home" value="C:\Program Files (x86)\IBM\IntegrationToolkit90" />
    <property name="ant.bars.basedir" value="C:\iib-ci-repo" />
    <property name="bar.name" value="${ant.bars.basedir}\result.bar" />
    <property name="workspace.dir" value="F:\Code\Broker\worksp" />
    <antcall target="build" />
  </target>
  <target name="build">
     <echo message="Building the Message Broker Project @ ${workspace.dir}" />
      <echo message="Output ${bar.name}" />
     <exec executable="${toolkit.home}\mqsicreatebar.exe" spawn="false">

        <arg value="-b" />
            <arg value="${bar.name}" />

        <arg value="-a" />
            <arg value="MY_APP_NAME" />

        <arg value="-skipWSErrorCheck" />
             <arg value="" />

     </exec>
  </target>
</project>


问:
MVVM bind IsEnabled to multiple bools in ViewModel
I have the button below which has it's IsEnabled property bound to a bool in the ViewModel called EnableBtn.

If I have another bool called EnableMail how would I amend this so that the IsEnabled is bound to both?

```<code>    <Button IsEnabled="{Binding EnableBtn, Converter={StaticResource InvertBooleanConverter}}" x:Name="SaveSendButton" Grid.Row="0" Grid.Column="1" Text="{i18n:Translate SaveAndSend}" Style="{StaticResource bottomButtonsBlue}" Command="{Binding EmailPlanCommand}"></Button>
</code>```

答:
```<code>    public bool IsBothEnabled
    {
        get
        {
            if (EnableBtn && EnableMail)
                return true;
            return false;
        }
    }
</code>```

Now bind your Button.IsEnabled Property to IsBothEnabled.

Body:
I have the button below which has it's IsEnabled property bound to a bool in the ViewModel called EnableBtn.

If I have another bool called EnableMail how would I amend this so that the IsEnabled is bound to both?

    <Button IsEnabled="{Binding EnableBtn, Converter={StaticResource InvertBooleanConverter}}" x:Name="SaveSendButton" Grid.Row="0" Grid.Column="1" Text="{i18n:Translate SaveAndSend}" Style="{StaticResource bottomButtonsBlue}" Command="{Binding EmailPlanCommand}"></Button>

Body:
    public bool IsBothEnabled
    {
        get
        {
            if (EnableBtn && EnableMail)
                return true;
            return false;
        }
    }

Now bind your Button.IsEnabled Property to IsBothEnabled.


问:
Read from csv file of characters and storing in tensor
```<code>filename_queue = tf.train.string_input_producer(["AlldTKmer4997.csv"])

reader = tf.TextLineReader()

key, value = reader.read(filename_queue)

record_defaults = [tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),]

  col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15
   = tf.decode_csv(value,record_defaults=record_defaults)

features = tf.stack([col1, col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15 ])

 with tf.Session() as sess:

 coord = tf.train.Coordinator()

 threads = tf.train.start_queue_runners(coord=coord)

 for i in range(1000):

X = sess.run([features])

coord.request_stop()

coord.join(threads)
</code>```

`
I am trying to read from a csv file of characters and special characters and have written the above code
The input csv file looks like this:

"A" "G" "T" "C"...(15 characters) "/" ")" "3" (15 special characters/integers)

But I am getting the following error:

InvalidArgumentError: Quote inside a string has to be escaped by another quote
     [[Node: DecodeCSV_2 = DecodeCSV[OUT_TYPE=[DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING], field_delim=",", _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2_2:1, Const_15, Const_16, Const_17, Const_18, Const_19, Const_20, Const_21, Const_22, Const_23, Const_24, Const_25, Const_26, Const_27, Const_28, Const_29)]]

答:
Tensorflow can only decode valid csv following RFC4180.

It seems that you might have a double-quote inside field where double-quotes are used to enclose. Refer to section 2.7 of RFC4180.

If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote.  For example:

```<code>"aaa","b""bb","ccc"
</code>```

Try add an extra double-quote before it.

Body:
filename_queue = tf.train.string_input_producer(["AlldTKmer4997.csv"])

reader = tf.TextLineReader()

key, value = reader.read(filename_queue)

record_defaults = [tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),
               tf.constant([], dtype=tf.string),]

  col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15
   = tf.decode_csv(value,record_defaults=record_defaults)

features = tf.stack([col1, col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15 ])

 with tf.Session() as sess:

 coord = tf.train.Coordinator()

 threads = tf.train.start_queue_runners(coord=coord)

 for i in range(1000):

X = sess.run([features])

coord.request_stop()

coord.join(threads)

`
I am trying to read from a csv file of characters and special characters and have written the above code
The input csv file looks like this:

"A" "G" "T" "C"...(15 characters) "/" ")" "3" (15 special characters/integers)

But I am getting the following error:

InvalidArgumentError: Quote inside a string has to be escaped by another quote
     [[Node: DecodeCSV_2 = DecodeCSV[OUT_TYPE=[DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING, DT_STRING], field_delim=",", _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2_2:1, Const_15, Const_16, Const_17, Const_18, Const_19, Const_20, Const_21, Const_22, Const_23, Const_24, Const_25, Const_26, Const_27, Const_28, Const_29)]]

Body:
Tensorflow can only decode valid csv following RFC4180.

It seems that you might have a double-quote inside field where double-quotes are used to enclose. Refer to section 2.7 of RFC4180.

If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote.  For example:

"aaa","b""bb","ccc"

Try add an extra double-quote before it.


问:
Troubleshooting OSError: out of pty devices
From time to time I'm getting an OSError exception with the message 'out of pty devices' when calling pty.openpty() (it's happening when a bunch of instances of my scripts run concurrently).

What is the limit that I'm hitting?  How can I get around this?

CentOS 5.6, Python 2.4

答:
Same issue is raised when devpts is not mounted, usually in chroots, to mount devpts device type:

```<code>mount -t devpts none /path/to/chroot/dev/pts
</code>```

Body:
Same issue is raised when devpts is not mounted, usually in chroots, to mount devpts device type:

mount -t devpts none /path/to/chroot/dev/pts


问:
Unpack dict from list where key is not None
Trying to unpack the dicts which are not None from a list:

```<code>In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]
</code>```

Tried a dict comprehension

```<code>In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)
</code>```

And a list comprehension:

```<code>In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping
</code>```

Expected result:

```<code>{'key': 'a', 'key_2': 'b'}
</code>```

What is the right syntax?

答:
FWIW, you can do this with a for loop and successive calls to dict.update, which I think is quite readable:

```<code>>>> dct = {}
>>> for d in unpack_dict:
...    if d:
...       dct.update(d)
...
>>> dct
{'key': 'a', 'key_2': 'b'}
</code>```

Body:
Trying to unpack the dicts which are not None from a list:

In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]

Tried a dict comprehension

In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)

And a list comprehension:

In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping

Expected result:

{'key': 'a', 'key_2': 'b'}

What is the right syntax?

Body:
FWIW, you can do this with a for loop and successive calls to dict.update, which I think is quite readable:

>>> dct = {}
>>> for d in unpack_dict:
...    if d:
...       dct.update(d)
...
>>> dct
{'key': 'a', 'key_2': 'b'}