Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
29,677,339 | I'm getting an `InvalidStateError` at the blob creation line on IE 11. Needless to say, it works in Chrome and Firefox.
I can see that the binary data is my client side. Are there any alternatives to download this as a file?
```
var request = new ActiveXObject("MicrosoftXMLHTTP");
request.open("post", strURL, true);
request.setRequestHeader("Content-type", "text/html");
addSecureTokenHeader(request);
request.responseType = 'blob';
request.onload = function(event) {
if (request.status == 200) {
var blob = new Blob([request.response], { type: 'application/pdf' });
var url = URL.createObjectURL(blob);
var link = document.querySelector('#sim');
link.setAttribute('href', url);
var filename = request.getResponseHeader('Content-Disposition');
$('#sim').attr("download", filename);
$(link).trigger('click');
fireEvent(link, 'click');
} else {
// handle error
}
}
``` | 2015/04/16 | [
"https://Stackoverflow.com/questions/29677339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709463/"
] | After instantiating an `XmlHttpRequest` with `xhr.responseType = "blob"`
I was getting an `InvalidStateError`.
However, moving `xhr.responseType = "blob"` to `onloadstart` solved it for me! :)
```
xhr.onloadstart = function(ev) {
xhr.responseType = "blob";
}
``` | Spent some time on this and actually found out adding `new Uint8Array` works:
```js
var blob = new Blob([new Uint8Array(request.response)], {type: 'application/pdf'});
``` |
29,677,339 | I'm getting an `InvalidStateError` at the blob creation line on IE 11. Needless to say, it works in Chrome and Firefox.
I can see that the binary data is my client side. Are there any alternatives to download this as a file?
```
var request = new ActiveXObject("MicrosoftXMLHTTP");
request.open("post", strURL, true);
request.setRequestHeader("Content-type", "text/html");
addSecureTokenHeader(request);
request.responseType = 'blob';
request.onload = function(event) {
if (request.status == 200) {
var blob = new Blob([request.response], { type: 'application/pdf' });
var url = URL.createObjectURL(blob);
var link = document.querySelector('#sim');
link.setAttribute('href', url);
var filename = request.getResponseHeader('Content-Disposition');
$('#sim').attr("download", filename);
$(link).trigger('click');
fireEvent(link, 'click');
} else {
// handle error
}
}
``` | 2015/04/16 | [
"https://Stackoverflow.com/questions/29677339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709463/"
] | Spent some time on this and actually found out adding `new Uint8Array` works:
```js
var blob = new Blob([new Uint8Array(request.response)], {type: 'application/pdf'});
``` | After much searching this worked for me on IE, Edge and Chrome
```
var xhr = new XMLHttpRequest();
xhr.onloadstart = function (ev) {
xhr.responseType = "blob";
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (!window.navigator.msSaveOrOpenBlob) {
var url = (window.URL || window.webkitURL).createObjectURL(xhr.response);
var aLink = document.createElement("a");
document.body.appendChild(aLink);
aLink.href = url;
aLink.download = filename;
aLink.click();
} else {
var fileData = [xhr.response];
blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, filename);
}
}
};
``` |
29,677,339 | I'm getting an `InvalidStateError` at the blob creation line on IE 11. Needless to say, it works in Chrome and Firefox.
I can see that the binary data is my client side. Are there any alternatives to download this as a file?
```
var request = new ActiveXObject("MicrosoftXMLHTTP");
request.open("post", strURL, true);
request.setRequestHeader("Content-type", "text/html");
addSecureTokenHeader(request);
request.responseType = 'blob';
request.onload = function(event) {
if (request.status == 200) {
var blob = new Blob([request.response], { type: 'application/pdf' });
var url = URL.createObjectURL(blob);
var link = document.querySelector('#sim');
link.setAttribute('href', url);
var filename = request.getResponseHeader('Content-Disposition');
$('#sim').attr("download", filename);
$(link).trigger('click');
fireEvent(link, 'click');
} else {
// handle error
}
}
``` | 2015/04/16 | [
"https://Stackoverflow.com/questions/29677339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709463/"
] | After instantiating an `XmlHttpRequest` with `xhr.responseType = "blob"`
I was getting an `InvalidStateError`.
However, moving `xhr.responseType = "blob"` to `onloadstart` solved it for me! :)
```
xhr.onloadstart = function(ev) {
xhr.responseType = "blob";
}
``` | After much searching this worked for me on IE, Edge and Chrome
```
var xhr = new XMLHttpRequest();
xhr.onloadstart = function (ev) {
xhr.responseType = "blob";
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (!window.navigator.msSaveOrOpenBlob) {
var url = (window.URL || window.webkitURL).createObjectURL(xhr.response);
var aLink = document.createElement("a");
document.body.appendChild(aLink);
aLink.href = url;
aLink.download = filename;
aLink.click();
} else {
var fileData = [xhr.response];
blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, filename);
}
}
};
``` |
63,748,751 | I am trying to retrieve the user's IP address and assign it to a variable:
```
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") ||
Request.ServerVariables("REMOTE_ADDR") ||
Request.ServerVariables("HTTP_HOST");
Response.Write(Request.ServerVariables("HTTP_HOST") + "<br />\n\n"); // produces "localhost"
Response.Write(Request.ServerVariables("REMOTE_ADDR") + "<br />\n\n"); // produces "::1"
Response.Write(Request.ServerVariables("HTTP_X_FORWARDED_FOR") + "<br />\n\n"); // produces "undefined"
Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n"); // produces "ipAddress = object undefined"
```
I am using JScript for Classic ASP. I am unsure as to what to do at this point. Can anyone help?
Thanks | 2020/09/04 | [
"https://Stackoverflow.com/questions/63748751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544358/"
] | Things work in ASP with JScript a little bit different than ASP with VBScript.
Since everything is an object in JavaScript, with `var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")` you get an object reference instead of a string value because like most of other `Request` collections, the `ServerVariables` is a collection of `IStringList` objects
So, to make that short-circuit evaluation work as you expect, you need to play with the values, not the object references.
You can use the `Item` method that returns the string value of `IStringList` object if there's a value (the key exists), otherwise it returns an `Empty` value that evaluated as `undefined` in JScript.
```js
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR").Item ||
Request.ServerVariables("REMOTE_ADDR").Item ||
Request.ServerVariables("HTTP_HOST").Item;
``` | I solved the problem with obtaining the IP address, and the truthyness/falsyness of JScript is a complete and utter nightmare.
```
if (!String.prototype.isNullOrEmpty) {
String.isNullOrEmpty = function(value) {
return (typeof value === 'undefined' || value == null || value.length == undefined || value.length == 0);
};
}
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") ||
Request.ServerVariables("REMOTE_ADDR") ||
Request.ServerVariables("HTTP_HOST");
function getIPAddress() {
try {
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR");
}
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("REMOTE_ADDR");
}
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("HTTP_HOST");
}
} catch (e) {
Response.Write("From getIPAddress(): " + e.message);
hasErrors = true;
} finally {
return ipAddress;
}
}
ipAddress = getIPAddress();
Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n"); // produces "object localhost"
``` |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | ```
Employee _emp1 = new Employee();
```
Everytime you have `new Employee()` you have new memory allocated in heap and stack.
means \_emp1 is value in memory pointing to heap say 1212.
Now you have second statement
```
Employee _emp2 = new Employee();
```
So again new value \_emp2 say 1414 in heap.
That's why \_emp1.Equals(\_emp2) returns false here.
when you say
```
_emp1 = _emp2
```
You are assigning the same values in both. | `Employee`, does not implement it's own `.Equals()` method, then it is using `Object.Equals()`, which is only comparing the references. In case 1, your two references are made equal when assigning.
If you want to compare the `Employee` objects by their internal properties, you should implement your own `.Equals()` method that returns true if all those properties values match, and false otherwise. |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | ```
Employee _emp1 = new Employee();
```
Everytime you have `new Employee()` you have new memory allocated in heap and stack.
means \_emp1 is value in memory pointing to heap say 1212.
Now you have second statement
```
Employee _emp2 = new Employee();
```
So again new value \_emp2 say 1414 in heap.
That's why \_emp1.Equals(\_emp2) returns false here.
when you say
```
_emp1 = _emp2
```
You are assigning the same values in both. | There is no way of equating the two seperate instances of employee, you need a way of equating whether they are equal because they are seperate instances. In case one, the instances are the same and `_emp2` is `_emp1` You can do this by implementing the `IEquatable<T>` interface.
```
public class Employee : IEquatable<Employee>
{
public int Id { get; set; }
public bool Equals(Employee other)
{
return other.Id == Id;
}
}
```
You can then do this
```
Employee e = new Employee() { Id = 1 };
Employee e2 = new Employee() { Id = 1 };
//Returns true
bool b = e.Equals(e2);
``` |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | Simply speaking, the default comparator compares object instances.
* In your first example, both `_emp1` and `_emp2` are pointing to the same instance of `Employee` and therefore `Equals` returns true.
* In your second example, you create two `Employee` objects, `_emp1` and `_emp2` being two distinctly different objects. Therefore, `Equals` returns false.
---
Note that copy constructors are *not implicitly called* for reference types. Were you to do:
```
Employee _emp1 = new Employee();
Employee _emp2 = new Employee(_emp1); //or _emp1.Clone() if that is implemented
```
then `Equals` using a the default comparator will return false since they are two unique objects.
Also note that this behavior is *not the same* for value types.
---
Furthermore, if you (as you should) override the default behavior of `Equals` and `CompareTo`, all the above becomes moot. A standard technique might be (assuming a little bit):
```
public bool Equals(object rhs)
{
var rhsEmployee = rhs as Employee;
if(rhsEmployee == null) return false;
return this.Equals(rhsEmployee);
}
public bool Equals(Employee rhs)
{
return this.EmployeeId == rhs.EmployeeId;
}
```
---
Further reading:
* [`Object.Equals`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx)
* [`Object.ReferenceEquals`](http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx)
* [Value Types and Reference Types](http://msdn.microsoft.com/en-us/library/t63sy5hs%28v=vs.80%29.aspx) | There is no way of equating the two seperate instances of employee, you need a way of equating whether they are equal because they are seperate instances. In case one, the instances are the same and `_emp2` is `_emp1` You can do this by implementing the `IEquatable<T>` interface.
```
public class Employee : IEquatable<Employee>
{
public int Id { get; set; }
public bool Equals(Employee other)
{
return other.Id == Id;
}
}
```
You can then do this
```
Employee e = new Employee() { Id = 1 };
Employee e2 = new Employee() { Id = 1 };
//Returns true
bool b = e.Equals(e2);
``` |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | "This apple belongs to Joe. This pear belongs to the same man. Is this apple's owner the same person as this pear's owner? Yes."
"This apple belongs to Susan. This pear belongs to Susan. Is this apple's owner the same person as this pear's owner? No, they just happen to both be called Susan." | You should create your own `Equals` method. By default `Equals` is called from `Object` class, which is basically check if these two references points to one object (i.e. `Object.ReferenceEqual(object, object)` is called) |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | ```
Employee _emp1 = new Employee();
```
Everytime you have `new Employee()` you have new memory allocated in heap and stack.
means \_emp1 is value in memory pointing to heap say 1212.
Now you have second statement
```
Employee _emp2 = new Employee();
```
So again new value \_emp2 say 1414 in heap.
That's why \_emp1.Equals(\_emp2) returns false here.
when you say
```
_emp1 = _emp2
```
You are assigning the same values in both. | "This apple belongs to Joe. This pear belongs to the same man. Is this apple's owner the same person as this pear's owner? Yes."
"This apple belongs to Susan. This pear belongs to Susan. Is this apple's owner the same person as this pear's owner? No, they just happen to both be called Susan." |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | "This apple belongs to Joe. This pear belongs to the same man. Is this apple's owner the same person as this pear's owner? Yes."
"This apple belongs to Susan. This pear belongs to Susan. Is this apple's owner the same person as this pear's owner? No, they just happen to both be called Susan." | There is no way of equating the two seperate instances of employee, you need a way of equating whether they are equal because they are seperate instances. In case one, the instances are the same and `_emp2` is `_emp1` You can do this by implementing the `IEquatable<T>` interface.
```
public class Employee : IEquatable<Employee>
{
public int Id { get; set; }
public bool Equals(Employee other)
{
return other.Id == Id;
}
}
```
You can then do this
```
Employee e = new Employee() { Id = 1 };
Employee e2 = new Employee() { Id = 1 };
//Returns true
bool b = e.Equals(e2);
``` |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | Simply speaking, the default comparator compares object instances.
* In your first example, both `_emp1` and `_emp2` are pointing to the same instance of `Employee` and therefore `Equals` returns true.
* In your second example, you create two `Employee` objects, `_emp1` and `_emp2` being two distinctly different objects. Therefore, `Equals` returns false.
---
Note that copy constructors are *not implicitly called* for reference types. Were you to do:
```
Employee _emp1 = new Employee();
Employee _emp2 = new Employee(_emp1); //or _emp1.Clone() if that is implemented
```
then `Equals` using a the default comparator will return false since they are two unique objects.
Also note that this behavior is *not the same* for value types.
---
Furthermore, if you (as you should) override the default behavior of `Equals` and `CompareTo`, all the above becomes moot. A standard technique might be (assuming a little bit):
```
public bool Equals(object rhs)
{
var rhsEmployee = rhs as Employee;
if(rhsEmployee == null) return false;
return this.Equals(rhsEmployee);
}
public bool Equals(Employee rhs)
{
return this.EmployeeId == rhs.EmployeeId;
}
```
---
Further reading:
* [`Object.Equals`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx)
* [`Object.ReferenceEquals`](http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx)
* [Value Types and Reference Types](http://msdn.microsoft.com/en-us/library/t63sy5hs%28v=vs.80%29.aspx) | `Employee`, does not implement it's own `.Equals()` method, then it is using `Object.Equals()`, which is only comparing the references. In case 1, your two references are made equal when assigning.
If you want to compare the `Employee` objects by their internal properties, you should implement your own `.Equals()` method that returns true if all those properties values match, and false otherwise. |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | "This apple belongs to Joe. This pear belongs to the same man. Is this apple's owner the same person as this pear's owner? Yes."
"This apple belongs to Susan. This pear belongs to Susan. Is this apple's owner the same person as this pear's owner? No, they just happen to both be called Susan." | When you write `Employee _emp1` you are allocating the memory which is needed to store a pointer to another piece of memory that will contain an instance of Employee.
`new Employee();` allocates a new piece of memory filling it with an instance of Employee and return you the address of this memory (the pointer). Something like, let's say, 1234567. So after Executing `Employee _emp1 = new Employee();`, you have `_emp1` equal to 1234567, and the memory pointed by 1234567 containing your Employee.
Then you execute `Employee _emp2 = _emp1;`, and the result is having another piece of memory able to contain an address to a piece of memory containing an instance of Employee (`_emp2`) which is equal to 1234567, too. This meand that when you execute `_emp1.Equals(_emp2)` the result is true, since both of your vars point to the same piece of memory.
In the second case, another instance of Employee is created and put in a different piece of memory (e.g. something like 7654321) and this address is assigned to `_emp2` that hence is different from `_emp1`. |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | ```
Employee _emp1 = new Employee();
```
Everytime you have `new Employee()` you have new memory allocated in heap and stack.
means \_emp1 is value in memory pointing to heap say 1212.
Now you have second statement
```
Employee _emp2 = new Employee();
```
So again new value \_emp2 say 1414 in heap.
That's why \_emp1.Equals(\_emp2) returns false here.
when you say
```
_emp1 = _emp2
```
You are assigning the same values in both. | When you write `Employee _emp1` you are allocating the memory which is needed to store a pointer to another piece of memory that will contain an instance of Employee.
`new Employee();` allocates a new piece of memory filling it with an instance of Employee and return you the address of this memory (the pointer). Something like, let's say, 1234567. So after Executing `Employee _emp1 = new Employee();`, you have `_emp1` equal to 1234567, and the memory pointed by 1234567 containing your Employee.
Then you execute `Employee _emp2 = _emp1;`, and the result is having another piece of memory able to contain an address to a piece of memory containing an instance of Employee (`_emp2`) which is equal to 1234567, too. This meand that when you execute `_emp1.Equals(_emp2)` the result is true, since both of your vars point to the same piece of memory.
In the second case, another instance of Employee is created and put in a different piece of memory (e.g. something like 7654321) and this address is assigned to `_emp2` that hence is different from `_emp1`. |
14,519,295 | I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
```
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]
```
When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints? | 2013/01/25 | [
"https://Stackoverflow.com/questions/14519295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253944/"
] | Simply speaking, the default comparator compares object instances.
* In your first example, both `_emp1` and `_emp2` are pointing to the same instance of `Employee` and therefore `Equals` returns true.
* In your second example, you create two `Employee` objects, `_emp1` and `_emp2` being two distinctly different objects. Therefore, `Equals` returns false.
---
Note that copy constructors are *not implicitly called* for reference types. Were you to do:
```
Employee _emp1 = new Employee();
Employee _emp2 = new Employee(_emp1); //or _emp1.Clone() if that is implemented
```
then `Equals` using a the default comparator will return false since they are two unique objects.
Also note that this behavior is *not the same* for value types.
---
Furthermore, if you (as you should) override the default behavior of `Equals` and `CompareTo`, all the above becomes moot. A standard technique might be (assuming a little bit):
```
public bool Equals(object rhs)
{
var rhsEmployee = rhs as Employee;
if(rhsEmployee == null) return false;
return this.Equals(rhsEmployee);
}
public bool Equals(Employee rhs)
{
return this.EmployeeId == rhs.EmployeeId;
}
```
---
Further reading:
* [`Object.Equals`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx)
* [`Object.ReferenceEquals`](http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx)
* [Value Types and Reference Types](http://msdn.microsoft.com/en-us/library/t63sy5hs%28v=vs.80%29.aspx) | You should create your own `Equals` method. By default `Equals` is called from `Object` class, which is basically check if these two references points to one object (i.e. `Object.ReferenceEqual(object, object)` is called) |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | There are logical temporary "inserted" and "deleted" table which you can access.
if there are some rows in both tables that means its updated.
You can get the new values by selecting querying "inserted" table.
```
Select * from inserted
```
and you can get the old values which are being updated by querying the "deleted" table.
```
Select * from deleted
``` | As devio has stated, if you are doing different things for an INSERT and a DELETE, you could use two triggers. Just specify FOR INSERT or FOR DELETE after the CREATE TRIGGER line.
If you want to use one trigger, then, as Ismail hinted at, you could inspect the values of the temporary "inserted" and "deleted" tables that are given to you inside a trigger.
If the "deleted" table is empty then this trigger was fired by an INSERT statement;
If "deleted" is not empty and the "inserted" table is empty, then the trigger was fired by a DELETE statement.
If neither are empty, then an UPDATE statement will have been used. |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | There are logical temporary "inserted" and "deleted" table which you can access.
if there are some rows in both tables that means its updated.
You can get the new values by selecting querying "inserted" table.
```
Select * from inserted
```
and you can get the old values which are being updated by querying the "deleted" table.
```
Select * from deleted
``` | You can use the AFTER keyword to designate separate triggers for each event if that suits you better.
Eg:-
```
CREATE TRIGGER FooIns ON TableBar
AFTER INSERT
CREATE TRIGGER FooUpd ON TableBar
AFTER UPDATE
``` |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | There are logical temporary "inserted" and "deleted" table which you can access.
if there are some rows in both tables that means its updated.
You can get the new values by selecting querying "inserted" table.
```
Select * from inserted
```
and you can get the old values which are being updated by querying the "deleted" table.
```
Select * from deleted
``` | Just use separate triggers!! It has been mentioned that Triggers are evil, but they become more evil if you start to include convoluted code to try and determine the action (Insert/Update/Delete) If anyone works on your triggers in the future, they'll only question WTF was he thinking creating unnecessary complexity!
Also it's worth remembering that updates can effect multiple rows so when the trigger is fired the 'deleted' & 'inserted' tables can have many rows! |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | If you need to implement "different behavior", then what is the point of trying to write only 1 trigger, instead of one trigger per operation? | You can use the AFTER keyword to designate separate triggers for each event if that suits you better.
Eg:-
```
CREATE TRIGGER FooIns ON TableBar
AFTER INSERT
CREATE TRIGGER FooUpd ON TableBar
AFTER UPDATE
``` |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | You can use the AFTER keyword to designate separate triggers for each event if that suits you better.
Eg:-
```
CREATE TRIGGER FooIns ON TableBar
AFTER INSERT
CREATE TRIGGER FooUpd ON TableBar
AFTER UPDATE
``` | Just use separate triggers!! It has been mentioned that Triggers are evil, but they become more evil if you start to include convoluted code to try and determine the action (Insert/Update/Delete) If anyone works on your triggers in the future, they'll only question WTF was he thinking creating unnecessary complexity!
Also it's worth remembering that updates can effect multiple rows so when the trigger is fired the 'deleted' & 'inserted' tables can have many rows! |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | There are datasets called INSERTED and DELETED. Depending on the action that invoked the trigger, there's data in these datasets. For updates, IIRC, the original data is in DELETED, the new data is in INSERTED.
See [here](http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx). | You can use the AFTER keyword to designate separate triggers for each event if that suits you better.
Eg:-
```
CREATE TRIGGER FooIns ON TableBar
AFTER INSERT
CREATE TRIGGER FooUpd ON TableBar
AFTER UPDATE
``` |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | You can use the AFTER keyword to designate separate triggers for each event if that suits you better.
Eg:-
```
CREATE TRIGGER FooIns ON TableBar
AFTER INSERT
CREATE TRIGGER FooUpd ON TableBar
AFTER UPDATE
``` | As devio has stated, if you are doing different things for an INSERT and a DELETE, you could use two triggers. Just specify FOR INSERT or FOR DELETE after the CREATE TRIGGER line.
If you want to use one trigger, then, as Ismail hinted at, you could inspect the values of the temporary "inserted" and "deleted" tables that are given to you inside a trigger.
If the "deleted" table is empty then this trigger was fired by an INSERT statement;
If "deleted" is not empty and the "inserted" table is empty, then the trigger was fired by a DELETE statement.
If neither are empty, then an UPDATE statement will have been used. |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | If you need to implement "different behavior", then what is the point of trying to write only 1 trigger, instead of one trigger per operation? | As devio has stated, if you are doing different things for an INSERT and a DELETE, you could use two triggers. Just specify FOR INSERT or FOR DELETE after the CREATE TRIGGER line.
If you want to use one trigger, then, as Ismail hinted at, you could inspect the values of the temporary "inserted" and "deleted" tables that are given to you inside a trigger.
If the "deleted" table is empty then this trigger was fired by an INSERT statement;
If "deleted" is not empty and the "inserted" table is empty, then the trigger was fired by a DELETE statement.
If neither are empty, then an UPDATE statement will have been used. |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | There are datasets called INSERTED and DELETED. Depending on the action that invoked the trigger, there's data in these datasets. For updates, IIRC, the original data is in DELETED, the new data is in INSERTED.
See [here](http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx). | As devio has stated, if you are doing different things for an INSERT and a DELETE, you could use two triggers. Just specify FOR INSERT or FOR DELETE after the CREATE TRIGGER line.
If you want to use one trigger, then, as Ismail hinted at, you could inspect the values of the temporary "inserted" and "deleted" tables that are given to you inside a trigger.
If the "deleted" table is empty then this trigger was fired by an INSERT statement;
If "deleted" is not empty and the "inserted" table is empty, then the trigger was fired by a DELETE statement.
If neither are empty, then an UPDATE statement will have been used. |
1,687,368 | I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them.
Thanks in advance,
Paulo | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157693/"
] | There are datasets called INSERTED and DELETED. Depending on the action that invoked the trigger, there's data in these datasets. For updates, IIRC, the original data is in DELETED, the new data is in INSERTED.
See [here](http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx). | Just use separate triggers!! It has been mentioned that Triggers are evil, but they become more evil if you start to include convoluted code to try and determine the action (Insert/Update/Delete) If anyone works on your triggers in the future, they'll only question WTF was he thinking creating unnecessary complexity!
Also it's worth remembering that updates can effect multiple rows so when the trigger is fired the 'deleted' & 'inserted' tables can have many rows! |
1,612,438 | im trying to create a semi-transparent form which is displayed in a panel. i can display the form in the panel but the opacity property wont work and the form is non-transparent.
```
private void button1_Click(object sender, EventArgs e)
{
Form fr = new Form();
fr.FormBorderStyle = FormBorderStyle.None;
fr.BackColor = Color.Black;
fr.TopLevel = false;
fr.Opacity = 0.5;
this.panel1.Controls.Add(fr);
fr.Show();
}
```
any ideas how i can handle that?
Thanks for your answeres! | 2009/10/23 | [
"https://Stackoverflow.com/questions/1612438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195201/"
] | Winforms only supports partial transparency for top-level forms. If you want to create an application with partially-transparent UI elements, you either need to use WPF, or handle all the drawing yourself. Sorry to be the bearer of bad news. | Your form is added as a child control of panel1 which is child of the main form which is of default Opacity = 1.
To see Opacity at work, try this:
```
private void button1_Click(object sender, EventArgs e)
{
Form fr = new Form();
fr.FormBorderStyle = FormBorderStyle.None;
fr.BackColor = Color.Blue;
fr.TopLevel = false;
//fr.Opacity = 0.5;
this.Opacity = 0.5; // add this
this.panel1.Controls.Add(fr);
fr.Show();
}
```
I guess you want the panel to look semi-transparent, you have to use another method and work with the form itself. |
61,002,320 | I looked online and every method for extracting numbers from strings uses the
`[int(word) for word in a_string.split() if word.isdigit()]` method,
however when I run the code below, it does not extract the number `45`
```
test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])
```
This is what python prints
```
ON45
[]
```
The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]` | 2020/04/02 | [
"https://Stackoverflow.com/questions/61002320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] | [`str.split`](https://docs.python.org/3.8/library/stdtypes.html#str.split) with no arguments splits a string on whitespace, which your string has none of. Thus you end up with `i` in your list comprehension being `ON45` which does not pass `isdigit()`; hence your output list is empty. One way of achieving what you want is:
```
int(''.join(i for i in test if i.isdigit()))
```
Output:
```
45
```
You can put that in a list if desired by simply enclosing the `int` in `[]` i.e.
```
[int(''.join(i for i in test if i.isdigit()))]
``` | You can iterate through the characters in each string from the list resulting from the split, filter out the non-digit characters, and then join the rest back into a string:
```
test = "ON45"
print([int(''.join(i for i in s if i.isdigit())) for s in test.split()])
```
This outputs:
```
[45]
``` |
61,002,320 | I looked online and every method for extracting numbers from strings uses the
`[int(word) for word in a_string.split() if word.isdigit()]` method,
however when I run the code below, it does not extract the number `45`
```
test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])
```
This is what python prints
```
ON45
[]
```
The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]` | 2020/04/02 | [
"https://Stackoverflow.com/questions/61002320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] | [`str.split`](https://docs.python.org/3.8/library/stdtypes.html#str.split) with no arguments splits a string on whitespace, which your string has none of. Thus you end up with `i` in your list comprehension being `ON45` which does not pass `isdigit()`; hence your output list is empty. One way of achieving what you want is:
```
int(''.join(i for i in test if i.isdigit()))
```
Output:
```
45
```
You can put that in a list if desired by simply enclosing the `int` in `[]` i.e.
```
[int(''.join(i for i in test if i.isdigit()))]
``` | Yes, because `string.split()` splits on space, which you don't have in the original string. With the string `"ON 24"` it'd work just fine. |
61,002,320 | I looked online and every method for extracting numbers from strings uses the
`[int(word) for word in a_string.split() if word.isdigit()]` method,
however when I run the code below, it does not extract the number `45`
```
test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])
```
This is what python prints
```
ON45
[]
```
The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]` | 2020/04/02 | [
"https://Stackoverflow.com/questions/61002320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] | Following works:
```
import re
test = "ON45"
print(test)
print(str(list(map(int, re.findall(r'\d+', test)))))
``` | You can iterate through the characters in each string from the list resulting from the split, filter out the non-digit characters, and then join the rest back into a string:
```
test = "ON45"
print([int(''.join(i for i in s if i.isdigit())) for s in test.split()])
```
This outputs:
```
[45]
``` |
61,002,320 | I looked online and every method for extracting numbers from strings uses the
`[int(word) for word in a_string.split() if word.isdigit()]` method,
however when I run the code below, it does not extract the number `45`
```
test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])
```
This is what python prints
```
ON45
[]
```
The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]` | 2020/04/02 | [
"https://Stackoverflow.com/questions/61002320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] | If you want to get the individual digits
```
print([int(i) for i in test if i.isdigit()])
```
output
`[4, 5`]
If you want to get concatenated numbers
```
import re
print(re.findall(r'[0-9]+', test))
```
output
`['45']`
hope it helps | You can iterate through the characters in each string from the list resulting from the split, filter out the non-digit characters, and then join the rest back into a string:
```
test = "ON45"
print([int(''.join(i for i in s if i.isdigit())) for s in test.split()])
```
This outputs:
```
[45]
``` |
61,002,320 | I looked online and every method for extracting numbers from strings uses the
`[int(word) for word in a_string.split() if word.isdigit()]` method,
however when I run the code below, it does not extract the number `45`
```
test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])
```
This is what python prints
```
ON45
[]
```
The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]` | 2020/04/02 | [
"https://Stackoverflow.com/questions/61002320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] | Following works:
```
import re
test = "ON45"
print(test)
print(str(list(map(int, re.findall(r'\d+', test)))))
``` | Yes, because `string.split()` splits on space, which you don't have in the original string. With the string `"ON 24"` it'd work just fine. |
61,002,320 | I looked online and every method for extracting numbers from strings uses the
`[int(word) for word in a_string.split() if word.isdigit()]` method,
however when I run the code below, it does not extract the number `45`
```
test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])
```
This is what python prints
```
ON45
[]
```
The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]` | 2020/04/02 | [
"https://Stackoverflow.com/questions/61002320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056201/"
] | If you want to get the individual digits
```
print([int(i) for i in test if i.isdigit()])
```
output
`[4, 5`]
If you want to get concatenated numbers
```
import re
print(re.findall(r'[0-9]+', test))
```
output
`['45']`
hope it helps | Yes, because `string.split()` splits on space, which you don't have in the original string. With the string `"ON 24"` it'd work just fine. |
2,244,272 | How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does? | 2010/02/11 | [
"https://Stackoverflow.com/questions/2244272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123927/"
] | What I'm doing right now is:
```
public static final HashMap<String, String> acceptTypes = new HashMap<String, String>(){{
put("html", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
put("img", "image/png,image/*;q=0.8,*/*;q=0.5");
put("script", "*/*");
put("style", "text/css,*/*;q=0.1");
}};
protected void downloadCssAndImages(HtmlPage page) {
String xPathExpression = "//*[name() = 'img' or name() = 'link' and @type = 'text/css']";
List<?> resultList = page.getByXPath(xPathExpression);
Iterator<?> i = resultList.iterator();
while (i.hasNext()) {
try {
HtmlElement el = (HtmlElement) i.next();
String path = el.getAttribute("src").equals("")?el.getAttribute("href"):el.getAttribute("src");
if (path == null || path.equals("")) continue;
URL url = page.getFullyQualifiedUrl(path);
WebRequestSettings wrs = new WebRequestSettings(url);
wrs.setAdditionalHeader("Referer", page.getWebResponse().getRequestSettings().getUrl().toString());
client.addRequestHeader("Accept", acceptTypes.get(el.getTagName().toLowerCase()));
client.getPage(wrs);
} catch (Exception e) {}
}
client.removeRequestHeader("Accept");
}
``` | HtmlUnit does not download CSS or images. They are useless to a headless browser...
Last I heard of it is here, but the ticket is marked private: <http://osdir.com/ml/java.htmlunit.devel/2007-01/msg00021.html> |
2,244,272 | How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does? | 2010/02/11 | [
"https://Stackoverflow.com/questions/2244272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123927/"
] | source : [How to get base64 encoded contents for an ImageReader?](https://stackoverflow.com/questions/3068543)
```
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
ImageReader imageReader = img.getImageReader();
BufferedImage bufferedImage = imageReader.read(0);
String formatName = imageReader.getFormatName();
ByteArrayOutputStream byteaOutput = new ByteArrayOutputStream();
Base64OutputStream base64Output = new base64OutputStream(byteaOutput);
ImageIO.write(bufferedImage, formatName, base64output);
String base64 = new String(byteaOutput.toByteArray());
``` | HtmlUnit does not download CSS or images. They are useless to a headless browser...
Last I heard of it is here, but the ticket is marked private: <http://osdir.com/ml/java.htmlunit.devel/2007-01/msg00021.html> |
2,244,272 | How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does? | 2010/02/11 | [
"https://Stackoverflow.com/questions/2244272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123927/"
] | Here's what I came up with:
```
public InputStream httpGetLowLevel(URL url) throws IOException
{
WebRequest wrq=new WebRequest(url);
ProxyConfig config =webClient.getProxyConfig();
//set request webproxy
wrq.setProxyHost(config.getProxyHost());
wrq.setProxyPort(config.getProxyPort());
wrq.setCredentials(webClient.getCredentialsProvider().getCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort())));
for(Cookie c:webClient.getCookieManager().getCookies(url)){
wrq.setAdditionalHeader("Cookie", c.toString());
}
WebResponse wr= webClient.getWebConnection().getResponse(wrq);
return wr.getContentAsStream();
}
```
My tests show, that it does support proxys and that it not only carries cookies from WebClient, but also if server sends new cookies during the response, the WebClient will eat those cookies | HtmlUnit does not download CSS or images. They are useless to a headless browser...
Last I heard of it is here, but the ticket is marked private: <http://osdir.com/ml/java.htmlunit.devel/2007-01/msg00021.html> |
2,244,272 | How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does? | 2010/02/11 | [
"https://Stackoverflow.com/questions/2244272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123927/"
] | What I'm doing right now is:
```
public static final HashMap<String, String> acceptTypes = new HashMap<String, String>(){{
put("html", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
put("img", "image/png,image/*;q=0.8,*/*;q=0.5");
put("script", "*/*");
put("style", "text/css,*/*;q=0.1");
}};
protected void downloadCssAndImages(HtmlPage page) {
String xPathExpression = "//*[name() = 'img' or name() = 'link' and @type = 'text/css']";
List<?> resultList = page.getByXPath(xPathExpression);
Iterator<?> i = resultList.iterator();
while (i.hasNext()) {
try {
HtmlElement el = (HtmlElement) i.next();
String path = el.getAttribute("src").equals("")?el.getAttribute("href"):el.getAttribute("src");
if (path == null || path.equals("")) continue;
URL url = page.getFullyQualifiedUrl(path);
WebRequestSettings wrs = new WebRequestSettings(url);
wrs.setAdditionalHeader("Referer", page.getWebResponse().getRequestSettings().getUrl().toString());
client.addRequestHeader("Accept", acceptTypes.get(el.getTagName().toLowerCase()));
client.getPage(wrs);
} catch (Exception e) {}
}
client.removeRequestHeader("Accept");
}
``` | source : [How to get base64 encoded contents for an ImageReader?](https://stackoverflow.com/questions/3068543)
```
HtmlImage img = (HtmlImage) p.getByXPath("//img").get(3);
ImageReader imageReader = img.getImageReader();
BufferedImage bufferedImage = imageReader.read(0);
String formatName = imageReader.getFormatName();
ByteArrayOutputStream byteaOutput = new ByteArrayOutputStream();
Base64OutputStream base64Output = new base64OutputStream(byteaOutput);
ImageIO.write(bufferedImage, formatName, base64output);
String base64 = new String(byteaOutput.toByteArray());
``` |
2,244,272 | How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does? | 2010/02/11 | [
"https://Stackoverflow.com/questions/2244272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123927/"
] | What I'm doing right now is:
```
public static final HashMap<String, String> acceptTypes = new HashMap<String, String>(){{
put("html", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
put("img", "image/png,image/*;q=0.8,*/*;q=0.5");
put("script", "*/*");
put("style", "text/css,*/*;q=0.1");
}};
protected void downloadCssAndImages(HtmlPage page) {
String xPathExpression = "//*[name() = 'img' or name() = 'link' and @type = 'text/css']";
List<?> resultList = page.getByXPath(xPathExpression);
Iterator<?> i = resultList.iterator();
while (i.hasNext()) {
try {
HtmlElement el = (HtmlElement) i.next();
String path = el.getAttribute("src").equals("")?el.getAttribute("href"):el.getAttribute("src");
if (path == null || path.equals("")) continue;
URL url = page.getFullyQualifiedUrl(path);
WebRequestSettings wrs = new WebRequestSettings(url);
wrs.setAdditionalHeader("Referer", page.getWebResponse().getRequestSettings().getUrl().toString());
client.addRequestHeader("Accept", acceptTypes.get(el.getTagName().toLowerCase()));
client.getPage(wrs);
} catch (Exception e) {}
}
client.removeRequestHeader("Accept");
}
``` | Here's what I came up with:
```
public InputStream httpGetLowLevel(URL url) throws IOException
{
WebRequest wrq=new WebRequest(url);
ProxyConfig config =webClient.getProxyConfig();
//set request webproxy
wrq.setProxyHost(config.getProxyHost());
wrq.setProxyPort(config.getProxyPort());
wrq.setCredentials(webClient.getCredentialsProvider().getCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort())));
for(Cookie c:webClient.getCookieManager().getCookies(url)){
wrq.setAdditionalHeader("Cookie", c.toString());
}
WebResponse wr= webClient.getWebConnection().getResponse(wrq);
return wr.getContentAsStream();
}
```
My tests show, that it does support proxys and that it not only carries cookies from WebClient, but also if server sends new cookies during the response, the WebClient will eat those cookies |
55,070,711 | I'm using MSYS2 but without pip (SSL error), and when I try to run
```
python vin.py
```
It throws me this error:
```
Traceback (most recent call last):
File "vin.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
```
What can I do? Thanks in advance | 2019/03/08 | [
"https://Stackoverflow.com/questions/55070711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10811266/"
] | I think it is because you installed the `requests` module for Python 3 while you are running Python 2.
To specifically install the package for Python 2, try entering this command:
```
pip2 install requests
```
or
```
python -m pip install requests
```
If you want to run the script with Python 3 instead, simply change `python` to `python3`, so:
```
python3 vin.py
``` | It is better to use a [`virtualenv`](https://virtualenv.pypa.io/en/latest/):
First create a virtualenv for your project and activate it:
```sh
python -m venv my_project
source my_project/bin/activate
```
Then install [`Requests`](http://docs.python-requests.org/en/master/):
```sh
pip install requests
```
To test: run python and import requests
```py
>>> import requests
``` |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | then just use:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
```
Using [.text()](http://api.jquery.com/text/) instad of [.html()](http://api.jquery.com/html/) and eventname will contain the text without html ;)
because if you remove the span, then you are removing the tag and its content (the text that you want) | Try using [text()](http://api.jquery.com/text/) instead of `html()`:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( $.trim(eventname ));
```
**[Working Demo](http://jsfiddle.net/X8nU2/)** |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | If the desired output is `Arrangementname` then the problem is the first line, which should be:
```
var eventname = $('#contentArea h1');
```
...because that makes `eventname` a jQuery object, on which you can use `.find()` to get the span and remove it with your existing second line. Though that actually removes the span element from the page completely, so you might want to do this:
```
var eventname = $('#contentArea h1').clone();
```
...so that you have a working copy that won't affect what is displayed on the page.
The next problem is that you have a variable called `eventnametrim` that you then refer to on the last line of your code as `$eventnametrim`. Remove the `$` from the latter so the names match.
If you're trying to get an output of `CourseArrangementname`, i.e., to ignore the `<span>` and `</span>` tags but keep the text content, you can do it like this:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
``` | Try using [text()](http://api.jquery.com/text/) instead of `html()`:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( $.trim(eventname ));
```
**[Working Demo](http://jsfiddle.net/X8nU2/)** |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | then just use:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
```
Using [.text()](http://api.jquery.com/text/) instad of [.html()](http://api.jquery.com/html/) and eventname will contain the text without html ;)
because if you remove the span, then you are removing the tag and its content (the text that you want) | try:
```
var eventname = $('#contentArea h1');
```
html is not a jQuery object, I believe, is what is going on. |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | If the desired output is `Arrangementname` then the problem is the first line, which should be:
```
var eventname = $('#contentArea h1');
```
...because that makes `eventname` a jQuery object, on which you can use `.find()` to get the span and remove it with your existing second line. Though that actually removes the span element from the page completely, so you might want to do this:
```
var eventname = $('#contentArea h1').clone();
```
...so that you have a working copy that won't affect what is displayed on the page.
The next problem is that you have a variable called `eventnametrim` that you then refer to on the last line of your code as `$eventnametrim`. Remove the `$` from the latter so the names match.
If you're trying to get an output of `CourseArrangementname`, i.e., to ignore the `<span>` and `</span>` tags but keep the text content, you can do it like this:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
``` | try:
```
var eventname = $('#contentArea h1');
```
html is not a jQuery object, I believe, is what is going on. |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | If the desired output is `Arrangementname` then the problem is the first line, which should be:
```
var eventname = $('#contentArea h1');
```
...because that makes `eventname` a jQuery object, on which you can use `.find()` to get the span and remove it with your existing second line. Though that actually removes the span element from the page completely, so you might want to do this:
```
var eventname = $('#contentArea h1').clone();
```
...so that you have a working copy that won't affect what is displayed on the page.
The next problem is that you have a variable called `eventnametrim` that you then refer to on the last line of your code as `$eventnametrim`. Remove the `$` from the latter so the names match.
If you're trying to get an output of `CourseArrangementname`, i.e., to ignore the `<span>` and `</span>` tags but keep the text content, you can do it like this:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
``` | then just use:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
```
Using [.text()](http://api.jquery.com/text/) instad of [.html()](http://api.jquery.com/html/) and eventname will contain the text without html ;)
because if you remove the span, then you are removing the tag and its content (the text that you want) |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | then just use:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
```
Using [.text()](http://api.jquery.com/text/) instad of [.html()](http://api.jquery.com/html/) and eventname will contain the text without html ;)
because if you remove the span, then you are removing the tag and its content (the text that you want) | I was getting an error in the console. Try something like this:
<http://jsfiddle.net/GmzXG/>
```
$('#contentArea h1').find("span").remove();
var eventname = $('#contentArea h1').html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventname );
``` |
18,106,312 | This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag
**I have this HTML:**
```
<div id="contentArea">
<h1><span>Course</span>Arrangementname<h1>
<input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement">
</div>
```
**jQuery**
```
var eventname = $('#contentArea h1').html();
eventname.find("span").remove();
var eventnametrim = eventname.html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventnametrim );
```
But nothing happens - the alert is also empty. My firebug tells me that
`"eventname.find is not a function"` it's jQuery 1.9.0
Can someone please telle me whats going on? | 2013/08/07 | [
"https://Stackoverflow.com/questions/18106312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680223/"
] | If the desired output is `Arrangementname` then the problem is the first line, which should be:
```
var eventname = $('#contentArea h1');
```
...because that makes `eventname` a jQuery object, on which you can use `.find()` to get the span and remove it with your existing second line. Though that actually removes the span element from the page completely, so you might want to do this:
```
var eventname = $('#contentArea h1').clone();
```
...so that you have a working copy that won't affect what is displayed on the page.
The next problem is that you have a variable called `eventnametrim` that you then refer to on the last line of your code as `$eventnametrim`. Remove the `$` from the latter so the names match.
If you're trying to get an output of `CourseArrangementname`, i.e., to ignore the `<span>` and `</span>` tags but keep the text content, you can do it like this:
```
var eventname = $('#contentArea h1').text();
$( "input[name*='Form_Arrangement']" ).val( eventname );
``` | I was getting an error in the console. Try something like this:
<http://jsfiddle.net/GmzXG/>
```
$('#contentArea h1').find("span").remove();
var eventname = $('#contentArea h1').html();
//alert(eventnametrim);
$( "input[name*='Form_Arrangement']" ).val( eventname );
``` |
30,766,016 | I have a large record import job running on our web application. The import is run by a PORO which calculates how many objects it needs to import and divides the number by an index of the current object it is presently on, leaving me with a clean way to calculate the percentage complete. After it does this calculation I am saving this percentage to the database in order to poll it and let the user know how far along this import has come.
It doesn't appear that sidekiq allows for these database writes to touch the database until the entire job is over, leaving me with this quesiton:
**Is every sidekiq job wrapped entirely in a transaction?**
*(I'm not lazy I just don't have a lot of time to go through the code and discover this myself.)* | 2015/06/10 | [
"https://Stackoverflow.com/questions/30766016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1005669/"
] | I'm not entirely sure I understand your question given that your code does work. But stylistically, for metafunctions that yield a type, that type should be named `type`. So you should have:
```
using type = decltype( test((T*)0) );
^^^^
```
Or, to avoid the zero-pointer-cast-hack:
```
using type = decltype(test(std::declval<T*>()));
```
Also, your `test` doesn't need a definition. Just the declaration. We're not actually *calling* it, just checking its return type. It doesn't have to be `constexpr` either, so this suffices:
```
template<class U>
static std::true_type test(Base<U> *);
static std::false_type test(...);
```
Once you have that, you can alias it:
```
template <typename T>
using is_Base_t = typename is_Base<T>::type;
```
And use the alias:
```
template <typename T,
typename = std::enable_if_t< is_Base_t<T>::value>>
void foo(T const&)
{
}
``` | After stumbling blindly into the answer in the comments, I found out I can just use `is_Base<T>::type::value` without any `typename` keywords. When trying to remove the `static_passoff` before, I kept putting in `typename`. I have always been mixed up with that one. Anyway, here is the final code with a few teaks from Barry's answer:
```
#include <iostream>
#include <memory>
using namespace std;
template < typename D >
class Base
{
public:
typedef D EType;
};
template<class T>
struct is_Base
{
using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
template<class U>
static constexpr std::true_type test(Base<U> *) { return std::true_type(); }
static constexpr std::false_type test(...) { return std::false_type(); }
using type = decltype(test(std::declval<T*>()));
};
template <typename T, typename = typename std::enable_if< is_Base< T >::type::value >::type >
void foo(T const&)
{
}
class Derived : public Base<Derived> {};
class NotDerived {};
int main()
{
Derived d;
//NotDerived nd;
foo(d);
//foo(nd); // <-- Should cause compile error
return 0;
}
``` |
16,572,771 | My game is turnbased, but it does have some realtime elements like chat, so it needs to be speedy. One server should ideally support a couple thousand online players.
I know Datasets tend to store large amounts of data in memory but I figured that's what I needed to avoid having to do db calls twice every milliscecond. I'm leaning away from Entity Framework because I don't seem to have as much control of whats happens under the hood, and it struck me as less efficient somehow.
Now I know neither of these (nor c# in general) are the most blazingly fast solution to ever exist in life but I do need a little convenience.
By the way I can't easily use .Net 4.0 because of some other iffy dependencies. Those could be fixed but to be honest I don't feel like investing the time in figuring it out. I rather just stick with 3.5 which my dependencies work well with. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16572771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379635/"
] | I have done a game with a database back-end.
Word to the wise: updating caches in a real-time game is difficult. Your players will be interacting all the time. You have to think about whether you want to keep all players on the same server - if so, caching is simple, but you will limit growth. If not, think how you can keep people interacting on the same server. A chat server, for example, would solve the chat issues. However if you have geography, you might want to segment by world areas, if you don't, might want to keep groups of players, or if you have different game instances, you can segment by that.
Another issue is locking - your players might access the same data that another is updating. You will almost certainly have to deal with transaction isolation levels - i. e. read uncommitted will help with locking. For this, ADO offers more control.
However EF lets you write much cleaner update code, and the performance will not be different if you are updating by ID.
You could go for a mix - read via ADO and write via EF. You could even write a transactional db context that uses ADO underneath. That way they look alike but do different things in the background.
Just my thoughts, I hope this helps you figure out your solution. | If your only problem is the chat you can choose different kind of solutions for it, using external cloud systems that provied messeging and breadcasting...
Check out this link :
<http://www.pubnub.com/solutions/how-pubnub-works>
Hoped i helped at some way |
16,572,771 | My game is turnbased, but it does have some realtime elements like chat, so it needs to be speedy. One server should ideally support a couple thousand online players.
I know Datasets tend to store large amounts of data in memory but I figured that's what I needed to avoid having to do db calls twice every milliscecond. I'm leaning away from Entity Framework because I don't seem to have as much control of whats happens under the hood, and it struck me as less efficient somehow.
Now I know neither of these (nor c# in general) are the most blazingly fast solution to ever exist in life but I do need a little convenience.
By the way I can't easily use .Net 4.0 because of some other iffy dependencies. Those could be fixed but to be honest I don't feel like investing the time in figuring it out. I rather just stick with 3.5 which my dependencies work well with. | 2013/05/15 | [
"https://Stackoverflow.com/questions/16572771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379635/"
] | I have done a game with a database back-end.
Word to the wise: updating caches in a real-time game is difficult. Your players will be interacting all the time. You have to think about whether you want to keep all players on the same server - if so, caching is simple, but you will limit growth. If not, think how you can keep people interacting on the same server. A chat server, for example, would solve the chat issues. However if you have geography, you might want to segment by world areas, if you don't, might want to keep groups of players, or if you have different game instances, you can segment by that.
Another issue is locking - your players might access the same data that another is updating. You will almost certainly have to deal with transaction isolation levels - i. e. read uncommitted will help with locking. For this, ADO offers more control.
However EF lets you write much cleaner update code, and the performance will not be different if you are updating by ID.
You could go for a mix - read via ADO and write via EF. You could even write a transactional db context that uses ADO underneath. That way they look alike but do different things in the background.
Just my thoughts, I hope this helps you figure out your solution. | It does not sound like either solution is an ideal fit for your problem. Your question is therefore like asking whether to use a wet newspaper or an umbrella to drive a nail into the wall.. regardless of the answer, you probably should do neither.
EF comes with a lot of limitations and quirks, and does have some overhead. If you really want to stick to 3.5 (poor choice in my opinion, but hey), then I wouldn't recommend it - unless you are already comfortable with it, including how to troubleshoot any performance issues.
DataSets are just an abomination. It is my professional belief that they were invented in order for Microsoft to be able to pull of their 5-minute drag-and-drop coding demos for Visual Studio, in order to convince all the VB programmers to switch to .NET. They are exceptionally slow compared to just about everything (although since .NET 2.0 performance does at least scale linearly).
I am not sure exactly what product you should be using, but I know there are in-memory relational databases that allow you to store transaction logs and the occasional snapshot, in order to facilitate rollback in case your server dies (or IIS is restarted, etc.), which gives you performance at the cost of scalability (your entire database must fit in memory).
Another option is to use a NoSQL database (such as MongoDB), which scales really well across multiple servers, and lets you bundle all related data into a single document (so you don't have all the overhead of joining tables when querying for data).
Either one of these options are going to be a much better fit than any of the two original suggestions. |
22,559,804 | So far, I've been using Git and it's tolerable for simple pushes and merges, but I just got a curve ball thrown at me. The developers of the source code I am using just released a new version release as a source tree. Several files have been changed and I am having difficulty figuring out how to incorporate the new source such that I can keep the old version of their code with my modifications as one branch, say Version 1.0, and the new version of their code with the same modifications as another branch, say Version 2.0. I'm the only one working on the project, so I don't care about rewriting the history if I have too. Ideally, I would like to be able to continue making my modifications and have them apply to both versions. | 2014/03/21 | [
"https://Stackoverflow.com/questions/22559804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148298/"
] | You can use submodule for code of library you are using , so will be able to have 2 brunches in this submodule (Version 1.0 and Version 2.0) and use master branch for your code. In such case when your changes will be done you will be able to easily provide them with both Version 1.0 and Version 2.0 just by switching branch in submodule
code example
```
cd /path/to/project/
mv lib /some/other/location/
git rm lib
git commit -m'move lib to submodule'
cd /some/other/location/lib
git init
git add .
git commit
cd /path/to/project/
git submodule add /some/other/location/lib
git commit -m'add submodule'
cd /some/other/location/lib
git checkout -b version2
do some modifications
git commit -m'version2'
cd /path/to/project/lib
git fetch --all
```
now you can simply switch between version1 and version2 by
```
cd /path/to/project/lib
git checkout version2
git checkout master
```
another variant using rebase (not recommended). lets say you have muster branch with version1 of you lib
```
git checkout -b version2
apply changes in you lib wich will bring it to version 2.
git commit
git checkout master
```
now do your work in master (commit something). To see your master changes in version2 branch do
```
git checkout version2
git rebase master
``` | Based on your comments, I think you have to take a similar approach no matter what source code control system you choose.
Keep the vendor code in one repository and your own code in its own repository.
If you have to patch or change the vendor code, then maintain the change management in the vendor repository. If you get a new vendor drop, then, use branches and tags to manage it in the vendor repo.
If you think you have difficulty because your directory tree is intermingled with vendor code and your own code, you need to find a way to separate the two. That is true no matter what source code management system you use. One way is to use symlinks to link vendor code in another directory into a directory in your own repo and do a .gitignore for that vendor symlink in your repo. To switch vendor versions, you go to the vendor directory and do a git checkout of the desired version. |
110,106 | I have stepped by a [YouTube video](https://youtu.be/-NqaupGcCpw) showing Vienna Philharmonic, under John Williams, playing theme from “Jurassic Park”.
In [1:44 minute](https://youtu.be/-NqaupGcCpw?t=104) of this video the drummer is doing *something* with a valve placed next to drums:
[![enter image description here](https://i.stack.imgur.com/jUXs0.jpg)](https://i.stack.imgur.com/jUXs0.jpg)
Can you explain this? What kind of drum is this? And why he is using a valve at all / like that? | 2021/01/23 | [
"https://music.stackexchange.com/questions/110106",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/74673/"
] | It's a kettledrum, aka timpanum.The handles are for changing the tension on the head, which changes the pitch of the drum. There is also a pedal which can be operated by foot, to go from one tuned pitch to another.
Valves are what they're not - there's no gas or liquid passing, only tension produced by a screwing motion. | Timpani, and those handles change the tuning. |
110,106 | I have stepped by a [YouTube video](https://youtu.be/-NqaupGcCpw) showing Vienna Philharmonic, under John Williams, playing theme from “Jurassic Park”.
In [1:44 minute](https://youtu.be/-NqaupGcCpw?t=104) of this video the drummer is doing *something* with a valve placed next to drums:
[![enter image description here](https://i.stack.imgur.com/jUXs0.jpg)](https://i.stack.imgur.com/jUXs0.jpg)
Can you explain this? What kind of drum is this? And why he is using a valve at all / like that? | 2021/01/23 | [
"https://music.stackexchange.com/questions/110106",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/74673/"
] | It's a kettledrum, aka timpanum.The handles are for changing the tension on the head, which changes the pitch of the drum. There is also a pedal which can be operated by foot, to go from one tuned pitch to another.
Valves are what they're not - there's no gas or liquid passing, only tension produced by a screwing motion. | It can be considered a dial with a solid rod mechanism that fine-tunes a kettle drum. Normally the player will set their pedal (lever) to the correct position before a piece and fine-tune while playing. |
2,184,625 | I have a written a [blog](http://dev.haaga.org/~macy/Blog/index.php) using php and mysql which has a login feature. When you are logged out and hit back it should not show the features of a member since you are no longer logged in. How do I correct it so that when a user is no longer logged in and hit back button, the previous page should be in the state before he logged in? | 2010/02/02 | [
"https://Stackoverflow.com/questions/2184625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/262926/"
] | It's hard to discern what authentication mechanism you're using, but assuming this is a pure caching issue you can add the following statements to the beginning of all .php pages displayed while logged in.
```
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 1 Jan 1970 05:00:00 GMT");
```
That should take care of caching issues. And make sure that you `unset()` the access variable you used to keep track of wether or not the user is logged in (in `$_SESSION` or similar). | This is a browser feature. But don't worry, you won't be able to actually do any admin-level stuff if you're not *actually* logged in. If you wanted, you could fire off a request to the server via javascript to ask if the user is logged in upon loading a page. If that request comes back false, you can hide the admin controls, or redirect the user to the index page.
You could explicitly state in code that you wish to *not cache* the pages, but that will slow down visitor-experience, and cause more overhead for your server. I don't think the ends justify the means in that particular solution. |
17,713,470 | Hi I am a new guy to hadoop.
Recently, I put a large amount of text files into HDFS.
What I wanna do is to read these files and put them into HBase using Pig (LOAD, STORE).
However, I found it takes long long time to store into HBase.
Does anyone meet similar situations before? If YES, how to solve this problem?
Thanks | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2593688/"
] | I face the same issue when I use HBaseStorage. Actualy HbaseStorage does sequential PUT operations to load data into HBase. Its not really a bulk load. see this unresolved Jira.
<https://issues.apache.org/jira/browse/PIG-2921>
But I get significant performance difference after using **ImportTSV** option.
<http://hbase.apache.org/book/ops_mgt.html#importtsv>
The bulk load involved three steps
*1. Pig : Read data from source , format in HBASE table structure, load to hdfs.
2. ImportTsv : preparing StoreFiles to be loaded via the completebulkload.
3. completebulkload : move generated StoreFiles into an HBase table. (It's like cut-pest)*
Hope this is useful :) | The time taken depends on the number of nodes you have and obviously the size of the file.
I think its better to check the number of nodes/dfs size w.r.t your input data set. |
35,469,209 | I have a worksheet that lists marines where in column G I have two values, trained and untrained. In column J the value is the unit the marine is with. I want to find the amount trained in each specific unit. Currently I am using `=countif(G2:G99,"TRAINED)` where g2:g99 is the range of marines in unit C, manually finding the range isn't hard, but I want to know if there is a way I can formulate countif that automatically finds the range based on the value in column J
hopefully my question is worded correctly and makes sense | 2016/02/17 | [
"https://Stackoverflow.com/questions/35469209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5942906/"
] | I was actually able to get this to work 100% of the time (in my testing at least) by using files under 500kb. Anything larger seemed to have mixed results.
I also seemed to have missed this page (<https://www.twilio.com/user/account/messaging/logs>) within my account. Clicking on the DateTime stamp will provide more detailed error messaging. | Joe, Megan from Twilio here. Video is not explicitly *supported* for [MMS](https://www.twilio.com/docs/api/rest/sending-messages). It is *accepted*, meaning requests will not be rejected, but content will not be modified for device compatibility.
You can see a full list of [accepted content types here](https://www.twilio.com/docs/api/rest/accepted-mime-types#sts=Video).
Hope this helps. |
31,643,209 | I got the following error message when calling the constructor of the class VS1838B
```
error: no matching function for call to ‘IRrecv::IRrecv()’
VS1838B::VS1838B(int pinoReceptorIR){
^
```
This is part of the header for the VS1838B class:
```
#ifndef INFRAREDRECEIVERVS1838B_H
#define INFRAREDRECEIVERVS1838B_H
#include "Arduino.h"
#include "IRremote.h"
#include "IRremoteInt.h"
class VS1838B{
public:
//Constructor
VS1838B(int pinIR);
//Atributes
int _pinInput;
IRrecv _receptorIR;
decode_results _buffer;
};
#endif /* INFRAREDRECEIVERVS1838B_H */
```
And this is part of the cpp for the same class:
```
#include "Arduino.h"
#include "InfraRedReceiverVs1838b.h"
#include "IRremote.h"
#include "IRremoteInt.h"
VS1838B::VS1838B(int pinIR){
_pinInput = pinIR;
IRrecv receptorIR(_pinInput);
decode_results buffer;
_receptorIR = receptorIR;
_buffer = buffer;
}
```
Note: IRrecv and decode\_results are custom types and their libraries are already included. | 2015/07/26 | [
"https://Stackoverflow.com/questions/31643209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4686873/"
] | Since you **did not provide a whole code example**, I'll instead explain what's wrong since I can still tell.
Your constructor's definition is written like this:
```
VS1838B::VS1838B(int pinIR)
{
// stuff
}
```
Regardless of what `// stuff` is, the compiler will actually insert code...
```
VS1838B::VS1838B(int pinIR)
// <--- here
{
// stuff
}
```
Which calls the default-constructor of every non-POD-type instance in your class, in order, which you did not specifically initialize, in that same spot.
Because you didn't initialize `_receptorIR`, it is inserting a default-constructor call so your constructor REALLY looks like this:
```
VS1838B::VS1838B(int pinIR)
: _receptorID () // ERROR: No default initializer!
, _buffer () // assuming _buffer is non-POD
{
// stuff
}
```
However, `_receptorID` apparently does not have a default constructor that's accessible.
You SHOULD be doing this:
```
VS1838B::VS1838B(int pinIR)
: _pinInput ( pinIR )
, _receptorID ( pinIR )
, _buffer ()
{
// stuff
// Note: you actually don't need to put ANYTHING you
// wrote in your example here because the initializer-list
// above did it all for you.
}
```
But seriously, **POST THE WHOLE CODE**. The error was CLEARLY with the constructor of IRrecv and you didn't even post its prototype. | ```
IRrecv receptorIR(_pinInput);
```
`IRrecv` class don't provide one parameter constructor function,you should provide it. |
169,286 | Referencing *Star Trek - The Voyage Home*, where Kirk saves the whales by traveling back in time to San Francisco.
Are whales extinct in the Kelvin timeline? And did the "Probe" ever visit Earth? | 2017/09/09 | [
"https://scifi.stackexchange.com/questions/169286",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/84323/"
] | Fundamentally, we don't know, but humpback whales are probably extinct, at least during the events of the feature films we've seen so far.
There are two basic points of view. One is that everything that happened before Nero's incursion into the past is exactly the same in both timelines. Although I can't find good quotes from Orci that specifically state this, this seems to be the attitude the writing staff from the first movie had. They also have an attitude that even events AFTER the split are more-or-less the same (with some big differences of course) because (quoting from [this interview](http://www.startrek.com/article/exclusive-orci-opens-up-about-star-trek-into-darkness-part-1)):
>
> We can do whatever we want. However, the rule that we have for ourselves is that it has to harmonize with canon. This is going to get way too geeky, and I apologize ahead of time… Quantum mechanics, which is how we based our time travel, is not just simple time travel. Leonard Nimoy didn’t just go back and change history (as Spock Prime in the 2009 film), and then everything is like Back to the Future. It’s using the rules of quantum mechanics, which means it’s an alternate universe where there is no going back. There is no fixing the timeline. There’s just another reality that is the latest and greatest of time travel that exist. So, on the one hand we’re free. On the other hand, these same rules of quantum mechanics tell us that the universes that exist, they exist because they are the most probable universe. (...) And, therefore, the things that happened in The Original Series didn’t just happen because they happened, they happened because it’s actually what’s most probably going to happen.
>
>
>
Under this view, humpback whales absolutely don't exist at any point in time that we see in the Kelvin timeline, and the probe might have visited Earth in the distant past (if it did when they first made contact with whales--this was never specified), and for the same reasons it did in the Prime timeline probably will appear a few decades after Star Trek: Beyond.
Simon Pegg, on the other hand, wrote this in a [blog post](http://simonpegg.net/2016/07/11/a-word-about-canon/) about Sulu's sexuality (which may arguably have been altered in the Kelvin timeline despite being born before the point of divergence)
>
> With the Kelvin timeline, we are not entirely beholden to existing canon, this is an alternate reality and, as such is full of new and alternate possibilities. “BUT WAIT!” I hear you brilliant and beautiful super Trekkies cry, “Canon tells us, Hikaru Sulu was born before the Kelvin incident, so how could his fundamental humanity be altered? Well, the explanation comes down to something very Star Treky; theoretical, quantum physics and the less than simple fact that time is not linear. Sure, we experience time as a contiguous series of cascading events but perception and reality aren’t always the same thing. Spock’s incursion from the Prime Universe created a multidimensional reality shift. The rift in space/time created an entirely new reality in all directions, top to bottom, from the Big Bang to the end of everything. As such this reality was, is and always will be subtly different from the Prime Universe. I don’t believe for one second that Gene Roddenberry wouldn’t have loved the idea of an alternate reality (Mirror, Mirror anyone?). This means, and this is absolutely key, the Kelvin universe can evolve and change in ways that don’t necessarily have to follow the Prime Universe at any point in history, before or after the events of Star Trek ‘09, it can mutate and subvert, it is a playground for the new and the progressive and I know in my heart, that Gene Roddenberry would be proud of us for keeping his ideals alive. Infinite diversity in infinite combinations, this was his dream, that is our dream, it should be everybody’s.
>
>
>
Under this view, anything goes (but with the understanding that a lot of things are still pretty dang similar in both).
So, theoretically, it's possible that in the Kelvin timeline, humpback whales still exist without time travel reasoning being involved. As far as I know, we've seen no evidence for it, and considering how many other things tended to stay the same, despite wild changes, Orci's view has some weight behind it in regards to most of the past. Probably, Humpback whales went extinct on schedule in the past of both timelines. Probably, the probe still visited in Earth's distant past (if that is indeed what happened in the Prime universe).
Now, because of time travel, we here get into a sticky and thus-far unrevealed part of canon: **Did, in the Kelvin timeline, the crew of the Enterprise (albeit using a Klingon Bird of Prey) appear in the 80s to steal two humpback whales and bring them to the future?**
Again, we don't know, we haven't reached the point in the Kelvin timeline in which they would have made that trip, nor do we know whether previous temporal incursions 'stick' despite the timeline changing (this might in fact be related to Pegg's outlook, the entire history of the universe might have subtly changed in part because of all the time travel that people from the Kelvin timeline would eventually have done differently, or not done at all, that made small alterations to the pre-Kelvin history as well).
So it's possible that, as in Orci's view, the most probable course of quantum events is, in a couple decades, the probe returning and devastating Earth while it waits for a reply, Spock (but now Kelvin-Spock) still figuring out they need Humpback whales, and using the time travel trick to go back in time to get them, and return.
Or it's possible that this will have been changed too, maybe the Enterprise crew is in another part of the galaxy when the probe returns (after all, Wrath of Khan must happen much differently, or not at all, after Into Darkness, and the ship's status and mission in III and IV all spiral directly out of events in II), nobody else will think of going back in time to get whales, nobody ever appeared back in the 80s either, whales are still extinct, and Earth in the Kelvin timeline is in severe danger when it reaches the equivalent time period of Star Trek IV.
Or, it's possible that a Klingon Bird of Prey (piloted by the Prime-Crew) appeared in the 80s to kidnap whales (and the disappearance of said whales, the scientist studying them, and any other associated historical impact from STIV is recorded by the Kelvin timeline's history), and yet again no corresponding Klingon Bird of Prey goes back in time to get them and returns to put them in the ocean (because they came from, and returned to, the Prime timeline) and whales are still extinct so Earth is likely doomed in this scenario too. (But we'll probably never get to see how that winds up affecting the future of the Kelvin timeline and maybe they'll find another solution...)
Or it's possible (though unlikely) that in the Kelvin timeline whales aren't extinct BECAUSE George and Gracie aren't removed from the population in the 80s, and that made all the difference, so there's no reason for the probe to revisit.
That's a lot of possibilities, as must be expected when you're dealing with an unrevealed part of canon complicated by something like time travel that hasn't been used with consistency over a show's run, but most of the possibilities still point towards humpback whales being extinct at least during the timeline of the movies. | It should be noted that ST:IV mentions [Humpback Whales](https://en.wikipedia.org/wiki/Humpback_whale), not all known species of these marine mammals.
According to Memory Alpha, Humpback Whales [were extinct](https://memory-alpha.fandom.com/wiki/Humpback_whale) during the 21st century due to overhunting. So it is safe to assume, *even if the new movies never mention these events*, that they are extinct even in the Kelvin timeline.
About the [Whale Probe](https://memory-alpha.fandom.com/wiki/Whale_Probe), it is of unknown origin, so we can't say if the events that lead to the creation of the new timeline affected it in any way; we don't know if its destiny was somehow changed. |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | If you want to achieve a similar visual effect without changing the text you could cheat with css, with
```
h2, p {
direction: rtl;
unicode-bidi: bidi-override;
}
```
this will reverse the text
example fiddle: <http://jsfiddle.net/pn6Ga/> | Parse the HTML with something that will give you a DOM API to it.
Write a function that loops over the child nodes of an element.
If a node is a text node, get the data as a string, split it on words, reverse each one, then assign it back.
If a node is an element, recurse into your function. |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | Hi I came to this situation long time ago and i used the following code. Here is a rough code
```
<?php
function keepcase($word, $replace) {
$replace[0] = (ctype_upper($word[0]) ? strtoupper($replace[0]) : $replace[0]);
return $replace;
}
// regex - match the contents grouping into HTMLTAG and non-HTMLTAG chunks
$re = '%(</?\w++[^<>]*+>) # grab HTML open or close TAG into group 1
| # or...
([^<]*+(?:(?!</?\w++[^<>]*+>)<[^<]*+)*+) # grab non-HTMLTAG text into group 2
%x';
$contents = '<h2>Header</h2><p>the <span class="bright">content</span> here</p>';
// walk through the content, chunk, by chunk, replacing words in non-NTMLTAG chunks only
$contents = preg_replace_callback($re, 'callback_func', $contents);
function callback_func($matches) { // here's the callback function
if ($matches[1]) { // Case 1: this is a HTMLTAG
return $matches[1]; // return HTMLTAG unmodified
}
elseif (isset($matches[2])) { // Case 2: a non-HTMLTAG chunk.
// declare these here
// or use as global vars?
return preg_replace('/\b' . $matches[2] . '\b/ei', "keepcase('\\0', '".strrev($matches[2])."')",
$matches[2]);
}
exit("Error!"); // never get here
}
echo ($contents);
?>
``` | Parse the HTML with something that will give you a DOM API to it.
Write a function that loops over the child nodes of an element.
If a node is a text node, get the data as a string, split it on words, reverse each one, then assign it back.
If a node is an element, recurse into your function. |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | I implemented a version that seems to work quite well - although I still use (rather general and shoddy) regex to extract the html tags from the text. Here it is now in commented javascript:
Method
------
```
/**
* Manipulate text inside HTML according to passed function
* @param html the html string to manipulate
* @param manipulator the funciton to manipulate with (will be passed single word)
* @returns manipulated string including unmodified HTML
*
* Currently limited in that manipulator operates on words determined by regex
* word boundaries, and must return same length manipulated word
*
*/
var manipulate = function(html, manipulator) {
var block, tag, words, i,
final = '', // used to prepare return value
tags = [], // used to store tags as they are stripped from the html string
x = 0; // used to track the number of characters the html string is reduced by during stripping
// remove tags from html string, and use callback to store them with their index
// then split by word boundaries to get plain words from original html
words = html.replace(/<.+?>/g, function(match, index) {
tags.unshift({
match: match,
index: index - x
});
x += match.length;
return '';
}).split(/\b/);
// loop through each word and build the final string
// appending the word, or manipulated word if not a boundary
for (i = 0; i < words.length; i++) {
final += i % 2 ? words[i] : manipulator(words[i]);
}
// loop through each stored tag, and insert into final string
for (i = 0; i < tags.length; i++) {
final = final.slice(0, tags[i].index) + tags[i].match + final.slice(tags[i].index);
}
// ready to go!
return final;
};
```
The function defined above accepts a string of HTML, and a manipulation function to act on words within the string regardless of if they are split by HTML elements or not.
It works by first removing all HTML tags, and storing the tag along with the index it was taken from, then manipulating the text, then adding the tags into their original position in reverse order.
Test
----
```
/**
* Test our function with various input
*/
var reverse, rutherford, shuffle, text, titleCase;
// set our test html string
text = "<h2>Header</h2><p>all the <span class=\"bright\">content</span> here</p>\nQuick<em>Draw</em>McGraw\n<em>going</em><i>home</i>";
// function used to reverse words
reverse = function(s) {
return s.split('').reverse().join('');
};
// function used by rutherford to return a shuffled array
shuffle = function(a) {
return a.sort(function() {
return Math.round(Math.random()) - 0.5;
});
};
// function used to shuffle the middle of words, leaving each end undisturbed
rutherford = function(inc) {
var m = inc.match(/^(.?)(.*?)(.)$/);
return m[1] + shuffle(m[2].split('')).join('') + m[3];
};
// function to make word Title Cased
titleCase = function(s) {
return s.replace(/./, function(w) {
return w.toUpperCase();
});
};
console.log(manipulate(text, reverse));
console.log(manipulate(text, rutherford));
console.log(manipulate(text, titleCase));
```
There are still a few quirks, like the heading and paragraph text not being recognized as separate words (because they are in separate block level tags rather than inline tags) but this is basically a proof of method of what I was trying to do.
I would also like it to be able to handle the string manipulation formula actually adding and removing text, rather than replacing/moving it (so variable string length after manipulation) but that opens up a whole new can of works I am not yet ready for.
Now I have added some comments to the code, and put it up as a gist in javascript, I hope that someone will improve it - especially if someone could remove the regex part and replace with something better!
Gist: <https://gist.github.com/3309906>
---------------------------------------
Demo: <http://jsfiddle.net/gh/gist/underscore/1/3309906/>
---------------------------------------------------------
(outputs to console)
And now finally using an HTML parser
------------------------------------
(http://ejohn.org/files/htmlparser.js)
Demo: <http://jsfiddle.net/EDJyU/> | Parse the HTML with something that will give you a DOM API to it.
Write a function that loops over the child nodes of an element.
If a node is a text node, get the data as a string, split it on words, reverse each one, then assign it back.
If a node is an element, recurse into your function. |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | If you want to achieve a similar visual effect without changing the text you could cheat with css, with
```
h2, p {
direction: rtl;
unicode-bidi: bidi-override;
}
```
this will reverse the text
example fiddle: <http://jsfiddle.net/pn6Ga/> | could use jquery?
```
$('div *').each(function(){
text = $(this).text();
text = text.split('');
text = text.reverse();
text = text.join('');
$(this).text(text);
});
```
See here - <http://jsfiddle.net/GCAvb/> |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | If you want to achieve a similar visual effect without changing the text you could cheat with css, with
```
h2, p {
direction: rtl;
unicode-bidi: bidi-override;
}
```
this will reverse the text
example fiddle: <http://jsfiddle.net/pn6Ga/> | You can use a setInterval to change it every \*\* time for example:
```js
const TITTLE = document.getElementById("Tittle") //Let's get the div
setInterval(()=> {
let TITTLE2 = document.getElementById("rotate") //we get the element at the moment of execution
let spanTittle = document.createElement("span"); // we create the new element "span"
spanTittle.setAttribute("id","rotate"); // attribute to new element
(TITTLE2.textContent == "TEXT1") // We compare wich string is in the div
? spanTittle.appendChild(document.createTextNode(`TEXT2`))
: spanTittle.appendChild(document.createTextNode(`TEXT1`))
TITTLE.replaceChild(spanTittle,TITTLE2) //finally, replace the old span for a new
},2000)
```
```html
<html>
<head></head>
<body>
<div id="Tittle">TEST YOUR <span id="rotate">TEXT1</span></div>
</body>
</html>
``` |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | Hi I came to this situation long time ago and i used the following code. Here is a rough code
```
<?php
function keepcase($word, $replace) {
$replace[0] = (ctype_upper($word[0]) ? strtoupper($replace[0]) : $replace[0]);
return $replace;
}
// regex - match the contents grouping into HTMLTAG and non-HTMLTAG chunks
$re = '%(</?\w++[^<>]*+>) # grab HTML open or close TAG into group 1
| # or...
([^<]*+(?:(?!</?\w++[^<>]*+>)<[^<]*+)*+) # grab non-HTMLTAG text into group 2
%x';
$contents = '<h2>Header</h2><p>the <span class="bright">content</span> here</p>';
// walk through the content, chunk, by chunk, replacing words in non-NTMLTAG chunks only
$contents = preg_replace_callback($re, 'callback_func', $contents);
function callback_func($matches) { // here's the callback function
if ($matches[1]) { // Case 1: this is a HTMLTAG
return $matches[1]; // return HTMLTAG unmodified
}
elseif (isset($matches[2])) { // Case 2: a non-HTMLTAG chunk.
// declare these here
// or use as global vars?
return preg_replace('/\b' . $matches[2] . '\b/ei', "keepcase('\\0', '".strrev($matches[2])."')",
$matches[2]);
}
exit("Error!"); // never get here
}
echo ($contents);
?>
``` | could use jquery?
```
$('div *').each(function(){
text = $(this).text();
text = text.split('');
text = text.reverse();
text = text.join('');
$(this).text(text);
});
```
See here - <http://jsfiddle.net/GCAvb/> |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | I implemented a version that seems to work quite well - although I still use (rather general and shoddy) regex to extract the html tags from the text. Here it is now in commented javascript:
Method
------
```
/**
* Manipulate text inside HTML according to passed function
* @param html the html string to manipulate
* @param manipulator the funciton to manipulate with (will be passed single word)
* @returns manipulated string including unmodified HTML
*
* Currently limited in that manipulator operates on words determined by regex
* word boundaries, and must return same length manipulated word
*
*/
var manipulate = function(html, manipulator) {
var block, tag, words, i,
final = '', // used to prepare return value
tags = [], // used to store tags as they are stripped from the html string
x = 0; // used to track the number of characters the html string is reduced by during stripping
// remove tags from html string, and use callback to store them with their index
// then split by word boundaries to get plain words from original html
words = html.replace(/<.+?>/g, function(match, index) {
tags.unshift({
match: match,
index: index - x
});
x += match.length;
return '';
}).split(/\b/);
// loop through each word and build the final string
// appending the word, or manipulated word if not a boundary
for (i = 0; i < words.length; i++) {
final += i % 2 ? words[i] : manipulator(words[i]);
}
// loop through each stored tag, and insert into final string
for (i = 0; i < tags.length; i++) {
final = final.slice(0, tags[i].index) + tags[i].match + final.slice(tags[i].index);
}
// ready to go!
return final;
};
```
The function defined above accepts a string of HTML, and a manipulation function to act on words within the string regardless of if they are split by HTML elements or not.
It works by first removing all HTML tags, and storing the tag along with the index it was taken from, then manipulating the text, then adding the tags into their original position in reverse order.
Test
----
```
/**
* Test our function with various input
*/
var reverse, rutherford, shuffle, text, titleCase;
// set our test html string
text = "<h2>Header</h2><p>all the <span class=\"bright\">content</span> here</p>\nQuick<em>Draw</em>McGraw\n<em>going</em><i>home</i>";
// function used to reverse words
reverse = function(s) {
return s.split('').reverse().join('');
};
// function used by rutherford to return a shuffled array
shuffle = function(a) {
return a.sort(function() {
return Math.round(Math.random()) - 0.5;
});
};
// function used to shuffle the middle of words, leaving each end undisturbed
rutherford = function(inc) {
var m = inc.match(/^(.?)(.*?)(.)$/);
return m[1] + shuffle(m[2].split('')).join('') + m[3];
};
// function to make word Title Cased
titleCase = function(s) {
return s.replace(/./, function(w) {
return w.toUpperCase();
});
};
console.log(manipulate(text, reverse));
console.log(manipulate(text, rutherford));
console.log(manipulate(text, titleCase));
```
There are still a few quirks, like the heading and paragraph text not being recognized as separate words (because they are in separate block level tags rather than inline tags) but this is basically a proof of method of what I was trying to do.
I would also like it to be able to handle the string manipulation formula actually adding and removing text, rather than replacing/moving it (so variable string length after manipulation) but that opens up a whole new can of works I am not yet ready for.
Now I have added some comments to the code, and put it up as a gist in javascript, I hope that someone will improve it - especially if someone could remove the regex part and replace with something better!
Gist: <https://gist.github.com/3309906>
---------------------------------------
Demo: <http://jsfiddle.net/gh/gist/underscore/1/3309906/>
---------------------------------------------------------
(outputs to console)
And now finally using an HTML parser
------------------------------------
(http://ejohn.org/files/htmlparser.js)
Demo: <http://jsfiddle.net/EDJyU/> | could use jquery?
```
$('div *').each(function(){
text = $(this).text();
text = text.split('');
text = text.reverse();
text = text.join('');
$(this).text(text);
});
```
See here - <http://jsfiddle.net/GCAvb/> |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | Hi I came to this situation long time ago and i used the following code. Here is a rough code
```
<?php
function keepcase($word, $replace) {
$replace[0] = (ctype_upper($word[0]) ? strtoupper($replace[0]) : $replace[0]);
return $replace;
}
// regex - match the contents grouping into HTMLTAG and non-HTMLTAG chunks
$re = '%(</?\w++[^<>]*+>) # grab HTML open or close TAG into group 1
| # or...
([^<]*+(?:(?!</?\w++[^<>]*+>)<[^<]*+)*+) # grab non-HTMLTAG text into group 2
%x';
$contents = '<h2>Header</h2><p>the <span class="bright">content</span> here</p>';
// walk through the content, chunk, by chunk, replacing words in non-NTMLTAG chunks only
$contents = preg_replace_callback($re, 'callback_func', $contents);
function callback_func($matches) { // here's the callback function
if ($matches[1]) { // Case 1: this is a HTMLTAG
return $matches[1]; // return HTMLTAG unmodified
}
elseif (isset($matches[2])) { // Case 2: a non-HTMLTAG chunk.
// declare these here
// or use as global vars?
return preg_replace('/\b' . $matches[2] . '\b/ei', "keepcase('\\0', '".strrev($matches[2])."')",
$matches[2]);
}
exit("Error!"); // never get here
}
echo ($contents);
?>
``` | You can use a setInterval to change it every \*\* time for example:
```js
const TITTLE = document.getElementById("Tittle") //Let's get the div
setInterval(()=> {
let TITTLE2 = document.getElementById("rotate") //we get the element at the moment of execution
let spanTittle = document.createElement("span"); // we create the new element "span"
spanTittle.setAttribute("id","rotate"); // attribute to new element
(TITTLE2.textContent == "TEXT1") // We compare wich string is in the div
? spanTittle.appendChild(document.createTextNode(`TEXT2`))
: spanTittle.appendChild(document.createTextNode(`TEXT1`))
TITTLE.replaceChild(spanTittle,TITTLE2) //finally, replace the old span for a new
},2000)
```
```html
<html>
<head></head>
<body>
<div id="Tittle">TEST YOUR <span id="rotate">TEXT1</span></div>
</body>
</html>
``` |
11,884,839 | If I have a string of HTML, maybe like this...
```
<h2>Header</h2><p>all the <span class="bright">content</span> here</p>
```
And I want to manipulate the string so that all words are reversed for example...
```
<h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p>
```
I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML?
I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific.
Edit
----
I also want to be able to manipulate text that spans several DOM elements...
```
Quick<em>Draw</em>McGraw
warGcM<em>warD</em>kciuQ
```
Another Edit
------------
Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array.
This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for.
Yet Another Edit
----------------
I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this...
```
<em>going</em><i>home</i>
```
Converts to
```
<em>goonh</em><i>gmie</i>
```
So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula. | 2012/08/09 | [
"https://Stackoverflow.com/questions/11884839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] | I implemented a version that seems to work quite well - although I still use (rather general and shoddy) regex to extract the html tags from the text. Here it is now in commented javascript:
Method
------
```
/**
* Manipulate text inside HTML according to passed function
* @param html the html string to manipulate
* @param manipulator the funciton to manipulate with (will be passed single word)
* @returns manipulated string including unmodified HTML
*
* Currently limited in that manipulator operates on words determined by regex
* word boundaries, and must return same length manipulated word
*
*/
var manipulate = function(html, manipulator) {
var block, tag, words, i,
final = '', // used to prepare return value
tags = [], // used to store tags as they are stripped from the html string
x = 0; // used to track the number of characters the html string is reduced by during stripping
// remove tags from html string, and use callback to store them with their index
// then split by word boundaries to get plain words from original html
words = html.replace(/<.+?>/g, function(match, index) {
tags.unshift({
match: match,
index: index - x
});
x += match.length;
return '';
}).split(/\b/);
// loop through each word and build the final string
// appending the word, or manipulated word if not a boundary
for (i = 0; i < words.length; i++) {
final += i % 2 ? words[i] : manipulator(words[i]);
}
// loop through each stored tag, and insert into final string
for (i = 0; i < tags.length; i++) {
final = final.slice(0, tags[i].index) + tags[i].match + final.slice(tags[i].index);
}
// ready to go!
return final;
};
```
The function defined above accepts a string of HTML, and a manipulation function to act on words within the string regardless of if they are split by HTML elements or not.
It works by first removing all HTML tags, and storing the tag along with the index it was taken from, then manipulating the text, then adding the tags into their original position in reverse order.
Test
----
```
/**
* Test our function with various input
*/
var reverse, rutherford, shuffle, text, titleCase;
// set our test html string
text = "<h2>Header</h2><p>all the <span class=\"bright\">content</span> here</p>\nQuick<em>Draw</em>McGraw\n<em>going</em><i>home</i>";
// function used to reverse words
reverse = function(s) {
return s.split('').reverse().join('');
};
// function used by rutherford to return a shuffled array
shuffle = function(a) {
return a.sort(function() {
return Math.round(Math.random()) - 0.5;
});
};
// function used to shuffle the middle of words, leaving each end undisturbed
rutherford = function(inc) {
var m = inc.match(/^(.?)(.*?)(.)$/);
return m[1] + shuffle(m[2].split('')).join('') + m[3];
};
// function to make word Title Cased
titleCase = function(s) {
return s.replace(/./, function(w) {
return w.toUpperCase();
});
};
console.log(manipulate(text, reverse));
console.log(manipulate(text, rutherford));
console.log(manipulate(text, titleCase));
```
There are still a few quirks, like the heading and paragraph text not being recognized as separate words (because they are in separate block level tags rather than inline tags) but this is basically a proof of method of what I was trying to do.
I would also like it to be able to handle the string manipulation formula actually adding and removing text, rather than replacing/moving it (so variable string length after manipulation) but that opens up a whole new can of works I am not yet ready for.
Now I have added some comments to the code, and put it up as a gist in javascript, I hope that someone will improve it - especially if someone could remove the regex part and replace with something better!
Gist: <https://gist.github.com/3309906>
---------------------------------------
Demo: <http://jsfiddle.net/gh/gist/underscore/1/3309906/>
---------------------------------------------------------
(outputs to console)
And now finally using an HTML parser
------------------------------------
(http://ejohn.org/files/htmlparser.js)
Demo: <http://jsfiddle.net/EDJyU/> | You can use a setInterval to change it every \*\* time for example:
```js
const TITTLE = document.getElementById("Tittle") //Let's get the div
setInterval(()=> {
let TITTLE2 = document.getElementById("rotate") //we get the element at the moment of execution
let spanTittle = document.createElement("span"); // we create the new element "span"
spanTittle.setAttribute("id","rotate"); // attribute to new element
(TITTLE2.textContent == "TEXT1") // We compare wich string is in the div
? spanTittle.appendChild(document.createTextNode(`TEXT2`))
: spanTittle.appendChild(document.createTextNode(`TEXT1`))
TITTLE.replaceChild(spanTittle,TITTLE2) //finally, replace the old span for a new
},2000)
```
```html
<html>
<head></head>
<body>
<div id="Tittle">TEST YOUR <span id="rotate">TEXT1</span></div>
</body>
</html>
``` |
30,738,344 | I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following:
**config.json**
```
{
"AppSettings": {
"Environment":"dev"
},
"DbSettings": {
"AppConnectionString": "..."
},
"EmailSettings": {
"EmailApiKey": "..."
},
}
```
I am trying to figure out how to load these settings into a configuration file in Startup.cs. Currently, I have a file that looks like this:
**Configuration.cs**
```
public class AppConfiguration
{
public AppSettings AppSettings { get; set; }
public DbSettings DbSettings { get; set; }
public EmailSettings EmailSettings { get; set; }
}
public class AppSettings
{
public string Environment { get; set; }
}
public class DbSettings
{
public string AppConnectionString { get; set; }
}
public class EmailSettings
{
public string MandrillApiKey { get; set; }
}
```
Then, in Startup.cs, I have the following:
```
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
{
var configuration = new Configuration().AddJsonFile("config.json");
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppConfiguration>(Configuration);
}
```
However, this approach doesn't work. Basically, its like it doesn't know how to map between the .json and the Config classes. How do I do this?
I would really like to stay with the DI approach so I can test my app more effectively.
Thank you | 2015/06/09 | [
"https://Stackoverflow.com/questions/30738344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4703156/"
] | You can simply access the value of config property `Environment` by using `Configuration` class like this anywhere in your application.
```
var environment = Configuration["AppSettings:Environment"];
```
But if you want it to access through a property of class you can do this
```
public class AppSettings
{
public string Environment
{
get
{
return new Configuration().Get("AppSettings:Environment").ToString();
}
set;
}
}
```
**Note** I haven't set the value of `Environment` in setter because this value will be in `config.json` so there is no need to set this value in setter.
For more details have a look at this [article](http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/#.VWcNi8-qqko). | Try use `OptionsModel`. it allows strong typed model binding to configuration.
```
class AppSettings
{
public string SomeSetting {get;set;}
}
var configuration = new Configuration().AddJsonFile("config.json");
var opt = ConfigurationBinder.Bind<AppSettings>(configuration);
opt.SomeSetting
```
Example:
<https://github.com/aspnet/Options/blob/dev/test/Microsoft.Framework.OptionsModel.Test/OptionsTest.cs#L80> |
30,738,344 | I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following:
**config.json**
```
{
"AppSettings": {
"Environment":"dev"
},
"DbSettings": {
"AppConnectionString": "..."
},
"EmailSettings": {
"EmailApiKey": "..."
},
}
```
I am trying to figure out how to load these settings into a configuration file in Startup.cs. Currently, I have a file that looks like this:
**Configuration.cs**
```
public class AppConfiguration
{
public AppSettings AppSettings { get; set; }
public DbSettings DbSettings { get; set; }
public EmailSettings EmailSettings { get; set; }
}
public class AppSettings
{
public string Environment { get; set; }
}
public class DbSettings
{
public string AppConnectionString { get; set; }
}
public class EmailSettings
{
public string MandrillApiKey { get; set; }
}
```
Then, in Startup.cs, I have the following:
```
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
{
var configuration = new Configuration().AddJsonFile("config.json");
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppConfiguration>(Configuration);
}
```
However, this approach doesn't work. Basically, its like it doesn't know how to map between the .json and the Config classes. How do I do this?
I would really like to stay with the DI approach so I can test my app more effectively.
Thank you | 2015/06/09 | [
"https://Stackoverflow.com/questions/30738344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4703156/"
] | In your `Startup` class, first specify your configuration sources:
```
private readonly IConfiguration configuration;
public Startup(IHostingEnvironment env)
{
configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
}
```
*The `env.EnvironmentName` is something like `"development"` or `"production"`. Suppose it is `"development"`. The framework will try to pull configuration values from `config.development.json` first. If the requested values aren't there, or the `config.development.json` file doesn't exist, then the framework will try to pull the values from `config.json`.*
Configure your `config.json` sections as services like this:
```
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(configuration.GetSubKey("AppSettings"));
services.Configure<DbSettings>(configuration.GetSubKey("DbSettings"));
services.Configure<EmailSettings>(configuration.GetSubKey("EmailSettings"));
}
```
*Calling `Configure<T>(IConfiguration)` on the `IServiceCollection` registers the type `IOptions<T>` in the dependency injection container. Note that you don't need your `AppConfiguration` class.*
Then specify dependencies to be injected like this:
```
public class EmailController : Controller
{
private readonly IOptions<EmailSettings> emailSettings;
public EmailController (IOptions<EmailSettings> emailSettings)
{
this.emailSettings = emailSettings;
}
public IActionResult Index()
{
string apiKey = emailSettings.Options.EmailApiKey;
...
}
}
``` | Try use `OptionsModel`. it allows strong typed model binding to configuration.
```
class AppSettings
{
public string SomeSetting {get;set;}
}
var configuration = new Configuration().AddJsonFile("config.json");
var opt = ConfigurationBinder.Bind<AppSettings>(configuration);
opt.SomeSetting
```
Example:
<https://github.com/aspnet/Options/blob/dev/test/Microsoft.Framework.OptionsModel.Test/OptionsTest.cs#L80> |
30,738,344 | I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following:
**config.json**
```
{
"AppSettings": {
"Environment":"dev"
},
"DbSettings": {
"AppConnectionString": "..."
},
"EmailSettings": {
"EmailApiKey": "..."
},
}
```
I am trying to figure out how to load these settings into a configuration file in Startup.cs. Currently, I have a file that looks like this:
**Configuration.cs**
```
public class AppConfiguration
{
public AppSettings AppSettings { get; set; }
public DbSettings DbSettings { get; set; }
public EmailSettings EmailSettings { get; set; }
}
public class AppSettings
{
public string Environment { get; set; }
}
public class DbSettings
{
public string AppConnectionString { get; set; }
}
public class EmailSettings
{
public string MandrillApiKey { get; set; }
}
```
Then, in Startup.cs, I have the following:
```
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
{
var configuration = new Configuration().AddJsonFile("config.json");
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppConfiguration>(Configuration);
}
```
However, this approach doesn't work. Basically, its like it doesn't know how to map between the .json and the Config classes. How do I do this?
I would really like to stay with the DI approach so I can test my app more effectively.
Thank you | 2015/06/09 | [
"https://Stackoverflow.com/questions/30738344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4703156/"
] | In your `Startup` class, first specify your configuration sources:
```
private readonly IConfiguration configuration;
public Startup(IHostingEnvironment env)
{
configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
}
```
*The `env.EnvironmentName` is something like `"development"` or `"production"`. Suppose it is `"development"`. The framework will try to pull configuration values from `config.development.json` first. If the requested values aren't there, or the `config.development.json` file doesn't exist, then the framework will try to pull the values from `config.json`.*
Configure your `config.json` sections as services like this:
```
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(configuration.GetSubKey("AppSettings"));
services.Configure<DbSettings>(configuration.GetSubKey("DbSettings"));
services.Configure<EmailSettings>(configuration.GetSubKey("EmailSettings"));
}
```
*Calling `Configure<T>(IConfiguration)` on the `IServiceCollection` registers the type `IOptions<T>` in the dependency injection container. Note that you don't need your `AppConfiguration` class.*
Then specify dependencies to be injected like this:
```
public class EmailController : Controller
{
private readonly IOptions<EmailSettings> emailSettings;
public EmailController (IOptions<EmailSettings> emailSettings)
{
this.emailSettings = emailSettings;
}
public IActionResult Index()
{
string apiKey = emailSettings.Options.EmailApiKey;
...
}
}
``` | You can simply access the value of config property `Environment` by using `Configuration` class like this anywhere in your application.
```
var environment = Configuration["AppSettings:Environment"];
```
But if you want it to access through a property of class you can do this
```
public class AppSettings
{
public string Environment
{
get
{
return new Configuration().Get("AppSettings:Environment").ToString();
}
set;
}
}
```
**Note** I haven't set the value of `Environment` in setter because this value will be in `config.json` so there is no need to set this value in setter.
For more details have a look at this [article](http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/#.VWcNi8-qqko). |
57,772,105 | * I am making an application in which database products will be added to an xml file.
+ after querying the xml file, these products will be added to an array.
+ This array would be sent to the other activity, such as, MainActivity for Menu, but **I can't send the array through `Intent`**.
```
//MainActivity
public class MainActivity extends AppCompatActivity {
public ArrayList<Produto> array;
private File Produtos;
private FileOutputStream fileos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
array = new ArrayList<Produto>();
//if there is no xml file this goes to the database and adds the products in an xml file
if ((Produtos.exists() == false))
AdicionarProdutosXML();
//query xml file and add the products in an array
ConsultarFicheirosXml();
//pass the array from one activity to another
Intent i=new Intent(MainActivity.this,Menu.class);
i.putExtra("array",array);
startActivity(i);
}
public void ConsultarFicheirosXml()
{
int tipo=0;
String nome="";
float pvp=0;
int quantidade;
int eventType=0;
XmlPullParser parser=null;
File file=null;
FileInputStream fis=null;
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
file = new File("/mnt/sdcard/Produtos.xml");
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parser.setInput(new InputStreamReader(fis));
eventType=parser.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(eventType!=XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if (parser.getName().equalsIgnoreCase("Tipo")) {
Produto p = new Produto();
try {
tipo= Integer.valueOf(parser.nextText());
parser.nextTag();
nome=parser.nextText();
parser.nextTag();
pvp=Float.valueOf(parser.nextText());
parser.nextTag();
quantidade=Integer.valueOf(parser.nextText());
parser.nextTag();
p.tipo=tipo;
p.nome=nome;
p.pvp=pvp;
p.quantidade=quantidade;
array.add(p);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.END_DOCUMENT:
break;
}
try {
eventType = parser.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//another activity
public class Menu extends AppCompatActivity {
public ArrayList<Produto> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Bundle produtos=getIntent().getExtras();
}
``` | 2019/09/03 | [
"https://Stackoverflow.com/questions/57772105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11990252/"
] | Just post it here to help everyone that have same problem
Update your tsconfig.json file with either options
```
"skipTemplateCodegen": false,
"strictMetadataEmit": false
```
or
```
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true
```
Another suggest link to take a look at
<https://github.com/gevgeny/angular2-highcharts/issues/156#issue-207301509>
Update double check my config with your to see if it work
tsconfig.json
```
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "esnext",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}
```
angular.json
```
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular8": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular8",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angular8:build"
},
"configurations": {
"production": {
"browserTarget": "angular8:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "angular8:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "angular8:serve"
},
"configurations": {
"production": {
"devServerTarget": "angular8:serve:production"
}
}
}
}
}},
"defaultProject": "angular8"
}
``` | You should show us your app.module files and the usage of ɵmakeDecorator for a more detailed investigation, but it seems that you should check if you are using imports correctly. More info can be found [here](https://github.com/ng-packagr/ng-packagr/issues/727)
EDIT:
Just moving up the solution that seems to work for the author which was provided in this post comments:
>
> This comment right here [github.com/ng-packagr/ng-packagr/issues/](http://github.com/ng-packagr/ng-packagr/issues/)… was helpful
>
>
> |
6,168,935 | Hopefully a quick question. I'm trying to validate a double. Making sure it's positive to one decimal place.
Good Values: 0.1, 2.5, 100.1, 1, 54
Bad Values: -0.1, 1.123, 1.12, abc, 00012.1
So I've tried Regex here:
```
public boolean isValidAge(String doubleNumber)
{
DoubleValidator doubleValidator = new DoubleValidator();
return doubleValidator.isValid(doubleNumber,"*[0-9]\\\\.[0-9]");
}
```
I've also tried: `"*[0-9].[0-9]"`, `"\\\\d+(\\\\.\\\\d{1})?"`, `"[0-9]+(\\\\.[0-9]?)?"`
Nothing seems to be working. I've been using `org.apache.commons.validator.routines.DoubleValidator`
Is there another way I can do this any reason why these regex's aren't working? I don't have to use regex.
Thanks | 2011/05/29 | [
"https://Stackoverflow.com/questions/6168935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/152405/"
] | This will match a number and only a number with either a multi-digit pre-decimal point number with no leading zero(s), or just a zero, and optionally a decimal point with one decimal digit. Includes match of the beginning/end of string, so it won't match a number in a larger string (*updated to not accept leading zeros, credit @Nicklas A*):
```
^([1-9]\d*|0)(\.\d)?$
```
Use the `java.util.regex.Pattern` library instead.
<http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html>
Because you're putting the regex into a string, be sure to escape the backslashes
```
"^([1-9]\\d*|0)(\\.\\d)?$"
```
I recommend that you read up on regular expressions here, they are an important tool to have "under your belt" so to speak.
<http://www.regular-expressions.info/> | ```
Pattern.compile ("[0-9]+\\.[0-9])").matcher (doubleNumber).matches ()
```
would do the trick.
If you also want to allow no decimal point:
```
Pattern.compile ("[0-9]+(\\.[0-9])?").matcher (doubleNumber).matches ()
```
**EDIT :** following your comment about no leading zeros and an integer is OK:
```
Pattern.compile("([1-9][0-9]*|[0-9])(\\.[0-9])?").matcher(doubleNumber).matches()
``` |
6,168,935 | Hopefully a quick question. I'm trying to validate a double. Making sure it's positive to one decimal place.
Good Values: 0.1, 2.5, 100.1, 1, 54
Bad Values: -0.1, 1.123, 1.12, abc, 00012.1
So I've tried Regex here:
```
public boolean isValidAge(String doubleNumber)
{
DoubleValidator doubleValidator = new DoubleValidator();
return doubleValidator.isValid(doubleNumber,"*[0-9]\\\\.[0-9]");
}
```
I've also tried: `"*[0-9].[0-9]"`, `"\\\\d+(\\\\.\\\\d{1})?"`, `"[0-9]+(\\\\.[0-9]?)?"`
Nothing seems to be working. I've been using `org.apache.commons.validator.routines.DoubleValidator`
Is there another way I can do this any reason why these regex's aren't working? I don't have to use regex.
Thanks | 2011/05/29 | [
"https://Stackoverflow.com/questions/6168935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/152405/"
] | This will match a number and only a number with either a multi-digit pre-decimal point number with no leading zero(s), or just a zero, and optionally a decimal point with one decimal digit. Includes match of the beginning/end of string, so it won't match a number in a larger string (*updated to not accept leading zeros, credit @Nicklas A*):
```
^([1-9]\d*|0)(\.\d)?$
```
Use the `java.util.regex.Pattern` library instead.
<http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html>
Because you're putting the regex into a string, be sure to escape the backslashes
```
"^([1-9]\\d*|0)(\\.\\d)?$"
```
I recommend that you read up on regular expressions here, they are an important tool to have "under your belt" so to speak.
<http://www.regular-expressions.info/> | if you need to validate decimal with dots, commas, positives and negatives:
```
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+([\\.\\,]{1}[0-9]{1}){0,1}$", (CharSequence) testObject);
```
Good luck. |
6,168,935 | Hopefully a quick question. I'm trying to validate a double. Making sure it's positive to one decimal place.
Good Values: 0.1, 2.5, 100.1, 1, 54
Bad Values: -0.1, 1.123, 1.12, abc, 00012.1
So I've tried Regex here:
```
public boolean isValidAge(String doubleNumber)
{
DoubleValidator doubleValidator = new DoubleValidator();
return doubleValidator.isValid(doubleNumber,"*[0-9]\\\\.[0-9]");
}
```
I've also tried: `"*[0-9].[0-9]"`, `"\\\\d+(\\\\.\\\\d{1})?"`, `"[0-9]+(\\\\.[0-9]?)?"`
Nothing seems to be working. I've been using `org.apache.commons.validator.routines.DoubleValidator`
Is there another way I can do this any reason why these regex's aren't working? I don't have to use regex.
Thanks | 2011/05/29 | [
"https://Stackoverflow.com/questions/6168935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/152405/"
] | ```
Pattern.compile ("[0-9]+\\.[0-9])").matcher (doubleNumber).matches ()
```
would do the trick.
If you also want to allow no decimal point:
```
Pattern.compile ("[0-9]+(\\.[0-9])?").matcher (doubleNumber).matches ()
```
**EDIT :** following your comment about no leading zeros and an integer is OK:
```
Pattern.compile("([1-9][0-9]*|[0-9])(\\.[0-9])?").matcher(doubleNumber).matches()
``` | if you need to validate decimal with dots, commas, positives and negatives:
```
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+([\\.\\,]{1}[0-9]{1}){0,1}$", (CharSequence) testObject);
```
Good luck. |
42,743,413 | Animating with jQuery is straightforward. Here's an example of animating a number from 0 to 1000 over 2 seconds:
```
var $h1 = $('h1'),
startValue = parseInt($h1.text(), 10),
endValue = parseInt($h1.data('end-value'), 10);
$({ int: startValue })
.animate({
int: endValue
}, {
duration: 2 * 1000,
step: function () {
$h1.text(Math.ceil(this.int));
}
});
```
*Working example: <http://codepen.io/troywarr/pen/NpjyJE?editors=1010#0>*
This animation looks nice, but makes it difficult to read the number at any point during the animation, as the next number replaces it within milliseconds. Ideally, I'd like to animate the number over the same length of time but using fewer steps (increasing the length of the update interval), so that it's easier to read the number at a glance as it animates.
It doesn't appear that jQuery offers direct control over the number of steps in the animation, nor the update interval; it only seems to accept a [`step` function](http://api.jquery.com/animate/ "jQuery .animate() method documentation") that receives an interpolated value.
Is there a way to adjust the number of steps that jQuery uses to interpolate the animation over its duration? | 2017/03/12 | [
"https://Stackoverflow.com/questions/42743413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/167911/"
] | You can use `regular expression` to achieve this,
```
var result = "3 rolls 7 buns 9 bars 7 cooks".split(/\s(?=\d)/);
conosole.log(result); //["3 rolls", "7 buns", "9 bars", "7 cooks"]
```
The regex concept used here is `positive look ahead`. | You can use `String.prototype.match()` with `RegExp` `/\d+\s+\w+/g` to match one or more digit characters followed by one or more space characters followed by one or more word characters
```js
var str = "3 rolls 7 buns 9 bars 7 cooks";
var res = str.match(/\d+\s+\w+/g);
console.log(res);
``` |
6,501,970 | I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels.
For example:
```
<Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" />
```
and
```
<TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" />
```
My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters?
I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters.
-------Update--------
I also tried to create a MultiValueConverter with this xaml
```
<Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png">
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" >
<Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" />
<Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" />
</MultiBinding>
</Image.Visibility>
</Image>
```
But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here.
--------Solution---------
I had to modify to this, but then it worked.
```
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest">
<Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" />
<Binding Path="MyObject.UpdatedFields" />
</MultiBinding>
</Image.Visibility>
``` | 2011/06/28 | [
"https://Stackoverflow.com/questions/6501970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818540/"
] | You could use a MultiBinding together with a short, hand made IMultiValueConverter.
**Example:**
```
<StackPanel>
<StackPanel.Resources>
<local:MultiBooleanToVisibilityConverter x:Key="Converter" />
</StackPanel.Resources>
<CheckBox x:Name="Box1" />
<CheckBox x:Name="Box2" />
<TextBlock Text="Hidden Text">
<TextBlock.Visibility>
<MultiBinding Converter="{StaticResource Converter}">
<Binding ElementName="Box1"
Path="IsChecked" />
<Binding ElementName="Box2"
Path="IsChecked" />
</MultiBinding>
</TextBlock.Visibility>
</TextBlock>
</StackPanel>
```
... and the converter ...
```
class MultiBooleanToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
bool visible = true;
foreach (object value in values)
if (value is bool)
visible = visible && (bool)value;
if (visible)
return System.Windows.Visibility.Visible;
else
return System.Windows.Visibility.Hidden;
}
public object[] ConvertBack(object value,
Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
``` | One thing that came to mind is, perhaps, instead of two different boolean fields, a single bit field created by ORing together updatedField and allowedField. Then you can have three value converters, all operating on the same field.
Or just calculate another field in your data model that does the ANDing there. That's probably more efficient (in terms of runtime). |
6,501,970 | I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels.
For example:
```
<Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" />
```
and
```
<TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" />
```
My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters?
I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters.
-------Update--------
I also tried to create a MultiValueConverter with this xaml
```
<Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png">
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" >
<Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" />
<Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" />
</MultiBinding>
</Image.Visibility>
</Image>
```
But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here.
--------Solution---------
I had to modify to this, but then it worked.
```
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest">
<Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" />
<Binding Path="MyObject.UpdatedFields" />
</MultiBinding>
</Image.Visibility>
``` | 2011/06/28 | [
"https://Stackoverflow.com/questions/6501970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818540/"
] | One thing that came to mind is, perhaps, instead of two different boolean fields, a single bit field created by ORing together updatedField and allowedField. Then you can have three value converters, all operating on the same field.
Or just calculate another field in your data model that does the ANDing there. That's probably more efficient (in terms of runtime). | You could pass an array of two objects to the converter in the `ConverterParameter` - constructing the array in XAML. |
6,501,970 | I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels.
For example:
```
<Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" />
```
and
```
<TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" />
```
My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters?
I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters.
-------Update--------
I also tried to create a MultiValueConverter with this xaml
```
<Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png">
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" >
<Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" />
<Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" />
</MultiBinding>
</Image.Visibility>
</Image>
```
But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here.
--------Solution---------
I had to modify to this, but then it worked.
```
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest">
<Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" />
<Binding Path="MyObject.UpdatedFields" />
</MultiBinding>
</Image.Visibility>
``` | 2011/06/28 | [
"https://Stackoverflow.com/questions/6501970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818540/"
] | Late to the party here but an easier solution is to just wrap the control in another control. I prefer this to having lots of Converters that do different things.
```
<Border Visibility="{Binding Value1, Converter={convertersDF:Converter_ValueToVisibility}}">
<ComboBox Visibility="{Binding Value2, Converter={convertersDF:Converter_ValueToVisibility}}"/>
</Border>
``` | One thing that came to mind is, perhaps, instead of two different boolean fields, a single bit field created by ORing together updatedField and allowedField. Then you can have three value converters, all operating on the same field.
Or just calculate another field in your data model that does the ANDing there. That's probably more efficient (in terms of runtime). |
6,501,970 | I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels.
For example:
```
<Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" />
```
and
```
<TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" />
```
My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters?
I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters.
-------Update--------
I also tried to create a MultiValueConverter with this xaml
```
<Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png">
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" >
<Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" />
<Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" />
</MultiBinding>
</Image.Visibility>
</Image>
```
But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here.
--------Solution---------
I had to modify to this, but then it worked.
```
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest">
<Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" />
<Binding Path="MyObject.UpdatedFields" />
</MultiBinding>
</Image.Visibility>
``` | 2011/06/28 | [
"https://Stackoverflow.com/questions/6501970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818540/"
] | You could use a MultiBinding together with a short, hand made IMultiValueConverter.
**Example:**
```
<StackPanel>
<StackPanel.Resources>
<local:MultiBooleanToVisibilityConverter x:Key="Converter" />
</StackPanel.Resources>
<CheckBox x:Name="Box1" />
<CheckBox x:Name="Box2" />
<TextBlock Text="Hidden Text">
<TextBlock.Visibility>
<MultiBinding Converter="{StaticResource Converter}">
<Binding ElementName="Box1"
Path="IsChecked" />
<Binding ElementName="Box2"
Path="IsChecked" />
</MultiBinding>
</TextBlock.Visibility>
</TextBlock>
</StackPanel>
```
... and the converter ...
```
class MultiBooleanToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
bool visible = true;
foreach (object value in values)
if (value is bool)
visible = visible && (bool)value;
if (visible)
return System.Windows.Visibility.Visible;
else
return System.Windows.Visibility.Hidden;
}
public object[] ConvertBack(object value,
Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
``` | You could pass an array of two objects to the converter in the `ConverterParameter` - constructing the array in XAML. |
6,501,970 | I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels.
For example:
```
<Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" />
```
and
```
<TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" />
```
My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters?
I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters.
-------Update--------
I also tried to create a MultiValueConverter with this xaml
```
<Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png">
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" >
<Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" />
<Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" />
</MultiBinding>
</Image.Visibility>
</Image>
```
But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here.
--------Solution---------
I had to modify to this, but then it worked.
```
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest">
<Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" />
<Binding Path="MyObject.UpdatedFields" />
</MultiBinding>
</Image.Visibility>
``` | 2011/06/28 | [
"https://Stackoverflow.com/questions/6501970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818540/"
] | You could use a MultiBinding together with a short, hand made IMultiValueConverter.
**Example:**
```
<StackPanel>
<StackPanel.Resources>
<local:MultiBooleanToVisibilityConverter x:Key="Converter" />
</StackPanel.Resources>
<CheckBox x:Name="Box1" />
<CheckBox x:Name="Box2" />
<TextBlock Text="Hidden Text">
<TextBlock.Visibility>
<MultiBinding Converter="{StaticResource Converter}">
<Binding ElementName="Box1"
Path="IsChecked" />
<Binding ElementName="Box2"
Path="IsChecked" />
</MultiBinding>
</TextBlock.Visibility>
</TextBlock>
</StackPanel>
```
... and the converter ...
```
class MultiBooleanToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
bool visible = true;
foreach (object value in values)
if (value is bool)
visible = visible && (bool)value;
if (visible)
return System.Windows.Visibility.Visible;
else
return System.Windows.Visibility.Hidden;
}
public object[] ConvertBack(object value,
Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
``` | Late to the party here but an easier solution is to just wrap the control in another control. I prefer this to having lots of Converters that do different things.
```
<Border Visibility="{Binding Value1, Converter={convertersDF:Converter_ValueToVisibility}}">
<ComboBox Visibility="{Binding Value2, Converter={convertersDF:Converter_ValueToVisibility}}"/>
</Border>
``` |
6,501,970 | I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels.
For example:
```
<Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" />
```
and
```
<TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" />
```
My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters?
I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters.
-------Update--------
I also tried to create a MultiValueConverter with this xaml
```
<Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png">
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" >
<Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" />
<Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" />
</MultiBinding>
</Image.Visibility>
</Image>
```
But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here.
--------Solution---------
I had to modify to this, but then it worked.
```
<Image.Visibility>
<MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest">
<Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" />
<Binding Path="MyObject.UpdatedFields" />
</MultiBinding>
</Image.Visibility>
``` | 2011/06/28 | [
"https://Stackoverflow.com/questions/6501970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818540/"
] | Late to the party here but an easier solution is to just wrap the control in another control. I prefer this to having lots of Converters that do different things.
```
<Border Visibility="{Binding Value1, Converter={convertersDF:Converter_ValueToVisibility}}">
<ComboBox Visibility="{Binding Value2, Converter={convertersDF:Converter_ValueToVisibility}}"/>
</Border>
``` | You could pass an array of two objects to the converter in the `ConverterParameter` - constructing the array in XAML. |
8,138,539 | Apologies for if the question is obvious but I can't figure out why it is suddenly not working. I have a jquery datepicker that has been working fine as long as I can remember, but all of a sudden, when I try to submit the form that the datepicker is on the datepicker reappears as though the date I am submitting is invalid. I have already set my date to uk style using the following line of code:
```
<script type="text/javascript">
$(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd/mm/yy", minDate: 0 });
});
</script>
```
And I setup the datepicker in my view like this:
```
@Html.TextBox("DateDue", "", new { @class = "date" })
```
I think that something is requiring the datestring selected to be in US format (as it will submit a valid us date (mm/dd/yyyy) but not the UK format, even though it has been set in the javascript.
Am I missing something obvious? Could anyone tell me what I'm doing wrong here?
Am not sure if it is necessary but the form that the datepicker is on is created like this:
```
@using (
Html.BeginForm(
Html.BeginForm(
"Create",
"Task",
FormMethod.Post,
new { id = "taskCreateForm" }
)
)
)
```
PS. The datestring actually works and posts without a problem in Firefox but not in Chrome
Any help appreciated
EDIT:
The problem goes away when I disable the unobtrusive js validation:
```
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
```
I had a feeling it was something to do with this and tried remoing the [Required] and [DataType(DataType.Date)] from the model annotation but this didn't do the trick.
Not sure how to leave the unobtrusive js in as well as have the uk date string working ok, but am more and more turning to write my own javascript validation for forms than to even bother with the built in stuff, which never seems to work for anything more complicated than a 'required' validation check.. | 2011/11/15 | [
"https://Stackoverflow.com/questions/8138539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896631/"
] | You can use the dateFormat, so in your javascript file (after the page is loaded etc.) you can place:
```
$('.datepicker').datepicker({dateFormat:'yy-mm-dd'});
``` | Try using altFormat instead!
```
altFormat: "dd/mm/yy",
```
That works for me : )
EDIT: Try this on JSFiddle <http://jsfiddle.net/adover/BRfcK/> |
8,138,539 | Apologies for if the question is obvious but I can't figure out why it is suddenly not working. I have a jquery datepicker that has been working fine as long as I can remember, but all of a sudden, when I try to submit the form that the datepicker is on the datepicker reappears as though the date I am submitting is invalid. I have already set my date to uk style using the following line of code:
```
<script type="text/javascript">
$(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd/mm/yy", minDate: 0 });
});
</script>
```
And I setup the datepicker in my view like this:
```
@Html.TextBox("DateDue", "", new { @class = "date" })
```
I think that something is requiring the datestring selected to be in US format (as it will submit a valid us date (mm/dd/yyyy) but not the UK format, even though it has been set in the javascript.
Am I missing something obvious? Could anyone tell me what I'm doing wrong here?
Am not sure if it is necessary but the form that the datepicker is on is created like this:
```
@using (
Html.BeginForm(
Html.BeginForm(
"Create",
"Task",
FormMethod.Post,
new { id = "taskCreateForm" }
)
)
)
```
PS. The datestring actually works and posts without a problem in Firefox but not in Chrome
Any help appreciated
EDIT:
The problem goes away when I disable the unobtrusive js validation:
```
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
```
I had a feeling it was something to do with this and tried remoing the [Required] and [DataType(DataType.Date)] from the model annotation but this didn't do the trick.
Not sure how to leave the unobtrusive js in as well as have the uk date string working ok, but am more and more turning to write my own javascript validation for forms than to even bother with the built in stuff, which never seems to work for anything more complicated than a 'required' validation check.. | 2011/11/15 | [
"https://Stackoverflow.com/questions/8138539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896631/"
] | a google search gave a lot of results relating to localizing/globalizing asp.net mvc 3 validation.
this article in particular might be on to something:
<http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx>
scroll down to: "Globalized jQuery Unobtrusive Validation"
the answer to this question might help as well:
[Localizing jquery validation with asp.net mvc 3](https://stackoverflow.com/questions/7438754/localizing-jquery-validation-with-asp-net-mvc-3)
jQuery allows you to override the different validation functions like so:
```
$.validator.methods.number = function (value, element) {
return !isNaN($.parseFloat(value));
}
```
you could do something like this for the date validator, and run it against a regEx for a valid UK date. | Try using altFormat instead!
```
altFormat: "dd/mm/yy",
```
That works for me : )
EDIT: Try this on JSFiddle <http://jsfiddle.net/adover/BRfcK/> |
8,138,539 | Apologies for if the question is obvious but I can't figure out why it is suddenly not working. I have a jquery datepicker that has been working fine as long as I can remember, but all of a sudden, when I try to submit the form that the datepicker is on the datepicker reappears as though the date I am submitting is invalid. I have already set my date to uk style using the following line of code:
```
<script type="text/javascript">
$(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd/mm/yy", minDate: 0 });
});
</script>
```
And I setup the datepicker in my view like this:
```
@Html.TextBox("DateDue", "", new { @class = "date" })
```
I think that something is requiring the datestring selected to be in US format (as it will submit a valid us date (mm/dd/yyyy) but not the UK format, even though it has been set in the javascript.
Am I missing something obvious? Could anyone tell me what I'm doing wrong here?
Am not sure if it is necessary but the form that the datepicker is on is created like this:
```
@using (
Html.BeginForm(
Html.BeginForm(
"Create",
"Task",
FormMethod.Post,
new { id = "taskCreateForm" }
)
)
)
```
PS. The datestring actually works and posts without a problem in Firefox but not in Chrome
Any help appreciated
EDIT:
The problem goes away when I disable the unobtrusive js validation:
```
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
```
I had a feeling it was something to do with this and tried remoing the [Required] and [DataType(DataType.Date)] from the model annotation but this didn't do the trick.
Not sure how to leave the unobtrusive js in as well as have the uk date string working ok, but am more and more turning to write my own javascript validation for forms than to even bother with the built in stuff, which never seems to work for anything more complicated than a 'required' validation check.. | 2011/11/15 | [
"https://Stackoverflow.com/questions/8138539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896631/"
] | a google search gave a lot of results relating to localizing/globalizing asp.net mvc 3 validation.
this article in particular might be on to something:
<http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx>
scroll down to: "Globalized jQuery Unobtrusive Validation"
the answer to this question might help as well:
[Localizing jquery validation with asp.net mvc 3](https://stackoverflow.com/questions/7438754/localizing-jquery-validation-with-asp-net-mvc-3)
jQuery allows you to override the different validation functions like so:
```
$.validator.methods.number = function (value, element) {
return !isNaN($.parseFloat(value));
}
```
you could do something like this for the date validator, and run it against a regEx for a valid UK date. | You can use the dateFormat, so in your javascript file (after the page is loaded etc.) you can place:
```
$('.datepicker').datepicker({dateFormat:'yy-mm-dd'});
``` |
26,425,032 | I want to have a `DropdownMenu` from which i can choose how i want to sort my `ListView`.
This is my current code for it :
```
<asp:DropDownList ID="DropDownSelect" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="GetProducts">
<asp:ListItem Selected="True" Value="DesDate"> Descending Date </asp:ListItem>
<asp:ListItem Value="AsDate"> Ascending Date </asp:ListItem>
<asp:ListItem Value="AsAlp"> Ascending Alphabetical </asp:ListItem>
<asp:ListItem Value="DesAlp"> Decentind Alphabetical </asp:ListItem>
</asp:DropDownList>
```
And I have this `ListView` to display my data:
```
<asp:ListView ID="productList" runat="server"
DataKeyNames="NewsID" GroupItemCount="1"
ItemType="SiteStiri.Models.News" SelectMethod="GetProducts">
<EmptyDataTemplate>
<table>
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td/>
</EmptyItemTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td runat="server">
<table>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>"
width="100" height="75" style="border: solid" /></a>
</td>
</tr>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<p style="color: black;">
<%#:Item.NewsTitle%>
</p>
</a>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</p>
</td>
</ItemTemplate>
<LayoutTemplate>
<table style="width:100%;">
<tbody>
<tr>
<td>
<table id="groupPlaceholderContainer" runat="server"
style="width:100%">
<tr id="groupPlaceholder"></tr>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr></tr>
</tbody>
</table>
</LayoutTemplate>
</asp:ListView>
```
The thing that i have no idea how to do is:
After selecting a sorting rule from the dropdown menu, i can't figure out how to write(or where to write) the method that would update my ListView as it should. My attemp is :
```
public IQueryable<News> GetProducts()
{
var _db = new SiteStiri.Models.NewsContext();
IQueryable<News> query = _db.News;
if (("DesDate").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderByDescending(u => u.ReleaseDate);
}
if (("AsDate").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderBy(u => u.ReleaseDate);
}
if (("AsAlp").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderBy(u => u.NewsTitle);
}
if (("DesApl").Equals(DropDownSelect.SelectedItem.Value))
{
query.OrderByDescending(u => u.NewsTitle);
}
return query;
}
```
which gives me a bunch of errors and it doesn't even work .... a little bit of help please? I am new to this (2 days). | 2014/10/17 | [
"https://Stackoverflow.com/questions/26425032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948157/"
] | Let's fix your code step by step.
1. Event handlers need to have a certain signature. In case of every ASP.NET control I can remember of, they need to receive two parameters, event arguments and event source object, and return void. Also note that just calling `GetProduct` is not going to update `ListView`, we need to trigger databinding for the control itself. We'll get to that later. For now let's introduce a proper handler:
```
public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e)
```
Don't forget to update markup as well:
```
OnSelectedIndexChanged="DropDownSelect_SelectedIndexChanged"
```
2. The conditions on how you show data in the `ListView` have changed. That means that you need to rebind it with calling `DataBind`, which should call `GetProducts` (as a one specified in `SelectMethod`):
```
public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e)
{
productList.DataBind();
}
```
3. Finally in `GetProducts` note that LINQ calls do not update the current object, but rather they produce new one every time. So you should have something like this:
```
if ("DesDate".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderByDescending(u => u.ReleaseDate);
}
``` | I am guessing you want the data and not the query right? That code would look like this, all you have to do is parse the selected value and pass it into the method. If the ListView is bound to the data (and it should be) you're all set. This example shows the separation of concerns, whereby the view is just a framework for HOW to show the data, and the code behind is a framework for WHAT data is supplied based on triggers from the view. The trigger in this case is the "filter" parameter.
```
List<News> query = _db.News.ToList();
public List<News> GetProduct(string filter) {
if (filter == "DesDate") return query.OrderByDescending(u => ReleaseDate).ToList();
}
```
One last note: IQueryable is a class that lets you pass queries around, you can alter the query itself from method to method. But this class does not produce results until it is told to do so by using any of the To methods like ToList(), ToArray(), ToLookup() and or any attempt to iterate over it such as:
```
Foreach(var thing in MyQuerable){ //results are here }
``` |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | I am not familiar with Richter's material, but I think the philosophy/justification is that in the vast majority of cases there is really nothing that the program can do to recover from an unhandled and unexpected exception.
Letting the program die in front of a user, however, is not a very good idea - it leaves a very bad impression. I prefer to log unhandled exceptions to a database, notify the developers, and track them to make sure that they get fixed.
Then again, I sell a product for exactly that purpose, so I am a bit biased in this area! | You can always setup a custom error handler and ignore catching exceptions that you aren't prepared to handle. Trying to recover from unknowns may have negative consequences too if the right conditions are met. But then again, that really does depend on what the exception is and how you're handling them.
On the other hand - I think people get to overwhelmed with the whole "exceptions are evil" mentality. They are a tool, and if used appropriately, can have astonishing perks. However, many people misuse them by wrapping root with catch(Exception).. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | [Karl Seguin](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) says the following about exception handling:
1. Only handle exceptions that you can actually do something about
2. You can't do anything about the vast majority of exceptions
Good intro to the subject. | The problem with having try catch around everything is that you often end up 'handling' things that you don't know how to recover from. The user gets a false impression that things are going fine, but internally you turn to swiss cheese and eventually break in really strange ways.
On the other hand, throwing the exception up to the user isn't all that helpful when they don't have some way of reporting it too you
* the new windows services provide that feature when you register with MS.
* installing drwatson can also capture the data (dump files) for your users to send to you manually.
If your providing a service library and it's run in process, if your service messes with the overall server messing up memory or settings and such, then perhaps the server will realy need to shut down when the exception is raised.
By contract APIs will tend to provide a way to say 'can I do this' and then a way to 'do it', and many APIs like the MS file open will allow you to change between raising an exception and returning an error code. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | I think it depends on what kind of app you are running and what the consequences of 'dying' are. For many client apps, dying is awesome. For servers, often not so much (and swallow-and-log is appropriate). There's no one-size-fits-all solution. | What does your customer expects?
It all comes back to that. If the customer can handle the program dying and they can restart it, so be it.
Sometimes, it is better to let a process die and create another to handle requests.
Sometimes, it is better to attempt to resolve the problem. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | [Karl Seguin](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) says the following about exception handling:
1. Only handle exceptions that you can actually do something about
2. You can't do anything about the vast majority of exceptions
Good intro to the subject. | What does your customer expects?
It all comes back to that. If the customer can handle the program dying and they can restart it, so be it.
Sometimes, it is better to let a process die and create another to handle requests.
Sometimes, it is better to attempt to resolve the problem. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | [Karl Seguin](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) says the following about exception handling:
1. Only handle exceptions that you can actually do something about
2. You can't do anything about the vast majority of exceptions
Good intro to the subject. | I am not familiar with Richter's material, but I think the philosophy/justification is that in the vast majority of cases there is really nothing that the program can do to recover from an unhandled and unexpected exception.
Letting the program die in front of a user, however, is not a very good idea - it leaves a very bad impression. I prefer to log unhandled exceptions to a database, notify the developers, and track them to make sure that they get fixed.
Then again, I sell a product for exactly that purpose, so I am a bit biased in this area! |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | I think it depends on what kind of app you are running and what the consequences of 'dying' are. For many client apps, dying is awesome. For servers, often not so much (and swallow-and-log is appropriate). There's no one-size-fits-all solution. | If you can't handle the problem adequately--and if it's anything other than rejecting bad input in some form (this includes something you tried to read from the disk or web) you probably can't--then you should die. Unless you're 100% certain you can continue safely, don't.
However, I wouldn't simply let an exception go. Catch it and gather as much information as you can. If your program manipulates a document of some kind save it *UNDER A NEW NAME*--it might be corrupt, you don't want to overwrite the original. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | Also known as Offensive Programming.
You should check out, "[Offensive Programming: Crash Early, Crash Often](http://blogs.23.nu/c0re/offensive-programming-crash-early-crash-often/)".
Which is a very different ideology from the norm of [Defensive Programming](http://en.wikipedia.org/wiki/Defensive_programming):
>
> [Defensive Programming] is intended to
> ensure the continuing function of a
> piece of software in spite of
> unforeseeable usage of said software.
>
>
>
I personally like the "Crash Early, Crash Often" philosophy.
I've seen far too many:
```
try
{
// ... Huge block of code goes here
}
catch(Exception ex)
{
// Do nothing...
}
```
Which is far worse than crashing hard. If exceptions are handled properly then a little defensive programming is fine. | I say you should always have a root exception catcher... Especially if you can fit some kind of information in the exception saying what went wrong, a code or something and print it out to the user. Then, the user can always ask you(or support or whatever) what went wrong and provide some info.. rather than "it crashed with a protection fault" |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | **Sounds like Guruspeak**
This sounds like another one of those general guidelines preached by *gurus* that is not a bad piece of advice in itself. However, this guideline could easily be applied to places where it does not belong. I think the key phrase to remember that you used above was "one strategy of coding" because this stategy is very useful in certain domains, yet can be quite harmful in others.
Dying *is* awesome - if you have a lot of tightly coupled components whose state depends on each other, then an exception could easily be a catastrophic event. However, one of your goals should be to code in such a way that a single failure does not have to bring down the entire system (notice goal).
What would you think of the following applications dying on a run-of-the-mill exception:
* Medical Devices
* Power Plants
* Intrusion Detection Systems
For exceptions that you are catching in try / catch - you really should be expecting them and handling them. For all other cases, it is good to fail fast to a predicted run-level. So, if you are at a network or web handler, why not just have the current operation die? Do you really need the whole app to go down?
This becomes increasingly important if you are developing an app that is mission critical and has a public interface. If there are exceptions available that can bring the app down, then that becomes a vector of attack for black-hat hackers intent on causing a denial of service attack.
The edge cases of abusing this strategy are a little too big to give it much praise. A much better approach, is to solve the problem of your domain. Understand what this stategy is getting at and apply the appropriate parts to your problem.
Caveats: I work on server-side systems where uptime and security is critical.
EDIT: I guess I got confused by what was meant by "process die" - was this a reference to the entire app or just the running thread, etc? | Awesome answers here already, especially by Simucal. I just want to add a point:
Offensive programming is excellent for debugging. In my experience, "fail early, fail often" can be thought of as like setting traps for bugs in your code. When something goes awry--whether it's a memory leak, memory stomp, unexpected NULL, etc.--it's generally much easier to see the problem if the program fails immediately (with associated debugging data such as a callstack).
Defensive programming is excellent for production environments. Once your application has shipped, you may not want your end-users to ever see a nice little dialog saying "unhandled exception at foo()." That might be great if your app is in beta and you're still gathering debug info, but if you're shipping a stable app you might simply want to not bother the user with cryptic output in the rare case that something does fail.
Sometimes you can have it both ways. I've often wrote C code along the following lines:
```
void foo(char* data) {
ASSERT(data);
if (!data) { return; }
// ... work with data
}
```
If this code is compiled in a test environment, the assert statement traps the error condition. If it is compiled in a production environment, the assert is removed by the pre-processor and foo() fails silently.
Exceptions are more expressive and flexible than asserts, and there are various ways to manage them such that an app fails early in a test environment and chugs along while logging errors in a production environment. Depending on the type of project, this sort of design may make sense for you. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | This is very microsoft.
MS want you to throw all unhandled exceptions to WER. (Windows error reporting, its the dialog you get to send your error to microsoft when an app crashes)
That way you get usage metrics and can focus on the key unhandled exceptions which are causing customers grief. I believe the idea is it forces you to think about where the exceptions will come from.
But I wholeheartedly agree with you. Even if you rethrow after, you would always catch an unhandled at the root, log what happened. The only problem with this is if your unhandled ex is an out of memory in which case your call to log could fail as the JIT can't allocate any more memory etc. I think C++ programs deal with this by taking a bubble of memory, releasing it on an unhandled exception and then running a very tight log routine to try and fail gracefully. | Awesome answers here already, especially by Simucal. I just want to add a point:
Offensive programming is excellent for debugging. In my experience, "fail early, fail often" can be thought of as like setting traps for bugs in your code. When something goes awry--whether it's a memory leak, memory stomp, unexpected NULL, etc.--it's generally much easier to see the problem if the program fails immediately (with associated debugging data such as a callstack).
Defensive programming is excellent for production environments. Once your application has shipped, you may not want your end-users to ever see a nice little dialog saying "unhandled exception at foo()." That might be great if your app is in beta and you're still gathering debug info, but if you're shipping a stable app you might simply want to not bother the user with cryptic output in the rare case that something does fail.
Sometimes you can have it both ways. I've often wrote C code along the following lines:
```
void foo(char* data) {
ASSERT(data);
if (!data) { return; }
// ... work with data
}
```
If this code is compiled in a test environment, the assert statement traps the error condition. If it is compiled in a production environment, the assert is removed by the pre-processor and foo() fails silently.
Exceptions are more expressive and flexible than asserts, and there are various ways to manage them such that an app fails early in a test environment and chugs along while logging errors in a production environment. Depending on the type of project, this sort of design may make sense for you. |
576,532 | Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die.
I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service.
What do you think? | 2009/02/23 | [
"https://Stackoverflow.com/questions/576532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] | I think it depends on what kind of app you are running and what the consequences of 'dying' are. For many client apps, dying is awesome. For servers, often not so much (and swallow-and-log is appropriate). There's no one-size-fits-all solution. | Since you don't know what every subclass of Exception IS, you simply CANNOT know it's OK to catch them. Therefore, you should mind your own business: catch exceptions you know and care about, which will mainly be the ones you've explicitly created for your own program, or the ones created for errors from the library calls you're using. In particular, catching the Exception class is just lazy, bad programming --- essentially, you're saying "I don't care what the problem is, and don't tell me; just do this." Take a look at how java programs handle exceptions, as the exception handling practices there are usually pretty good. |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | If you already have `<?php comments_template(); ?>` in place (which you do) then it could be a file permission issue.
Also, it is probably pulling from `classic` or `default` if it can't read your `comments.php` file in the current directory of your theme.
Make sure your `comments.php` has the same permissions as the rest of your theme files. | You need to include the following in your template's single.php to include comments:
```
<?php comments_template(); ?>
```
Use the default template that comes with WordPress as a reference.
Doug Neiner added this as a comment first so if he posts it as an answer please choose his. |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | I got it working now, I had to change
`<?php comments_template(); ?>`
into this
```
<?php comments_template('', true); ?>
```
instead, weird but it fixed my problem | You need to include the following in your template's single.php to include comments:
```
<?php comments_template(); ?>
```
Use the default template that comes with WordPress as a reference.
Doug Neiner added this as a comment first so if he posts it as an answer please choose his. |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | I got it working now, I had to change
`<?php comments_template(); ?>`
into this
```
<?php comments_template('', true); ?>
```
instead, weird but it fixed my problem | If you already have `<?php comments_template(); ?>` in place (which you do) then it could be a file permission issue.
Also, it is probably pulling from `classic` or `default` if it can't read your `comments.php` file in the current directory of your theme.
Make sure your `comments.php` has the same permissions as the rest of your theme files. |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | If you already have `<?php comments_template(); ?>` in place (which you do) then it could be a file permission issue.
Also, it is probably pulling from `classic` or `default` if it can't read your `comments.php` file in the current directory of your theme.
Make sure your `comments.php` has the same permissions as the rest of your theme files. | I think I found solution.
Problem that my theme not using single.php while it loads. So adding **comments\_template('', true);** not helping.
So I added it to my index.php file and it appears now like it should.
Hope this will help |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | If you already have `<?php comments_template(); ?>` in place (which you do) then it could be a file permission issue.
Also, it is probably pulling from `classic` or `default` if it can't read your `comments.php` file in the current directory of your theme.
Make sure your `comments.php` has the same permissions as the rest of your theme files. | This is typically done with the comments\_template function:
```
<?php comments_template($file, $separate_comments); ?>
```
**$file** is the file name you want to load (for example, "/comments.php"). It's an optional parameter.
**$separate\_comments** is used to set whether to separate the comments by comment type. It's boolean, and the default is FALSE. It's an optional parameter (if you omit it, it's set to FALSE).
**NOTE**: This only works for single posts and pages. To make it work everywhere, set **$withcomments** to "1".
If you want to create your own custom comment template (like for a custom theme), call it like this, for example ("short-comments" is just an example name):
```
<?php comments_template( '/short-comments.php' ); ?>
```
If you've done all this and WP still isn't using the correct comments.php, check file permissions. **Also--hacking comments is a common problem, so someone may have hacked your site and caused a problem with the file.** |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | I got it working now, I had to change
`<?php comments_template(); ?>`
into this
```
<?php comments_template('', true); ?>
```
instead, weird but it fixed my problem | I think I found solution.
Problem that my theme not using single.php while it loads. So adding **comments\_template('', true);** not helping.
So I added it to my index.php file and it appears now like it should.
Hope this will help |
2,129,957 | Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder? | 2010/01/25 | [
"https://Stackoverflow.com/questions/2129957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] | I got it working now, I had to change
`<?php comments_template(); ?>`
into this
```
<?php comments_template('', true); ?>
```
instead, weird but it fixed my problem | This is typically done with the comments\_template function:
```
<?php comments_template($file, $separate_comments); ?>
```
**$file** is the file name you want to load (for example, "/comments.php"). It's an optional parameter.
**$separate\_comments** is used to set whether to separate the comments by comment type. It's boolean, and the default is FALSE. It's an optional parameter (if you omit it, it's set to FALSE).
**NOTE**: This only works for single posts and pages. To make it work everywhere, set **$withcomments** to "1".
If you want to create your own custom comment template (like for a custom theme), call it like this, for example ("short-comments" is just an example name):
```
<?php comments_template( '/short-comments.php' ); ?>
```
If you've done all this and WP still isn't using the correct comments.php, check file permissions. **Also--hacking comments is a common problem, so someone may have hacked your site and caused a problem with the file.** |
151,651 | I'm starting to read chapter 11 of Stan Wagon's third edition of Mathematica in Action, a section written by Mark McClure (and there is a package for the notebook).
I start with:
```
f[z_] := z^2;
Subscript[z, 0] = 0.9 + 0.15 I;
orbit = NestList[f, Subscript[z, 0], 10]
```
Then:
```
Attributes[ComplexTicks] = Listable;
ComplexTicks[s_?NumericQ] := {s, s I} /.
Thread[{-1. I, 0. I, 1. I} -> {-I, 0, I}]
```
What this does, I believe, is create a list of tick marks drawn with the specified labels. For example:
```
ComplexTicks[Range[0, .4, 0.1]]
```
Produces:
{{0., 0}, {0.1, 0. + 0.1 I}, {0.2, 0. + 0.2 I}, {0.3,
0. + 0.3 I}, {0.4, 0. + 0.4 I}}
So, for example, at 0.0 we'll mark with 0; at 0.1 we'll mark with 0.+0.1I; etc. Now, his next code is:
```
ListPlot[{Re[#], Im[#]} & /@ orbit, Frame -> True,
FrameTicks -> {Automatic, ComplexTicks[Range[0, 0.4, 0.1]], None,
None}]
```
Which is supposed to produce this image:
[![enter image description here](https://i.stack.imgur.com/RIozS.png)](https://i.stack.imgur.com/RIozS.png)
But that was in an older version of Mathematica. In Mathematica 11.1.1, it produces this image.
[![enter image description here](https://i.stack.imgur.com/I9nEX.png)](https://i.stack.imgur.com/I9nEX.png)
The current way to set FrameTicks in Mathematica is FrameTicks->{{left, right},{bottom, top}}. So I adjusted the code as follows:
```
ListPlot[{Re[#], Im[#]} & /@ orbit, Frame -> True,
FrameTicks -> {{ComplexTicks[Range[0, 0.4, 0.1]], None}, {Automatic,
None}}]
```
But that gives this image:
[![enter image description here](https://i.stack.imgur.com/pzCeH.png)](https://i.stack.imgur.com/pzCeH.png)
Any way to turn off the real zeros in each complex tick number?
**Update:** Thanks to the help from my colleagues, I gave this a try.
```
Attributes[ComplexTicks] = Listable;
ComplexTicks[s_?NumericQ] := {s, s "\[ImaginaryI]"} /.
Thread[{-1. "\[ImaginaryI]", 0. "\[ImaginaryI]",
1. "\[ImaginaryI]"} -> {-I, 0, I}]
f[z_] := z^2;
z0 = 0.9 + 0.15 I;
orbit = NestList[f, z0, 10];
ListPlot[{Re[#], Im[#]} & /@ orbit, Frame -> True,
FrameTicks -> {{ComplexTicks[Range[0, 0.4, 0.1]], None}, {Automatic,
None}}]
```
The resulting image is next:
[![enter image description here](https://i.stack.imgur.com/cfeQb.png)](https://i.stack.imgur.com/cfeQb.png)
Any thoughts? | 2017/07/17 | [
"https://mathematica.stackexchange.com/questions/151651",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5183/"
] | At some point, Mathematica started showing the real part in inexact complex numbers. To workaround this, I would change `ComplexTicks` to something like:
```
ComplexTicks[s_?NumericQ] := {s, s Defer[I]}
```
or
```
ComplexTicks[s_?NumericQ] := {s, s HoldForm[I]}
``` | If it's just a visualization requirement, perhaps you could use:
```
ComplexTicks[s_?NumericQ] := {s, ToString[s] <> ToString[" \[ImaginaryI]"]}
```
![Mathematica graphics](https://i.stack.imgur.com/Eu9Ap.png) |