问:
React JSX - dynamic html attribute
In JSX, we can indicate attribute value dynamically like:

```<code><div className={this.state.className}>This is a div.</div>
</code>```

Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:

```<code>const value = emptyValue ? "" : "value='test'";
<input {value} />
</code>```

That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).

答:
you can insert whole element in if statement in render function, but before return like this:

```<code>render() {

var input = (<input />);
if (!emptyValue) {
    input = (<input value='test'/>)
}

return (
    <div>
        {input}
    </div>
    )
}
</code>```

Title: React JSX - dynamic html attribute

Body:
In JSX, we can indicate attribute value dynamically like:

This is a div.

Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:

const value = emptyValue ? "" : "value='test'";
<input {value} />

That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).

Body:
you can insert whole element in if statement in render function, but before return like this:

render() {

var input = (<input />);
if (!emptyValue) {
    input = (<input value='test'/>)
}

return (
    <div>
        {input}
    </div>
    )
}


来源: stackexchange

问:
dc.js numberdisplay filter percentage
I'm new into javascript and dc.js and currently having difficulty creating a numberDisplay that only looks at a particular value in a column within my data.

I have created a dashboard with a number of different charts but I'm currently stuck on the final numberDisplays that will also filter along with the rest of the charts.

My data includes two fields in a similar format to the below, and I'm looking to create a percentage numberDisplay only for SLA's that are "2 days".

So I would expect the numberDisplay to return a percentage of "2 days" within the entire group, so it would show 30% (10/30)

I've searched and tried different solutions but the only thing I've managed to do so far is to display the overall Sum for all SLA's.

```<code>var data = [{
"sla": "2 days",
    "team": "hr",
    "hits": 7
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 1
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 2
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 5
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 4
}, {
"sla": "5 days",
    "team": "finance",
    "hits": 3
}, {
"sla": "5 days",
    "team": "hr",
    "hits": 8
}];
</code>```

There are around 6-7 different possible entries in SLA, and I'm currently only looking to create number displays for 2 or 3 of them.

What would be the quickest/easiest solution to do this?

I have created a basic jsfiddle as an example: https://jsfiddle.net/kevinelphick/owx2L1wt/2/?utm_source=website&utm_medium=embed&utm_campaign=owx2L1wt

答:
I've managed to found a solution for this thanks to some guidance from Gordon's comment and some further research on this site:

I added some functions to the group:

```<code>var slaGroup1 = all.reduce(
  function(p, v) {
    p.count += v.hits;
    p.slasum += (v.sla == "2 days" ? v.hits : 0);
    p.slaPercent = p.count ? p.slasum/p.count : 0;
    return p;
    console.log(p.failures);
  },
  function(p, v) {
    p.count -= v.hits;
    p.slasum -= (v.sla == "2 days" ? v.hits : 0);
    p.slaPercent = p.count ? p.slasum/p.count : 0;
    return p;
  },
  function() {
    return {
      count: 0,
      slasum: 0,
      slaPercent: 0
    };
  }
);
</code>```

and then my NumberDisplay value accessor:

```<code>slaNumberDisplay
  .group(slaGroup1)
  .formatNumber(d3.format(".1%"))
  .valueAccessor(function (x) {return x.slaPercent;});
</code>```

I'm sure there's a more dynamic way to do this though? If I wanted to create multiple number displays for different criteria? Could I create the functions outside of the group, and the group calls the functions with the criteria set inside brackets? And I could also remove the percentage from the functions too, and simply do this in the value Accessor.

ContentLicense: CC BY-SA 3.0

Title: dc.js numberdisplay filter percentage

Body:
I'm new into javascript and dc.js and currently having difficulty creating a numberDisplay that only looks at a particular value in a column within my data.

I have created a dashboard with a number of different charts but I'm currently stuck on the final numberDisplays that will also filter along with the rest of the charts.

My data includes two fields in a similar format to the below, and I'm looking to create a percentage numberDisplay only for SLA's that are "2 days".

So I would expect the numberDisplay to return a percentage of "2 days" within the entire group, so it would show 30% (10/30)

I've searched and tried different solutions but the only thing I've managed to do so far is to display the overall Sum for all SLA's.

var data = [{
"sla": "2 days",
    "team": "hr",
    "hits": 7
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 1
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 2
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 5
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 4
}, {
"sla": "5 days",
    "team": "finance",
    "hits": 3
}, {
"sla": "5 days",
    "team": "hr",
    "hits": 8
}];

There are around 6-7 different possible entries in SLA, and I'm currently only looking to create number displays for 2 or 3 of them.

What would be the quickest/easiest solution to do this?

I have created a basic jsfiddle as an example: https://jsfiddle.net/kevinelphick/owx2L1wt/2/?utm_source=website&utm_medium=embed&utm_campaign=owx2L1wt

Body:
I've managed to found a solution for this thanks to some guidance from Gordon's comment and some further research on this site:

I added some functions to the group:

var slaGroup1 = all.reduce(
  function(p, v) {
    p.count += v.hits;
    p.slasum += (v.sla == "2 days" ? v.hits : 0);
    p.slaPercent = p.count ? p.slasum/p.count : 0;
    return p;
    console.log(p.failures);
  },
  function(p, v) {
    p.count -= v.hits;
    p.slasum -= (v.sla == "2 days" ? v.hits : 0);
    p.slaPercent = p.count ? p.slasum/p.count : 0;
    return p;
  },
  function() {
    return {
      count: 0,
      slasum: 0,
      slaPercent: 0
    };
  }
);

and then my NumberDisplay value accessor:

slaNumberDisplay
  .group(slaGroup1)
  .formatNumber(d3.format(".1%"))
  .valueAccessor(function (x) {return x.slaPercent;});

I'm sure there's a more dynamic way to do this though? If I wanted to create multiple number displays for different criteria? Could I create the functions outside of the group, and the group calls the functions with the criteria set inside brackets? And I could also remove the percentage from the functions too, and simply do this in the value Accessor.


问:
Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery
I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format.
This should occure .on("input") meaning as the user types it should secure the right input format.

A wrong char should be replaced with a blank.

Format Example:
 1.000
1.281
 21212.000
 21212.810
Nothing like this:
1.02.12
or
1919,201,00
 Only a dot between the two Number blocks.

This is what i have so far:

    Regex 1:

```<code>$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[^0-9]/g,'');
});
</code>```

Regex 2:

```<code>$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
</code>```

Regex 3:

```<code>$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
</code>```

I think i am doing something wrong with the replace() method.
Unfortunately none of them work as i want to. Any help is appreciated.

Here is the FIDDLE

Should Work in IE11

答:
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser

const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;

$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.</code>```

<input id="testId" type="tel" />

```

Body:
I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format.
This should occure .on("input") meaning as the user types it should secure the right input format.

A wrong char should be replaced with a blank.

Format Example:
 1.000
1.281
 21212.000
 21212.810
Nothing like this:
1.02.12
or
1919,201,00
 Only a dot between the two Number blocks.

This is what i have so far:

    Regex 1:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[^0-9]/g,'');
});

Regex 2:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});

Regex 3:

$("body").on("input", "#testId", function(){
     this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});

I think i am doing something wrong with the replace() method.
Unfortunately none of them work as i want to. Any help is appreciated.

Here is the FIDDLE

Should Work in IE11

Body:
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser

const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;

$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;

});

.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />

</body>
</html>


问:
How do I select the top ten scores in a database table full of scores using linq in C#
I'm new to Linq and database programming in general, I could really use some help.

I have tried using

```<code>var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;
</code>```

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

答:
I'm new to LINQ myself but here's what I think should work:</p>

```<code>var TopTen =  (from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t).Take(10);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm new to Linq and database programming in general, I could really use some help.

I have tried using

var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

Body:
I'm new to LINQ myself but here's what I think should work:

var TopTen =  (from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t).Take(10);


问:
Upload multiple images in swift using Alamofire
I'm using the following code to upload a single image to a server:

```<code>private static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData?, imageName: String) -> (URLRequestConvertible , NSData) {

    // create url request to send
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

    // create upload data to send
    let uploadData = NSMutableData()
    if(imageData != nil && imageData?.length != 0) {
        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(StringHelper.sharedInstance.randomString(5)).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData!)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    print("upload",parameters)
    // return URLRequestConvertible and NSData
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
</code>```

How can I upload multiple images in single parameter by editing this code?

答:
This one helps me:

```<code>private func urlRequestWithComponentsForUploadMultipleImages(urlString:String, parameters:Dictionary<String, String>, imagesData:[Data], imageName: String) -> (URLRequestConvertible , Data) {

    // create url request to send
    var mutableURLRequest = URLRequest(url: NSURL(string: urlString)! as URL)

    mutableURLRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

    // create upload data to send
    var uploadData = Data()
    // add image
    for data in imagesData {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(Date().timeIntervalSince1970).jpeg\"\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append(data)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
    }
    uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)
    print("upload",parameters)
    return (mutableURLRequest , uploadData)
}
</code>```

Body:
I'm using the following code to upload a single image to a server:

private static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData?, imageName: String) -> (URLRequestConvertible , NSData) {

    // create url request to send
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

    // create upload data to send
    let uploadData = NSMutableData()
    if(imageData != nil && imageData?.length != 0) {
        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(StringHelper.sharedInstance.randomString(5)).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData!)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    print("upload",parameters)
    // return URLRequestConvertible and NSData
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

How can I upload multiple images in single parameter by editing this code?

Body:
This one helps me:

private func urlRequestWithComponentsForUploadMultipleImages(urlString:String, parameters:Dictionary<String, String>, imagesData:[Data], imageName: String) -> (URLRequestConvertible , Data) {

    // create url request to send
    var mutableURLRequest = URLRequest(url: NSURL(string: urlString)! as URL)

    mutableURLRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

    // create upload data to send
    var uploadData = Data()
    // add image
    for data in imagesData {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(Date().timeIntervalSince1970).jpeg\"\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append(data)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
    }
    uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)
    print("upload",parameters)
    return (mutableURLRequest , uploadData)
}


问:
Issues commented by me in JIRA
As per JIRA documentation
http://www.atlassian.com/software/jira/docs/latest

The following filter will show the issues opned by me (Current User).

```<code>reporter = currentUser()
</code>```

Is there a filer that will show issues commented by me? something like the following does not work...

```<code>comment by = currentUser()
</code>```

答: For filtering issues in which you have been mentioned, try comment ~ currentUser()

Title: Issues commented by me in JIRA

Body:
As per JIRA documentation
http://www.atlassian.com/software/jira/docs/latest

The following filter will show the issues opned by me (Current User).

reporter = currentUser()

Is there a filer that will show issues commented by me? something like the following does not work...

comment by = currentUser()


Title: What is wrong with my json whois api output?

Body:
There's no problem - it's simply that the data in the whois property is URL encoded. You can decode it by using decodeURIComponent(), like this:

var response = {
  "result": "success",
  "status": "unavailable",
  "whois": "+---%3Cbr+%2F%3E%0AWhois+Server+Version+2.0%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0ADomain+names+in+the+.com+and+.net+domains+can+now+be+registered%3Cbr+%2F%3E%0Awith+many+different+competing+registrars.+Go+to+http%3A%2F%2Fwww.internic.net%3Cbr+%2F%3E%0Afor+detailed+information.%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0AAborting+search+50+records+found+.....%3Cbr+%2F%3E%0AGOOGLE.COM.ACKNOWLEDGES.NON-FREE.COM%3Cbr+%2F%3E%0AGOOGLE.COM.AFRICANBATS.ORG%3Cbr+%2F%3E%0AGOOGLE.COM.ANGRYPIRATES.COM%3Cbr+%2F%3E%0AGOOGLE.COM.AR%3Cbr+%2F%3E%0AGOOGLE.COM.AU%3Cbr+%2F%3E%0AGOOGLE.COM.BAISAD.COM%3Cbr+%2F%3E%0AGOOGLE.COM.BD%3Cbr+%2F%3E%0AGOOGLE.COM.BEYONDWHOIS.COM%3Cbr+%2F%3E%0AGOOGLE.COM.BR%3Cbr+%2F%3E%0AGOOGLE.COM.BUGBOUNTY.TEST.AT.CIPRI.COM%3Cbr+%2F%3E%0AGOOGLE.COM.CN%3Cbr+%2F%3E%0AGOOGLE.COM.CO%3Cbr+%2F%3E%0AGOOGLE.COM.DEADKNIFERECORDS.COM%3Cbr+%2F%3E%0AGOOGLE.COM.DGJTEST028-PP-QM-STG.COM%3Cbr+%2F%3E%0AGOOGLE.COM.DO%3Cbr+%2F%3E%0AGOOGLE.COM.EG%3Cbr+%2F%3E%0AGOOGLE.COM.FORSALE%3Cbr+%2F%3E%0AGOOGLE.COM.HACKED.BY.JAPTRON.ES%3Cbr+%2F%3E%0AGOOGLE.COM.HANNAHJESSICA.COM%3Cbr+%2F%3E%0AGOOGLE.COM.HAS.LESS.FREE.PORN.IN.ITS.SEARCH.ENGINE.THAN.SECZY.COM%3Cbr+%2F%3E%0AGOOGLE.COM.HK%3Cbr+%2F%3E%0AGOOGLE.COM.HOUDA.DO.YOU.WANT.TO.MARRY.ME.JEN.RE%3Cbr+%2F%3E%0AGOOGLE.COM.IS.APPROVED.BY.NUMEA.COM%3Cbr+%2F%3E%0AGOOGLE.COM.IS.NOT.HOSTED.BY.ACTIVEDOMAINDNS.NET%3Cbr+%2F%3E%0AGOOGLE.COM.LASERPIPE.COM.DOMAINPENDINGDELETE.COM%3Cbr+%2F%3E%0AGOOGLE.COM.LOLOLOLOLOL.SHTHEAD.COM%3Cbr+%2F%3E%0AGOOGLE.COM.MAIKO.BE%3Cbr+%2F%3E%0AGOOGLE.COM.MX%3Cbr+%2F%3E%0AGOOGLE.COM.MY%3Cbr+%2F%3E%0AGOOGLE.COM.NS1.CHALESHGAR.COM%3Cbr+%2F%3E%0AGOOGLE.COM.NS2.CHALESHGAR.COM%3Cbr+%2F%3E%0AGOOGLE.COM.PE%3Cbr+%2F%3E%0AGOOGLE.COM.PK%3Cbr+%2F%3E%0AGOOGLE.COM.SA%3Cbr+%2F%3E%0AGOOGLE.COM.SG%3Cbr+%2F%3E%0AGOOGLE.COM.SHQIPERIA.COM%3Cbr+%2F%3E%0AGOOGLE.COM.SOUTHBEACHNEEDLEARTISTRY.COM%3Cbr+%2F%3E%0AGOOGLE.COM.SPAMMING.IS.UNETHICAL.PLEASE.STOP.THEM.HUAXUEERBAN.COM%3Cbr+%2F%3E%0AGOOGLE.COM.SPROSIUYANDEKSA.RU%3Cbr+%2F%3E%0AGOOGLE.COM.SUCKS.FIND.CRACKZ.WITH.SEARCH.GULLI.COM%3Cbr+%2F%3E%0AGOOGLE.COM.TESTZZZZ.3000-RI.COM.DELETE-DNS.COM%3Cbr+%2F%3E%0AGOOGLE.COM.TR%3Cbr+%2F%3E%0AGOOGLE.COM.TW%3Cbr+%2F%3E%0AGOOGLE.COM.UA%3Cbr+%2F%3E%0AGOOGLE.COM.UK%3Cbr+%2F%3E%0AGOOGLE.COM.UY%3Cbr+%2F%3E%0AGOOGLE.COM.VABDAYOFF.COM%3Cbr+%2F%3E%0AGOOGLE.COM.VN%3Cbr+%2F%3E%0AGOOGLE.COM.YUCEHOCA.COM%3Cbr+%2F%3E%0AGOOGLE.COM%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0ATo+single+out+one+record%2C+look+it+up+with+%22xxx%22%2C+where+xxx+is+one+of+the%3Cbr+%2F%3E%0Arecords+displayed+above.+If+the+records+are+the+same%2C+look+them+up%3Cbr+%2F%3E%0Awith+%22%3Dxxx%22+to+receive+a+full+display+for+each+record.%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0A%3E%3E%3E+Last+update+of+whois+database%3A+Wed%2C+29+Mar+2017+09%3A49%3A20+GMT+%3C%3C%3C%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0AFor+more+information+on+Whois+status+codes%2C+please+visit+https%3A%2F%2Ficann.org%2Fepp%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0ANOTICE%3A+The+expiration+date+displayed+in+this+record+is+the+date+the%3Cbr+%2F%3E%0Aregistrar%27s+sponsorship+of+the+domain+name+registration+in+the+registry+is%3Cbr+%2F%3E%0Acurrently+set+to+expire.+This+date+does+not+necessarily+reflect+the+expiration%3Cbr+%2F%3E%0Adate+of+the+domain+name+registrant%27s+agreement+with+the+sponsoring%3Cbr+%2F%3E%0Aregistrar.++Users+may+consult+the+sponsoring+registrar%27s+Whois+database+to%3Cbr+%2F%3E%0Aview+the+registrar%27s+reported+date+of+expiration+for+this+registration.%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0ATERMS+OF+USE%3A+You+are+not+authorized+to+access+or+query+our+Whois%3Cbr+%2F%3E%0Adatabase+through+the+use+of+electronic+processes+that+are+high-volume+and%3Cbr+%2F%3E%0Aautomated+except+as+reasonably+necessary+to+register+domain+names+or%3Cbr+%2F%3E%0Amodify+existing+registrations%3B+the+Data+in+VeriSign+Global+Registry%3Cbr+%2F%3E%0AServices%27+%28%22VeriSign%22%29+Whois+database+is+provided+by+VeriSign+for%3Cbr+%2F%3E%0Ainformation+purposes+only%2C+and+to+assist+persons+in+obtaining+information%3Cbr+%2F%3E%0Aabout+or+related+to+a+domain+name+registration+record.+VeriSign+does+not%3Cbr+%2F%3E%0Aguarantee+its+accuracy.+By+submitting+a+Whois+query%2C+you+agree+to+abide%3Cbr+%2F%3E%0Aby+the+following+terms+of+use%3A+You+agree+that+you+may+use+this+Data+only%3Cbr+%2F%3E%0Afor+lawful+purposes+and+that+under+no+circumstances+will+you+use+this+Data%3Cbr+%2F%3E%0Ato%3A+%281%29+allow%2C+enable%2C+or+otherwise+support+the+transmission+of+mass%3Cbr+%2F%3E%0Aunsolicited%2C+commercial+advertising+or+solicitations+via+e-mail%2C+telephone%2C%3Cbr+%2F%3E%0Aor+facsimile%3B+or+%282%29+enable+high+volume%2C+automated%2C+electronic+processes%3Cbr+%2F%3E%0Athat+apply+to+VeriSign+%28or+its+computer+systems%29.+The+compilation%2C%3Cbr+%2F%3E%0Arepackaging%2C+dissemination+or+other+use+of+this+Data+is+expressly%3Cbr+%2F%3E%0Aprohibited+without+the+prior+written+consent+of+VeriSign.+You+agree+not+to%3Cbr+%2F%3E%0Ause+electronic+processes+that+are+automated+and+high-volume+to+access+or%3Cbr+%2F%3E%0Aquery+the+Whois+database+except+as+reasonably+necessary+to+register%3Cbr+%2F%3E%0Adomain+names+or+modify+existing+registrations.+VeriSign+reserves+the+right%3Cbr+%2F%3E%0Ato+restrict+your+access+to+the+Whois+database+in+its+sole+discretion+to+ensure%3Cbr+%2F%3E%0Aoperational+stability.++VeriSign+may+restrict+or+terminate+your+access+to+the%3Cbr+%2F%3E%0AWhois+database+for+failure+to+abide+by+these+terms+of+use.+VeriSign%3Cbr+%2F%3E%0Areserves+the+right+to+modify+these+terms+at+any+time.%3Cbr+%2F%3E%0A%3Cbr+%2F%3E%0AThe+Registry+database+contains+ONLY+.COM%2C+.NET%2C+.EDU+domains+and%3Cbr+%2F%3E%0ARegistrars.%3Cbr+%2F%3E%0A"
}

console.log(decodeURIComponent(response.whois).replace(/\+/g, ' '));


问:
How to create a queryset that filters multiple fields based on a single condition in Django?
My model is

```<code>class TestModel(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    field4 = models.IntegerField()
    field5 = models.IntegerField()
</code>```

I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them.

For example I want to apply a condition of checking for None to two or more fields

```<code>TestModel.objects.filter(two_or_more_fields=None)
</code>```

I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than:

```<code>from django.db.models import Q
TestModel.objects.filter(
    #condition for exactly 2 None
    Q(field1=None & field2=None) |
    Q(field2=None & field3=None) |
    Q(field3=None & field4=None) |
    Q(field4=None & field5=None) |
    Q(field5=None & field1=None) |
    #condition for more than 2 None
    Q(field1=None & field2=None & field3 = None) |
    '''''
    .
    .
    #so on to cover all possible cases of any two or more fields as None
     )
</code>```

I think there should be a better and simple way to accomplish this.

答:
I'm not aware of any method for filtering by number of non null fields in Django.

One less clumsy and lookup-efficient workaround I would suggest is to store number of null fields (null_count) in Model itself as a field.

You can do that by easily overriding save method of TestModel.

```<code>def save(self, *args, **kwargs):
    self.null_count = 0
    self.null_count += 1 if self.field1 is None else 0
    # update null_count for 4 remaining fields
    super(TestModel, self).save(*args, **kwargs)
</code>```

And in view, filter on null_count.

```<code>TestModel.objects.filter(null_count_gt=2)
</code>```

Body:
My model is

class TestModel(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    field4 = models.IntegerField()
    field5 = models.IntegerField()

I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them.

For example I want to apply a condition of checking for None to two or more fields

TestModel.objects.filter(two_or_more_fields=None)

I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than:

from django.db.models import Q
TestModel.objects.filter(
    #condition for exactly 2 None
    Q(field1=None & field2=None) |
    Q(field2=None & field3=None) |
    Q(field3=None & field4=None) |
    Q(field4=None & field5=None) |
    Q(field5=None & field1=None) |
    #condition for more than 2 None
    Q(field1=None & field2=None & field3 = None) |
    '''''
    .
    .
    #so on to cover all possible cases of any two or more fields as None
     )

I think there should be a better and simple way to accomplish this.

Body:
I'm not aware of any method for filtering by number of non null fields in Django.

One less clumsy and lookup-efficient workaround I would suggest is to store number of null fields (null_count) in Model itself as a field.

You can do that by easily overriding save method of TestModel.

def save(self, *args, **kwargs):
    self.null_count = 0
    self.null_count += 1 if self.field1 is None else 0
    # update null_count for 4 remaining fields
    super(TestModel, self).save(*args, **kwargs)

And in view, filter on null_count.

TestModel.objects.filter(null_count_gt=2)


问:
Using an external HD to write to and store a mysql Database
I have set up mysql database to run with java and eclipse on my Mac, it is running great, but now I will generate aprox 4.3billion rows of data which will take up approx 64gbs of data, I'm storing a large about of keys and encrypted values, I have a 1TB external i would like to use as a storage location, i first thought i could reinstall mysql onto the external but it no luck as it obviously isnt running mac osx, Is there anyway i Can point mysql to store a database on the external, i have done some searching but have not come across an answer yet.

I am running Java to build and query the databse and Table if this comes into play.

Thanks.

答:
Don't reinstall mysql. You should use both the hdd and the external hard to store the data (rows/tables..) for mysql server.

Maybe by changing the path, but I haven't tried that.


问:
Android actionLayout not showing with Toolbar
I'm trying to show custom layout as an item in options menu.
And this is what I have done so far

```<code><item
    android:id="@+id/action_profile"
    android:orderInCategory="100"
    android:title="Profile"
    android:actionLayout="@layout/layout_menu_profile"
    app:showAsAction="never" />
</code>```

I tried

```<code>    app:actionLayout="@layout/layout_menu_profile"
</code>```

as well as per this SO link but still it shows only title - Profile

I have created new project through Android Studio 1.5 with Blank Activity.
with minSDK = 15 and targetSDK = 23

Following is the code in Blank Activity.

```<code>@Override
 public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_home, menu);

    MenuItem item = menu.findItem(R.id.action_profile);

    return true;
}
</code>```

where am I going wrong ?

答:
Try this code

```<code><item
android:id="@+id/action_profile"
android:orderInCategory="100"
android:title="Profile"
android:actionLayout="@layout/layout_menu_profile"
app:showAsAction="always" />
</code>```

Just set the showAsAction elements to always

Body:
I'm trying to show custom layout as an item in options menu.
And this is what I have done so far

<item
    android:id="@+id/action_profile"
    android:orderInCategory="100"
    android:title="Profile"
    android:actionLayout="@layout/layout_menu_profile"
    app:showAsAction="never" />

I tried

    app:actionLayout="@layout/layout_menu_profile"

as well as per this SO link but still it shows only title - Profile

I have created new project through Android Studio 1.5 with Blank Activity.
with minSDK = 15 and targetSDK = 23

Following is the code in Blank Activity.

@Override
 public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_home, menu);

    MenuItem item = menu.findItem(R.id.action_profile);

    return true;
}

where am I going wrong ?

Body:
Try this code

<item
android:id="@+id/action_profile"
android:orderInCategory="100"
android:title="Profile"
android:actionLayout="@layout/layout_menu_profile"
app:showAsAction="always" />

Just set the showAsAction elements to always


问:
"No executable found matching command dotnet-ef" error with EF Core database-first
As you know, the newest version of Visual Studio 2017 abandons the 'project.json' and uses .csproj instead.

I'm using the RTM version and want to generate model from an exist database, following this guide.  I got an error on the last step:

The Entity Framework Core commands for the Package Manager Console don't yet support csproj-based .NET Core projects. Use the .NET Command Line Tools (i.e. dotnet ef) instead. For more details, see https://go.microsoft.com/fwlink/?linkid=834381.

Following the error, I used the link it mentioned to switch to dotnet ef.  Here is my package manager command:

PM> dotnet ef dbcontext scaffold "Server=.;Database=Jumpstart;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer

Then the error comes again:

dotnet : No executable found matching command "dotnet-ef"

I used the help command, I found that dotnet does not have a command called ef.

I just want to generate a model from an existing database.

答:
My issue was solved by changing tools to:

```<code>"tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final"
  },
</code>```

Then execute these 2 commands:

dotnet restore - to restore packages

dotnet ef migrations

Body:
My issue was solved by changing tools to:

"tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final"
  },

Then execute these 2 commands:

dotnet restore - to restore packages

dotnet ef migrations


问:
How to get as e.target the exact element at which onClick is specified?
I have a React Component and give it onClick event handler:

```<code>function Item(props) {
  return <li onClick={props.onClick}>{props.children}</li>
}
</code>```

Then I use the Component like this:

```<code><Item onClick={ function(e) {console.log(e.target)} }>
  <span>This element is returned as e.target if clicked on it!</span>
</Item>
</code>```

When I click on the text, the span element is logged as target and when it is clicked outside given span, li element is logged as target.

The problem is:

If there is a lot of child elements inside li element, and id or name are have to be gotten, it becomes a "hacky" task...

The question is:

Is it possible to get inside a handler function as e.target the exact element at which onClick is specified (not it's children; in this case li)?

PS. No jQuery for solution if possible.

答:
Yes

const { render } = ReactDOM;
function Item(props) {
  return <li onClick={props.onClick}
             {props.children}

}

render(
  <Item onClick = {
    function(e) {
      console.log(e.currentTarget)
    }
  }>
     This element is returned as e.target if clicked on it!
  </Item>,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a React Component and give it onClick event handler:

function Item(props) {
  return
{props.children}

}

Then I use the Component like this:

<Item onClick={ function(e) {console.log(e.target)} }>
  This element is returned as e.target if clicked on it!
</Item>

When I click on the text, the span element is logged as target and when it is clicked outside given span, li element is logged as target.

The problem is:

If there is a lot of child elements inside li element, and id or name are have to be gotten, it becomes a "hacky" task...

The question is:

Is it possible to get inside a handler function as e.target the exact element at which onClick is specified (not it's children; in this case li)?

PS. No jQuery for solution if possible.

Body:
Yes

const { render } = ReactDOM;
function Item(props) {
  return <li onClick={props.onClick}
             {props.children}
         </li>
}

render(
  <Item onClick = {
    function(e) {
      console.log(e.currentTarget)
    }
  }>
    <span> This element is returned as e.target if clicked on it! </span>
  </Item>,
  document.getElementById('root')
);

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


问:
How to generate dropdownlist at runtime based on user Input
I want to generate dropdownlists based on the count entered by user.Suppose if the user enters 3, then 3 dropdownlists should be generated.
Here is my view

```<code>@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <div class="form-group">
            @Html.Label("Make", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Make", ViewBag.Make as SelectList, "Select",  new { @id = "ddlSelect",onchange ="GetOption();"})
            </div>
        </div>
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.Label("Count", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBox("Count","", new { @id = "textCount",onblur ="GetCount();"})
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Category, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Cost, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Cost, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" id="click" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
</code>```

first of all i am asking the user two select a value from dropdownlist..after that i am asking hime to enter the count..based on that count, i want to generate dropdownlists & want to populate them using viewbag data.

My Model Class is

```<code>public partial class Cables_List
{
    public int ID { get; set; }
    public string Category { get; set; }
    public Nullable<decimal> Dlink { get; set; }
    public Nullable<decimal> Molex { get; set; }
}
</code>```

& Here is my Controller

```<code>public class BOMController : Controller
{
    private InventoryContext db = new InventoryContext();

    // GET: BOM
    public ActionResult Cables()
    {
        ViewBag.Make = new SelectList(db.Make, "ID", "Name");
        ViewBag.Dlink = new SelectList(db.Cables_List, "Dlink", "Category");
        ViewBag.Molex = new SelectList(db.Cables_List,"Molex","Category")
        return View();
    }
</code>```

I just want to load data from Viewbag.Dlink & Viewbag.Molex . based on user selection from dropdownlist. I am using Database first Approach. Is there any way to achieve this in MVC or i have to use jquery.Kindly guide.

答:
Cable model:

```<code>public class Cable
{
    public int ID { get; set; }
    public string Category { get; set; }
    public decimal? Dlink { get; set; }
    public decimal? Molex { get; set; }
}
</code>```

Your ViewModel:

```<code>public class HomeViewModel
{
    public int Amount { get; set; }
    public List<Cable> Cables { get; set; }
}
</code>```

The Controller method:

```<code>public ActionResult GetCables(int Amount)
{
    var model = new HomeViewModel();
    model.Cables = db.Cables_List.ToList();

    return PartialView("_Cable.cshtml", model);
}
</code>```

_Cable.cshtml partial view:

```<code>@model HomeViewModel

@for (var i = 0; i < Model.Amount; i++)
{
    @Html.DropDownList("DDname", new SelectList(Model.Cables, "ID", "Category"))
}
</code>```

jQuery call:

```<code>$(this).on('blur', '#textCount', function () {
    var amount = $(this).val(); // get the inputed number (maybe check if is grater than 0)

    $.ajax({
        url: '/Home/GetCables',
        type: 'GET',
        data: { Amount: amount },
        success: function (data) {
            $('#CableWrapper')
                .empty()
                .append(data);
        }
    });
});
</code>```

And into your main view put the div where you want the dropdowns to be appended:

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

Body:
I want to generate dropdownlists based on the count entered by user.Suppose if the user enters 3, then 3 dropdownlists should be generated.
Here is my view

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

            @Html.Label("Make", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("Make", ViewBag.Make as SelectList, "Select",  new { @id = "ddlSelect",onchange ="GetOption();"})

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.Label("Count", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.TextBox("Count","", new { @id = "textCount",onblur ="GetCount();"})

            @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Category, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Cost, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Cost, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })

                <input type="submit" id="click" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

first of all i am asking the user two select a value from dropdownlist..after that i am asking hime to enter the count..based on that count, i want to generate dropdownlists & want to populate them using viewbag data.

My Model Class is

public partial class Cables_List
{
    public int ID { get; set; }
    public string Category { get; set; }
    public Nullable<decimal> Dlink { get; set; }
    public Nullable<decimal> Molex { get; set; }
}

& Here is my Controller

public class BOMController : Controller
{
    private InventoryContext db = new InventoryContext();

    // GET: BOM
    public ActionResult Cables()
    {
        ViewBag.Make = new SelectList(db.Make, "ID", "Name");
        ViewBag.Dlink = new SelectList(db.Cables_List, "Dlink", "Category");
        ViewBag.Molex = new SelectList(db.Cables_List,"Molex","Category")
        return View();
    }

I just want to load data from Viewbag.Dlink & Viewbag.Molex . based on user selection from dropdownlist. I am using Database first Approach. Is there any way to achieve this in MVC or i have to use jquery.Kindly guide.

Body:
Cable model:

public class Cable
{
    public int ID { get; set; }
    public string Category { get; set; }
    public decimal? Dlink { get; set; }
    public decimal? Molex { get; set; }
}

Your ViewModel:

public class HomeViewModel
{
    public int Amount { get; set; }
    public List<Cable> Cables { get; set; }
}

The Controller method:

public ActionResult GetCables(int Amount)
{
    var model = new HomeViewModel();
    model.Cables = db.Cables_List.ToList();

    return PartialView("_Cable.cshtml", model);
}

_Cable.cshtml partial view:

@model HomeViewModel

@for (var i = 0; i < Model.Amount; i++)
{
    @Html.DropDownList("DDname", new SelectList(Model.Cables, "ID", "Category"))
}

jQuery call:

$(this).on('blur', '#textCount', function () {
    var amount = $(this).val(); // get the inputed number (maybe check if is grater than 0)

    $.ajax({
        url: '/Home/GetCables',
        type: 'GET',
        data: { Amount: amount },
        success: function (data) {
            $('#CableWrapper')
                .empty()
                .append(data);
        }
    });
});

And into your main view put the div where you want the dropdowns to be appended:

<div id="CableWrapper"></div>


问:
How to allow inbound calls in pjsip and Asterisk 13?
I have configured Asterisk 13.13.1 with PJProject 2.5.5 and enable PJSIP as SIP driver (without compiling chan_sip).

I have the fully configured system and it's working but I have some problems with incoming calls. I have few numbers connected with my host and when I calling from any public number I noticed this info on asterisk remote console:

```<code>[Feb 24 14:27:16] NOTICE[5291]: res_pjsip/pjsip_distributor.c:525 log_failed_request: Request 'INVITE' from '"zzzzz" <sip:zzzzz@192.168.34.1>' failed for '192.168.34.1:5062' (callid: 0e07e7607f8f62dd225347363173bb9f@192.168.34.1:5062) - No matching endpoint found
</code>```

And if I add the number which is calling to my Asterisk to endpoints then it's working - I can pick up this call.

How to add the possibility to allow all inbound calls?

答:
You need to create an anonymous endpoint to accept inbound calls from unknown endpoints.

Be aware that adding an anonymous endpoint opens the system to extension scanning attacks where scanners try to find out which extensions you have configured in your system. They do this either to spam you with advertising calls, or exploit call transferring to call long distance numbers, or for some other ulterior motive.

After creating an anonymous endpoint, associate it with a context different from that used by your extensions.  This prevents them from dialing long-distance through your trunks.

To add an anonymous endpoint in pjsip.conf, add the following lines:

```<code>[anonymous]
type=endpoint
context=anonymous
disallow=all
allow=speex,g726,g722,ilbc,gsm,alaw
</code>```

In the dialplan extensions.conf:

```<code>[anonymous]
exten => _XXXXX,1,GotoIf(${DIALPLAN_EXISTS(local-extensions,${EXTEN},1)}?local-extensions,${EXTEN},1)
 same => n,Hangup(1)
</code>```

local-extensions is the context listing your local extensions.

Body:
I have configured Asterisk 13.13.1 with PJProject 2.5.5 and enable PJSIP as SIP driver (without compiling chan_sip).

I have the fully configured system and it's working but I have some problems with incoming calls. I have few numbers connected with my host and when I calling from any public number I noticed this info on asterisk remote console:

[Feb 24 14:27:16] NOTICE[5291]: res_pjsip/pjsip_distributor.c:525 log_failed_request: Request 'INVITE' from '"zzzzz" <sip:zzzzz@192.168.34.1>' failed for '192.168.34.1:5062' (callid: 0e07e7607f8f62dd225347363173bb9f@192.168.34.1:5062) - No matching endpoint found

And if I add the number which is calling to my Asterisk to endpoints then it's working - I can pick up this call.

How to add the possibility to allow all inbound calls?

Body:
You need to create an anonymous endpoint to accept inbound calls from unknown endpoints.

Be aware that adding an anonymous endpoint opens the system to extension scanning attacks where scanners try to find out which extensions you have configured in your system. They do this either to spam you with advertising calls, or exploit call transferring to call long distance numbers, or for some other ulterior motive.

After creating an anonymous endpoint, associate it with a context different from that used by your extensions.  This prevents them from dialing long-distance through your trunks.

To add an anonymous endpoint in pjsip.conf, add the following lines:

[anonymous]
type=endpoint
context=anonymous
disallow=all
allow=speex,g726,g722,ilbc,gsm,alaw

In the dialplan extensions.conf:

[anonymous]
exten => _XXXXX,1,GotoIf(${DIALPLAN_EXISTS(local-extensions,${EXTEN},1)}?local-extensions,${EXTEN},1)
 same => n,Hangup(1)

local-extensions is the context listing your local extensions.


问:
How to get data from database to view page in laravel?
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

```<code><div class="table-responsive">
  <table class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th><strong>No</strong></th>
        <th><strong>Nama Petani</strong></th>
        <th><strong>Alamat</strong></th>
        <th><strong>No. Handphone</strong></th>
        <th><strong>Lokasi</strong></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </tbody>
  </table>
</div>
</code>```

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

```<code>Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});
</code>```

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

答:
Try this:

```<code>$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
</code>```

on your view iterate $petani using foreach() like:

```<code>foreach($petani as $data)
{
    echo $data->id_user;  // $petani is a Std Class Object here
    echo $data->username;
}
</code>```

Body:
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

        No
        Nama Petani
        Alamat
        No. Handphone
        Lokasi

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

Body:
Try this:

$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);

on your view iterate $petani using foreach() like:

foreach($petani as $data)
{
    echo $data->id_user;  // $petani is a Std Class Object here
    echo $data->username;
}


问:
CardView custom background
I try to add custom background in my CardView.This is my source

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/item_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff00"
android:orientation="vertical">

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="12dp"
    card_view:cardElevation="12dp"
    card_view:cardPreventCornerOverlap="false"
    card_view:contentPadding="0dp"
    android:layout_margin="16dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#cccccc">
        </RelativeLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</code>```

As you can see into Cardview i have LinearLayout and RelativieLayout.RelativeLayout's background color is #cccccc,but cornerradius and elevetion not working with custom background color.(please see my picture)
How i can solve my problem?

答:
Your Linear Layout inside CardView is overlapping your cardview's top corners due to fix height given to linear layout. When giving height to cardview  and making linear layout match_parent, and giving contentPadding in cardview makes corners visible.

Here is the code and screenshot.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/item_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff00"
android:orientation="vertical">

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    card_view:cardCornerRadius="12dp"
    card_view:cardElevation="12dp"
    card_view:cardPreventCornerOverlap="true"
    card_view:contentPadding="2dp"
    android:layout_margin="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#cccccc">
        </RelativeLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</code>```

Screenshot

Title: CardView custom background

Body:
I try to add custom background in my CardView.This is my source

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/item_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff00"
android:orientation="vertical">

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="12dp"
    card_view:cardElevation="12dp"
    card_view:cardPreventCornerOverlap="false"
    card_view:contentPadding="0dp"
    android:layout_margin="16dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#cccccc">
        </RelativeLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

As you can see into Cardview i have LinearLayout and RelativieLayout.RelativeLayout's background color is #cccccc,but cornerradius and elevetion not working with custom background color.(please see my picture)
How i can solve my problem?

Body:
Your Linear Layout inside CardView is overlapping your cardview's top corners due to fix height given to linear layout. When giving height to cardview  and making linear layout match_parent, and giving contentPadding in cardview makes corners visible.

Here is the code and screenshot.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/item_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff00"
android:orientation="vertical">

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    card_view:cardCornerRadius="12dp"
    card_view:cardElevation="12dp"
    card_view:cardPreventCornerOverlap="true"
    card_view:contentPadding="2dp"
    android:layout_margin="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#cccccc">
        </RelativeLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

Screenshot


问:
Most efficient way to get the highest number from a collection of integers
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

```<code>int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }
</code>```

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?

答:
Here is my favorite argument which I always uses to quick judge such question:

You have to use at least O(N) just to look all elements, which is
  I/O time.

Without thinking too much, it can persuade myself that no algorithms can beat any O(N) algorithms in terms of complexity. Hope it makes sense.

Body:
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?


问:
Can AJAX create a Timeout when the request is back in time, but the JS thread is busy?
Is it possible for an ajax request to return a timeout, because the JavaScript thread is unavailable?

Say I send a request, after which the backend returns a success code ~500 ms later. Immediately after sending the request, I perform a really expensive function (using practically all CPU for 10 seconds), will my request end up as en error due to the timeout, or as a success because it was the function returned after 500ms?

```<code>$.ajax({
    url: "my/url",
    error: function(){
       //do something
    },
    success: function(){
       //do something
    },
    timeout: 5000
});
expensiveFunction(); //takes 10 seconds
</code>```

答:
Why not try it? It's the best way to find these things out.

Note - running the below snippet will probably lock up your browser for about 5 seconds.

document.getElementById('start').addEventListener('click',startAjaxRequest);
function startAjaxRequest() {
  var errorTimer;

  function asyncFunction(callback) {
      errorTimer = setTimeout(fail, 2000);
      document.getElementById('FakeServerResponse').addEventListener('click',callback);
  }

  function fail() {
    console.log("Error!");
  }

  function cpuHog() {
      var startTime = new Date().getTime();
      var i = 0;
      while(startTime > new Date().getTime() - (1000 * 5)) {
        i++;
      }
      console.log("Cpu Hogging process is done");
      return i;
  }

  asyncFunction(function() {
    clearTimeout(errorTimer);
    console.log("Async process is complete");
  });
  setTimeout(cpuHog,0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="start">Start!</button>
<button id="FakeServerResponse">Click to fake the Server Responding</button></code>```

Try clicking start then immediately clicking the "Click to fake the Server Responding" button. You'll see the console says the process is complete.

Then try clicking start and not faking the server response. You'll see the error callback is hit.

This is because when new events (literal events triggering, or timeouts firing) occur in javascript, they are added to a "message queue" which is evaluated one by one when javascript has time. When the server responds to your request, an event is fired inside jquery (readystatechange) which is added to that message queue. Similarly, your timeout (of 2000ms in the example I have created) is just placed in a setTimeout inside jquery. When the timeout is up, an event is added to the message queue to evaluate that timeout. So long as this event is added after the server responded, the server response will be evaluated first. If the timeout gets hit before the server responded, then the error will occur first.

Body:
Is it possible for an ajax request to return a timeout, because the JavaScript thread is unavailable?

Say I send a request, after which the backend returns a success code ~500 ms later. Immediately after sending the request, I perform a really expensive function (using practically all CPU for 10 seconds), will my request end up as en error due to the timeout, or as a success because it was the function returned after 500ms?

$.ajax({
    url: "my/url",
    error: function(){
       //do something
    },
    success: function(){
       //do something
    },
    timeout: 5000
});
expensiveFunction(); //takes 10 seconds

Body:
Why not try it? It's the best way to find these things out.

Note - running the below snippet will probably lock up your browser for about 5 seconds.

document.getElementById('start').addEventListener('click',startAjaxRequest);
function startAjaxRequest() {
  var errorTimer;

  function asyncFunction(callback) {
      errorTimer = setTimeout(fail, 2000);
      document.getElementById('FakeServerResponse').addEventListener('click',callback);
  }

  function fail() {
    console.log("Error!");
  }

  function cpuHog() {
      var startTime = new Date().getTime();
      var i = 0;
      while(startTime > new Date().getTime() - (1000 * 5)) {
        i++;
      }
      console.log("Cpu Hogging process is done");
      return i;
  }

  asyncFunction(function() {
    clearTimeout(errorTimer);
    console.log("Async process is complete");
  });
  setTimeout(cpuHog,0);
}

<button id="start">Start!</button>
<button id="FakeServerResponse">Click to fake the Server Responding</button>

Try clicking start then immediately clicking the "Click to fake the Server Responding" button. You'll see the console says the process is complete.

Then try clicking start and not faking the server response. You'll see the error callback is hit.

This is because when new events (literal events triggering, or timeouts firing) occur in javascript, they are added to a "message queue" which is evaluated one by one when javascript has time. When the server responds to your request, an event is fired inside jquery (readystatechange) which is added to that message queue. Similarly, your timeout (of 2000ms in the example I have created) is just placed in a setTimeout inside jquery. When the timeout is up, an event is added to the message queue to evaluate that timeout. So long as this event is added after the server responded, the server response will be evaluated first. If the timeout gets hit before the server responded, then the error will occur first.


问:
Wordpress query to only include posts that have certain content
I would like this query to only show the posts if it contains and text that comes from geodir_special_offers echo

```<code><?php

global $post;

$args = array(

 'posts_per_page' => 4 , 'post_type' => 'gd_arts',);

$lastposts = get_posts( $args ); foreach ( $lastposts as $post ) : setup_postdata( $post ); ?>

<h2><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2>

<?php if ( has_post_thumbnail() ) {
            the_post_thumbnail(array(486,226));
        } ?>
<php echo $post->geodir_special_offers; ?>

<?php endforeach;
wp_reset_postdata();
?>
</code>```

I am quite new to WP queries so bear with me.

Sorry in advance if it is not structured 100%.

答:
Try this!It checks if the special offers is set before echoing out the content. Hope that's what you were looking for.</p>

```<code><?php

global $post;

$args = array(

 'posts_per_page' => 4 , 'post_type' => 'gd_arts',);

$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) {?>
<?php if(strlen ($post->geodir_special_offers) > 5){ ?>
<h2><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2>

<?php if ( has_post_thumbnail() ) {
            the_post_thumbnail(array(486,226));
        }

    }
}
wp_reset_postdata();
?>
</code>```

Body:
I would like this query to only show the posts if it contains and text that comes from geodir_special_offers echo

<?php

global $post;

$args = array(

 'posts_per_page' => 4 , 'post_type' => 'gd_arts',);

$lastposts = get_posts( $args ); foreach ( $lastposts as $post ) : setup_postdata( $post ); ?>

<a href="<?php the_permalink(); ?>"> <?php the_title(); ?>

<?php if ( has_post_thumbnail() ) {
            the_post_thumbnail(array(486,226));
        } ?>
<php echo $post->geodir_special_offers; ?>

<?php endforeach;
wp_reset_postdata();
?>

I am quite new to WP queries so bear with me.

Sorry in advance if it is not structured 100%.

Body:
Try this!It checks if the special offers is set before echoing out the content. Hope that's what you were looking for.

<?php

global $post;

$args = array(

 'posts_per_page' => 4 , 'post_type' => 'gd_arts',);

$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) {?>
<?php if(strlen ($post->geodir_special_offers) > 5){ ?>
<h2><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2>

<?php if ( has_post_thumbnail() ) {
            the_post_thumbnail(array(486,226));
        }

    }
}
wp_reset_postdata();
?>


问:
PHP & PDO: Can connect to DB; can't seem to query
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

```<code> private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }
</code>```

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

答:
In order to get the error in your query:</p>

```<code>$result = $link->query(...);
if($result===FALSE){
   print_r( $link->errorInfo);
   exit();
}

// the correct way to fetch one row
$link->fetch(PDO::FETCH_ASSOC); // or whatever way you want to fetch data
</code>```

Body:
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:

 private function connect() {
      try {
           $link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
      }
           catch (PDOException $e) {
           die ($e);
      }
      print_r($link);
      $result = $link->query("select * from mt3_users");
      var_dump($result);
      $row = $result->fetch($result);
      die("Your id is: ".$row["id"]);
      //$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
      if (!$link) {
          echo "Failed to connect to $this->sHost!";
          return false;
      }
      return $link;
 }

This returns the following:

PDO Object ( ) bool(false)
  Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32

So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?

Body:
In order to get the error in your query:

$result = $link->query(...);
if($result===FALSE){
   print_r( $link->errorInfo);
   exit();
}

// the correct way to fetch one row
$link->fetch(PDO::FETCH_ASSOC); // or whatever way you want to fetch data


问:
How can I find the user role using user id in moodle
I am new to Moodle and I have the following code:

```<code>$userDetails = $DB->get_record('user', array('id' => $singleuser->userid));
    var_dump($userDetails);
    echo $userDetails->firstname." ".$userDetails->lastname
</code>```

It is having the details of user table in Moodle. How can I find the role like Teacher, Admin, student?

Here I am having the userids $singleuser->userid . I am printing Users full name . I need the role along with it like the following:

```<code>echo $userDetails->firstname." ".$userDetails->lastname.$role.
</code>```

How can I find role? Please guide me.

Moodle Version: 2.9.1

答:
moodle get user roles in static pages like about..etc

```<code>$context = context_module::instance($cm->id);

$roles = get_user_roles($context, $USER->id, true);

foreach ($roles as $role) {

}
</code>```

Body:
I am new to Moodle and I have the following code:

$userDetails = $DB->get_record('user', array('id' => $singleuser->userid));
    var_dump($userDetails);
    echo $userDetails->firstname." ".$userDetails->lastname

It is having the details of user table in Moodle. How can I find the role like Teacher, Admin, student?

Here I am having the userids $singleuser->userid . I am printing Users full name . I need the role along with it like the following:

echo $userDetails->firstname." ".$userDetails->lastname.$role.

How can I find role? Please guide me.

Moodle Version: 2.9.1

Body:
moodle get user roles in static pages like about..etc

$context = context_module::instance($cm->id);

$roles = get_user_roles($context, $USER->id, true);

foreach ($roles as $role) {

}


答:
Using this you can get month wise result

```<code> select month(EVENT_DATE),year(EVENT_DATE), USER_ID from tableName
 where  year(EVENT_DATE)=2017
 Group by USER_ID,year(EVENT_DATE),month(EVENT_DATE)
 Having HAVING  COUNT(*) > 1
</code>```

if you want some specific month wise you can add where condition like  month(EVENT_DATE) =3

Title: Users that returned

Body:
I have a table with [EVENT_DATE] and [USER_ID], I would like to know how to count the users who came back in the same month.

Table_01
-------------------------------------------
    EVENT_DATE          |   USER_ID
-------------------------------------------
2017-03-28 00:00:25.000 | 0006235012201
2017-03-04 23:00:00.000 | 0006235012201
2017-03-19 00:25:15.000 | 0006235012201
2017-02-03 10:00:02.000 | 0006235012202
2017-01-18 00:15:00.000 | 0006235012202
2017-03-28 11:00:15.000 | 0006235012202
2017-03-23 15:20:02.000 | 0006235012203
2017-02-18 12:00:06.000 | 0006235012203
2017-03-21 16:05:09.000 | 0006235012203

The answering being 2, because users 0006235012201 & 0006235012203 both came back within the same month.

EDIT: Sorry

I am looking to get the count by month.

-----------------------
Month | Users Returned
-----------------------
01/17 | 70
02/17 | 60
03/17 | 10

This is what I have, but it isn't correct as it seems to be listing users.

SELECT A.[USER_ID], A.[EVENT_DATE], COUNT(*)
FROM(
    SELECT [USER_ID], [EVENT_DATE], COUNT(*)
    FROM Table_01
    GROUP BY [USER_ID], [EVENT_DATE]
    HAVING COUNT(*) > 1
     ) A
GROUP BY A.[USER_ID], A.[EVENT_DATE]

Microsoft SQL Server 2016. Compatibility level: SQL Server 2005 (90)

Body:
Using this you can get month wise result

 select month(EVENT_DATE),year(EVENT_DATE), USER_ID from tableName
 where  year(EVENT_DATE)=2017
 Group by USER_ID,year(EVENT_DATE),month(EVENT_DATE)
 Having HAVING  COUNT(*) > 1

if you want some specific month wise you can add where condition like  month(EVENT_DATE) =3


问:
React not passing state to child via props
I am trying to pass my parent App state to a child component Chart.

App

```<code>constructor() {
    super();
    this.state = {
        dataPoints: {
            '424353': {
                date: '10/10/2016',
                qty: '95'
            },
            '535332': {
                date: '10/11/2016',
                qty: '98'
            },
            '3453432': {
                date: '10/01/2017',
                qty: '94'
            }
        }
    };
    this.addPoint = this.addPoint.bind(this);
}

addPoint(dataPoint) {
    let dataPoints = {...this.state.dataPoints};
    const timestamp = Date.now();
    dataPoints[timestamp] = dataPoint;
    this.setState({ dataPoints: dataPoints });
    console.log('new state', this.state.dataPoints);
}

render() {
    return (
        <div className="app">
            <Chart dataPoints={this.state.dataPoints} />
            <FormControl addPoint={this.addPoint} />
        </div>
    );
}
</code>```

Chart

```<code>composeData() {
    Object
        .keys(this.props.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}

componentWillUpdate() {
    this.composeData();
}
</code>```

The addPoint method works, i.e. I can see in the React console that the new datapoint is added to the state. But it is not reflected in the Chart component. More oddly (to me) is the fact that when I've added a point, the console.log line in my addPoint method (above):

console.log('new state', this.state.dataPoints)

does not show the new data point.

答:
Because setState is asynchronous, use this you see the updated values:

```<code>this.setState({ dataPoints: dataPoints }, () => {
     console.log('new state', this.state.dataPoints);
});
</code>```

Second thing is, whenever any change happen to props values, componentWillReceiveProps lifecycle method will get called, do the computation in this method once you add the new item. Like this:

```<code>componentWillReceiveProps(newProps) {
    console.log('update props values', newProps);
    Object
        .keys(newProps.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}
</code>```

Check this answer for complete explanation: why setState is asynchronous.

Body:
I am trying to pass my parent App state to a child component Chart.

App

constructor() {
    super();
    this.state = {
        dataPoints: {
            '424353': {
                date: '10/10/2016',
                qty: '95'
            },
            '535332': {
                date: '10/11/2016',
                qty: '98'
            },
            '3453432': {
                date: '10/01/2017',
                qty: '94'
            }
        }
    };
    this.addPoint = this.addPoint.bind(this);
}

addPoint(dataPoint) {
    let dataPoints = {...this.state.dataPoints};
    const timestamp = Date.now();
    dataPoints[timestamp] = dataPoint;
    this.setState({ dataPoints: dataPoints });
    console.log('new state', this.state.dataPoints);
}

render() {
    return (

            <Chart dataPoints={this.state.dataPoints} />
            <FormControl addPoint={this.addPoint} />

    );
}

Chart

composeData() {
    Object
        .keys(this.props.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}

componentWillUpdate() {
    this.composeData();
}

The addPoint method works, i.e. I can see in the React console that the new datapoint is added to the state. But it is not reflected in the Chart component. More oddly (to me) is the fact that when I've added a point, the console.log line in my addPoint method (above):

console.log('new state', this.state.dataPoints)

does not show the new data point.

Body:
Because setState is asynchronous, use this you see the updated values:

this.setState({ dataPoints: dataPoints }, () => {
     console.log('new state', this.state.dataPoints);
});

Second thing is, whenever any change happen to props values, componentWillReceiveProps lifecycle method will get called, do the computation in this method once you add the new item. Like this:

componentWillReceiveProps(newProps) {
    console.log('update props values', newProps);
    Object
        .keys(newProps.dataPoints)
        .forEach(key => {
            ** do stuff **
        });

    return **stuff**;
}

Check this answer for complete explanation: why setState is asynchronous.


问:
Working way to make video from images in C#
Does anybody have a known reliable way to create a video from a series of image files?  Before you mod me down for not searching for the answer before posting the question, and before you fire off a simple message like "use FFMPEG," read the rest of this message.

I'm trying to create a video, it doesn't matter too much what format as long as it's widely supported, from a series of images (.jpg, .bmp, etc.).  My platform is Windows Server 2008, 64-bit.  If I can make the video from within my C# program, that's great, but I'm not averse to writing a series of image files to a directory and then firing off an external program to make a video from those images.

The only constraints are: it must work on my Windows Server 2008 system, and be scriptable.  That is, no GUI programs that require operator intervention.

I found a number of similar questions on StackOverflow, and have tried several of the solutions, all with varying degrees of frustration and none with anything like success.

FFMPEG looks like a great program.  Maybe it is, on Linux.  The two Windows builds I downloaded are broken.  Given this command line:

```<code>  ffmpeg -r 1 -f image2 -i jpeg\*.jpg video.avi
</code>```

One of the builds reads the images and then crashes due to data execution prevention.  The other reads the first file and then spits out an error message that says "cannot find suitable codec for file jpeg/image2.jpg".  Helpful, that.  In any case, FFMPEG looks like a non-starter under Windows.

One answer to a previous posting recommended Splicer .  It looks like pretty good code.  I compiled the samples and tried to run, but got some cryptic error message about a file not found.  It looks like a COM class isn't registered.  I suppose I need to install something (DirectShow, maybe, although I thought that was already installed?).  Depending on what's required, I might have a difficult time justifying its installation on a server.  ("What?  Why do you need that on a server?")

Another answer suggested the AviFile library from Code Project.  That looks simple enough:  a wrapper around the Windows AviFile subsystem.  Except that the AVI files the package creates appear to have all of the frames, but only the first frame shows when I play the AVI in Windows Media Player.  Well, that and if you try to create a compressed video, the program throws an exception.

So, I'm left wondering if there is a good, reliable way to do what I want: on a Windows system, create an AVI or other common video file format from a series of images, either through a .NET API or using an external program.  Any help?

答:
Instead of just going through all the hassle, you could coppy all the images that you want to be included in your video to the clipboard and have it imported into Windows Live Movie Maker (dynamically, of course!) and have it compile for you!

All of this CAN be done through code, but this way, you don't have to create it yourself. As you said that the platform was Windows, and ALL Windows comps have Windows Live Movie Maker installed, so it shouldn't be a problem for anyone using your application unless

a) They uninstalled Windows Live Movie Maker

b) They are using a computer running on a Windows Version more than 8 or 9 years old...

OwnerDisplayName: Jim Mischel

Body:
Does anybody have a known reliable way to create a video from a series of image files?  Before you mod me down for not searching for the answer before posting the question, and before you fire off a simple message like "use FFMPEG," read the rest of this message.

I'm trying to create a video, it doesn't matter too much what format as long as it's widely supported, from a series of images (.jpg, .bmp, etc.).  My platform is Windows Server 2008, 64-bit.  If I can make the video from within my C# program, that's great, but I'm not averse to writing a series of image files to a directory and then firing off an external program to make a video from those images.

The only constraints are: it must work on my Windows Server 2008 system, and be scriptable.  That is, no GUI programs that require operator intervention.

I found a number of similar questions on StackOverflow, and have tried several of the solutions, all with varying degrees of frustration and none with anything like success.

FFMPEG looks like a great program.  Maybe it is, on Linux.  The two Windows builds I downloaded are broken.  Given this command line:

  ffmpeg -r 1 -f image2 -i jpeg\*.jpg video.avi

One of the builds reads the images and then crashes due to data execution prevention.  The other reads the first file and then spits out an error message that says "cannot find suitable codec for file jpeg/image2.jpg".  Helpful, that.  In any case, FFMPEG looks like a non-starter under Windows.

One answer to a previous posting recommended Splicer .  It looks like pretty good code.  I compiled the samples and tried to run, but got some cryptic error message about a file not found.  It looks like a COM class isn't registered.  I suppose I need to install something (DirectShow, maybe, although I thought that was already installed?).  Depending on what's required, I might have a difficult time justifying its installation on a server.  ("What?  Why do you need that on a server?")

Another answer suggested the AviFile library from Code Project.  That looks simple enough:  a wrapper around the Windows AviFile subsystem.  Except that the AVI files the package creates appear to have all of the frames, but only the first frame shows when I play the AVI in Windows Media Player.  Well, that and if you try to create a compressed video, the program throws an exception.

So, I'm left wondering if there is a good, reliable way to do what I want: on a Windows system, create an AVI or other common video file format from a series of images, either through a .NET API or using an external program.  Any help?


问:
Setup private docker registry with anonymous pull access
I'd like to setup a docker registry that allows anonymous pulls but authenticates pushes.

My naive approach was to allow get requests. But that seems to break the login as the client only creates the credentials if the initial Get request to /v2/ yields a 401.

However also repository reads start with that so I cannot put this behind authentication either.

Basically it seems I'd have to distinguish between a ping before a pull and a ping before a login.

I'm also happy to setup token authentication. But that would probably run into the same conundrum.

答:
Apparently the way to go is to set up token authentication.

Then you can return a valid token for the scope pull even if no Basic Authentication was given.

You can find an example code on https://github.com/cloudfleet/floating-dock/blob/master/app/controllers/api/v1/jwt_controller.rb and https://github.com/cloudfleet/floating-dock/blob/master/app/services/auth/container_registry_authentication_service.rb

It is an adapted version of GitLabs JWT implementation for the registry.


问:
Maven: copy only build jars and not build poms
I have the following maven structure:

```<code>ParentProject
|-project-1
| |-src
| |-pom.xml
|-project-N
| |-src
| |-pom.xml
|-pom.xml
</code>```

In parent project pom I use the following plugin for copying:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.6</version>
    <executions>
    <execution>
        <id>copy</id>
        <phase>package</phase>
        <goals>
          <goal>copy</goal>
        </goals>
        <configuration>
            <artifactItems>
                <artifactItem>
                  <groupId>${project.groupId}</groupId>
                  <artifactId>${project.artifactId}</artifactId>
                  <version>${project.version}</version>
                  <type>${project.packaging}</type>
                  <outputDirectory>/somepath/jars</outputDirectory>
                </artifactItem>
            </artifactItems>
        </configuration>
        </execution>
    </executions>
</plugin>
</code>```

I use this plugin in parent project pom but not in project-1/N because I don't want to duplicate using this plugin and output directories (in some cases there can be one directory,in same cases several). The plugin works well. However, it also copies build parent project pom. How can I copy only project-1/N jars without parent project pom?

答:
One way you can achieve it is by adding skip to true inside your parent:

```<code>          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                    <skip>true</skip>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${project.artifactId}</artifactId>
                                <version>${project.version}</version>
                                <type>${project.packaging}</type>
                                <outputDirectory>${project.build.directory}/lib/</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

And then switch it to false in your children:

```<code>         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <skip>false</skip>
                    </configuration>
                </execution>
            </executions>
         </plugin>
</code>```

Body:
I have the following maven structure:

ParentProject
|-project-1
| |-src
| |-pom.xml
|-project-N
| |-src
| |-pom.xml
|-pom.xml

In parent project pom I use the following plugin for copying:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.6</version>
    <executions>
    <execution>
        <id>copy</id>
        <phase>package</phase>
        <goals>
          <goal>copy</goal>
        </goals>
        <configuration>
            <artifactItems>
                <artifactItem>
                  <groupId>${project.groupId}</groupId>
                  <artifactId>${project.artifactId}</artifactId>
                  <version>${project.version}</version>
                  <type>${project.packaging}</type>
                  <outputDirectory>/somepath/jars</outputDirectory>
                </artifactItem>
            </artifactItems>
        </configuration>
        </execution>
    </executions>
</plugin>

I use this plugin in parent project pom but not in project-1/N because I don't want to duplicate using this plugin and output directories (in some cases there can be one directory,in same cases several). The plugin works well. However, it also copies build parent project pom. How can I copy only project-1/N jars without parent project pom?

Body:
One way you can achieve it is by adding skip to true inside your parent:

          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                    <skip>true</skip>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${project.artifactId}</artifactId>
                                <version>${project.version}</version>
                                <type>${project.packaging}</type>
                                <outputDirectory>${project.build.directory}/lib/</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

And then switch it to false in your children:

         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <skip>false</skip>
                    </configuration>
                </execution>
            </executions>
         </plugin>


问:
Wordpress permalinks does not work on server
I have uploaded WordPress website to a new server which is working fine. But Permalinks settings are not working. All other pages returning me 404 error.

and below in my .htaccess file

```

        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]

```

答:
please check the apache module rewrite.

in a root wordpress folder insert into index.php phpinfo();
and find this string mod_rewrite. If it`s not, tell it your hoster support

Body:
I have uploaded WordPress website to a new server which is working fine. But Permalinks settings are not working. All other pages returning me 404 error.

and below in my .htaccess file

        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]


问:
allocate specific amount of memory in swift - iOS
I am learning Instruments so I created a simple app that lets the user input a number of Mega Bytes (MB) to be allocated. And I use the "Allocations" tool in Instruments to make sure this exact amount of data is allocated. However, I always see more memory allocated in Instruments than I expect.

I did the following

```<code>func allocateMemoryOfSize(numberOfBytes: Int) {

    var bytesArray = [Int8]()
    for i in 0 ..< numberOfBytes {
        bytesArray.append(Int8(i % 7))
    }
}
</code>```

I checked many questions and I found an alternative using:

```<code>func allocateMemoryOfSize(numberOfBytes: Int) {
      var imageData = UnsafeMutablePointer<Int8>.alloc(numberOfBytes)}
</code>```

But I still get more memory allocated. Here is the restults in Instruments when I allocate 10 MBs:

Before running the allocateMemoryOfSize function:

During the running of the function: 44.96 MB used

After the running of the function: back to only 20.58 MB

So, the function allocates around 22 MBs not 10 as wanted. What am I doing wrong? or is this extra memory management stuff?

答:
I did this:</p>

```<code>static var buffer = [UInt8]()
static func allocateMemoryOfSize(numberOfMegaBytes: Int) {
    print("Allocating \(numberOfMegaBytes)MB of memory")
    let mb = 1048576
    let newBuffer = [UInt8](count: numberOfMegaBytes * mb, repeatedValue: 0)
   buffer += newBuffer
}
</code>```

Body:
I am learning Instruments so I created a simple app that lets the user input a number of Mega Bytes (MB) to be allocated. And I use the "Allocations" tool in Instruments to make sure this exact amount of data is allocated. However, I always see more memory allocated in Instruments than I expect.

I did the following

func allocateMemoryOfSize(numberOfBytes: Int) {

    var bytesArray = [Int8]()
    for i in 0 ..< numberOfBytes {
        bytesArray.append(Int8(i % 7))
    }
}

I checked many questions and I found an alternative using:

func allocateMemoryOfSize(numberOfBytes: Int) {
      var imageData = UnsafeMutablePointer<Int8>.alloc(numberOfBytes)}

But I still get more memory allocated. Here is the restults in Instruments when I allocate 10 MBs:

Before running the allocateMemoryOfSize function:

During the running of the function: 44.96 MB used

After the running of the function: back to only 20.58 MB

So, the function allocates around 22 MBs not 10 as wanted. What am I doing wrong? or is this extra memory management stuff?

Body:
I did this:

static var buffer = [UInt8]()
static func allocateMemoryOfSize(numberOfMegaBytes: Int) {
    print("Allocating \(numberOfMegaBytes)MB of memory")
    let mb = 1048576
    let newBuffer = [UInt8](count: numberOfMegaBytes * mb, repeatedValue: 0)
   buffer += newBuffer
}


问:
javascript sound bar go up
I found this pen on Codepen. I want to use it however the bar goes down instead of upward how can I make it go upward?

var elem = $('div');
var count = elem.length;

var loop = function() {

  setTimeout(function() {
    elem.each(function() {
      var $this = $(this);
      var height = (Math.random() * 20) + 1;
      $this.css({
        'background': 'rgba(255, 255, 255,1)',
        'top': height,
        'height': height
      });
    });
    loop();
  }, 320);

}

loop();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  width: 100%;
  display: inline-block;
  margin: auto;
  background: #222;
}

div {
  background: #fff;
  float: left;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  vertical-align: middle;
  height: 1px;
  transition: all linear 250ms;
  width: 2px;
  margin-left: 1px;
}</code>```

```

答:
var elem = $('.sound-bars div');
var count = elem.length;

var loop = function(){

  setTimeout(function(){
    elem.each(function(){
      var $this = $(this);
      var height = (Math.random() * 20) + 1;
      $this.css({
        'height': height
      });
    });
    loop();
  }, 320);

}

loop();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sound-bars {
  width: 100%;
  display: flex;
  background: #222;
  position: absolute;
  bottom: 0;
  align-items: baseline;
}
.container {
  height: 80px;
  position: relative
}
.sound-bars div {
 background: #fff;
  height: 1px;
  transition: all linear 250ms;
  width: 2px;
  margin-left:1px;
}</code>```

```

Title: javascript sound bar go up

Body:
I found this pen on Codepen. I want to use it however the bar goes down instead of upward how can I make it go upward?

var elem = $('div');
var count = elem.length;

var loop = function() {

  setTimeout(function() {
    elem.each(function() {
      var $this = $(this);
      var height = (Math.random() * 20) + 1;
      $this.css({
        'background': 'rgba(255, 255, 255,1)',
        'top': height,
        'height': height
      });
    });
    loop();
  }, 320);

}

loop();

section {
  width: 100%;
  display: inline-block;
  margin: auto;
  background: #222;
}

div {
  background: #fff;
  float: left;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  vertical-align: middle;
  height: 1px;
  transition: all linear 250ms;
  width: 2px;
  margin-left: 1px;
}

Body:
var elem = $('.sound-bars div');
var count = elem.length;

var loop = function(){

  setTimeout(function(){
    elem.each(function(){
      var $this = $(this);
      var height = (Math.random() * 20) + 1;
      $this.css({
        'height': height
      });
    });
    loop();
  }, 320);

}

loop();

.sound-bars {
  width: 100%;
  display: flex;
  background: #222;
  position: absolute;
  bottom: 0;
  align-items: baseline;
}
.container {
  height: 80px;
  position: relative
}
.sound-bars div {
 background: #fff;
  height: 1px;
  transition: all linear 250ms;
  width: 2px;
  margin-left:1px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="sound-bars">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>