qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | You have two issues here:
#1, there are several different ways you can compute the MD5 hash:
* Do as you do and load into PHP as a string and use PHP's `md5()`
* Use PHP's `md5_file()`
* As of PHP 5.1+ you can use PHP's streams API with either of `md5` or `md5_file` to avoid loading entirely into memory
* Use `exec()` to call the system's `md5sum` command
* Use MySQL's `MD5()` function to compute the hash
Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are [some benchmarks](http://www.php.net/manual/en/function.md5-file.php#81751) showing system md5 via `exec` to be a lot faster than PHP's `md5_file` as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned.
#2, `mysql_real_escape_string` performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP.
It's going to be more efficient to use [PHP5 prepared statements](http://devzone.zend.com/node/view/id/686#Heading11) and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The [PHP docs for `mysqli_stmt::send_long_data`](http://www.php.net/manual/en/mysqli-stmt.send-long-data.php) have a great simple example of this that INSERTs a file into a blob column just like you are.
By doing that, and by using either the streams API, `md5_file` or `exec` with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want! | If you are using PDO, and prepared statments you can use the PDO::PARAM\_LOB type. See example #2 on the LOB page showing how to insert an image to a database using the file pointer.
<http://us2.php.net/manual/en/pdo.lobs.php> |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | You have two issues here:
#1, there are several different ways you can compute the MD5 hash:
* Do as you do and load into PHP as a string and use PHP's `md5()`
* Use PHP's `md5_file()`
* As of PHP 5.1+ you can use PHP's streams API with either of `md5` or `md5_file` to avoid loading entirely into memory
* Use `exec()` to call the system's `md5sum` command
* Use MySQL's `MD5()` function to compute the hash
Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are [some benchmarks](http://www.php.net/manual/en/function.md5-file.php#81751) showing system md5 via `exec` to be a lot faster than PHP's `md5_file` as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned.
#2, `mysql_real_escape_string` performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP.
It's going to be more efficient to use [PHP5 prepared statements](http://devzone.zend.com/node/view/id/686#Heading11) and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The [PHP docs for `mysqli_stmt::send_long_data`](http://www.php.net/manual/en/mysqli-stmt.send-long-data.php) have a great simple example of this that INSERTs a file into a blob column just like you are.
By doing that, and by using either the streams API, `md5_file` or `exec` with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want! | Would it make any difference if you didn't put the query into another variable, but instead passed it directly into the MySQL command. I've never tried this, but it may make a difference as the whole string isn't stored in another variable. |
972,554 | For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
```
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
```
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
<http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx> | 2009/06/09 | [
"https://Stackoverflow.com/questions/972554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50395/"
] | If it's already done this way and it's working I don't see why spending time implementing this in jQuery.
Unless if you want to learn/practice jQuery. | I think a better place for this would be <http://refactormycode.com/>
Stackoverflow is more geared towards direct Question and Answers, and less for discussions. |
972,554 | For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
```
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
```
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
<http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx> | 2009/06/09 | [
"https://Stackoverflow.com/questions/972554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50395/"
] | What exactly do you mean by "convert to jQuery code"? jQuery has really pretty much nothing to do with the code you posted. It is not a different language, it has no magic that will make the Javascript any different. jQuery is a library intended to make it easy to manipulate DOM elements and perform common Javascript tasks cross-browser. It *is* Javascript, and there's nowhere really where it would fit to have a function such as this one.
If what you really mean is "make a plugin out of this", then it's a 5 liner:
```
$.fn.humanizeNumber = function() {
return this.each(function() {
$(this).html(CALLTHEFUNCTION($(this).html()));
}
});
```
Where `CALLTHEFUNCTION` is whatever is the main function of the code you posted above (I don't really care to go through it and find what it is). That plugin would then let you do this:
```
$('#myelement').humanizeNumber();
```
To convert the value in `#myelement` from "123" to whatever your function returns. | I think a better place for this would be <http://refactormycode.com/>
Stackoverflow is more geared towards direct Question and Answers, and less for discussions. |
972,554 | For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
```
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
```
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
<http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx> | 2009/06/09 | [
"https://Stackoverflow.com/questions/972554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50395/"
] | If your code works, then **no**, don't refactor. Why? Because we don't have much time here, on Earth. | I think a better place for this would be <http://refactormycode.com/>
Stackoverflow is more geared towards direct Question and Answers, and less for discussions. |
972,554 | For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
```
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
```
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
<http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx> | 2009/06/09 | [
"https://Stackoverflow.com/questions/972554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50395/"
] | What exactly do you mean by "convert to jQuery code"? jQuery has really pretty much nothing to do with the code you posted. It is not a different language, it has no magic that will make the Javascript any different. jQuery is a library intended to make it easy to manipulate DOM elements and perform common Javascript tasks cross-browser. It *is* Javascript, and there's nowhere really where it would fit to have a function such as this one.
If what you really mean is "make a plugin out of this", then it's a 5 liner:
```
$.fn.humanizeNumber = function() {
return this.each(function() {
$(this).html(CALLTHEFUNCTION($(this).html()));
}
});
```
Where `CALLTHEFUNCTION` is whatever is the main function of the code you posted above (I don't really care to go through it and find what it is). That plugin would then let you do this:
```
$('#myelement').humanizeNumber();
```
To convert the value in `#myelement` from "123" to whatever your function returns. | If it's already done this way and it's working I don't see why spending time implementing this in jQuery.
Unless if you want to learn/practice jQuery. |
972,554 | For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
```
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
```
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
<http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx> | 2009/06/09 | [
"https://Stackoverflow.com/questions/972554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50395/"
] | What exactly do you mean by "convert to jQuery code"? jQuery has really pretty much nothing to do with the code you posted. It is not a different language, it has no magic that will make the Javascript any different. jQuery is a library intended to make it easy to manipulate DOM elements and perform common Javascript tasks cross-browser. It *is* Javascript, and there's nowhere really where it would fit to have a function such as this one.
If what you really mean is "make a plugin out of this", then it's a 5 liner:
```
$.fn.humanizeNumber = function() {
return this.each(function() {
$(this).html(CALLTHEFUNCTION($(this).html()));
}
});
```
Where `CALLTHEFUNCTION` is whatever is the main function of the code you posted above (I don't really care to go through it and find what it is). That plugin would then let you do this:
```
$('#myelement').humanizeNumber();
```
To convert the value in `#myelement` from "123" to whatever your function returns. | If your code works, then **no**, don't refactor. Why? Because we don't have much time here, on Earth. |
12,326,554 | I have some code that I put in a destructor to ensure it is run both on normal exit and exception stack unwinding:
```
struct withProtectedClose {
~withProtectedClose() {
// Do some cleanup here...
}
};
void test() {
withProtectedClose close;
// Do some work before closing
}
```
Yet the g++ compiler (g++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-11)) is complaining:
```
test.cpp: In function `void test()':
test.cpp:28: warning: unused variable 'close'
```
I can silence it by referring to the variable somehow, but that muddies the code only to silence the compiler, not how I want my code influenced.
Shouldn't the fact that there is a destructor be enough to clue the compiler in that it makes no difference that there is no use of the variable after construction?
Assuming the compiler cannot be shut up while still getting notices of legitimate unused variables, is there a way to silence this one only other than by using it? | 2012/09/07 | [
"https://Stackoverflow.com/questions/12326554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115751/"
] | I'd tend to think it is a bug in the compiler. It is still present in g++ 4.7.1.
As a work around, you may try to define a constructor which does nothing. It suppresses the warning with g++ 4.7.1, I don't know with 3.4.6. | MSVC doesn't issue this warning in such a case. If your gcc version does, try suppressing it this way:
```
withProtectedClose close;
(close);
``` |
12,326,554 | I have some code that I put in a destructor to ensure it is run both on normal exit and exception stack unwinding:
```
struct withProtectedClose {
~withProtectedClose() {
// Do some cleanup here...
}
};
void test() {
withProtectedClose close;
// Do some work before closing
}
```
Yet the g++ compiler (g++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-11)) is complaining:
```
test.cpp: In function `void test()':
test.cpp:28: warning: unused variable 'close'
```
I can silence it by referring to the variable somehow, but that muddies the code only to silence the compiler, not how I want my code influenced.
Shouldn't the fact that there is a destructor be enough to clue the compiler in that it makes no difference that there is no use of the variable after construction?
Assuming the compiler cannot be shut up while still getting notices of legitimate unused variables, is there a way to silence this one only other than by using it? | 2012/09/07 | [
"https://Stackoverflow.com/questions/12326554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115751/"
] | I'd tend to think it is a bug in the compiler. It is still present in g++ 4.7.1.
As a work around, you may try to define a constructor which does nothing. It suppresses the warning with g++ 4.7.1, I don't know with 3.4.6. | Since it seems to be solely a GCC issue, you can "fix" it by declaring your struct like this:
```
struct __attribute__ ((__unused__)) withProtectedClose
```
This reliably silences the warning on my version 4.6.3 compiler (and the destructor is demonstrably run, in accordance with the standard). It will however **still** warn you about unused variables otherwise.
Most of the time, it's a mistake that you really want to know about, so turning off the warning (`-Wno-unused-variable`) alltogether is not a good alternative. If for no other reason, one will want to remove (unintentionally) unused variables because they confuse people reading the code and put needless burden on the optimizer.
If you need to be portable, use a macro to encapsulate the attribute stuff (empty macro on non-GCC).
To address the actual question "Should compilers ignore unused variables that result in constructors or destructors being run?" -- **No.**
The C++ standard states [3.7.3.3]:
>
> If a variable with automatic storage duration has initialization or a destructor
> with side effects, it shall not be eliminated even if it appears to be unused,
> except that a class object or its copy/move may be eliminated as specified in 12.8.
>
>
>
Insofar, a compiler is *not* allowed to *ignore* the variable. It is, however, allowed to warn about something that is often unintentional. |
12,326,554 | I have some code that I put in a destructor to ensure it is run both on normal exit and exception stack unwinding:
```
struct withProtectedClose {
~withProtectedClose() {
// Do some cleanup here...
}
};
void test() {
withProtectedClose close;
// Do some work before closing
}
```
Yet the g++ compiler (g++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-11)) is complaining:
```
test.cpp: In function `void test()':
test.cpp:28: warning: unused variable 'close'
```
I can silence it by referring to the variable somehow, but that muddies the code only to silence the compiler, not how I want my code influenced.
Shouldn't the fact that there is a destructor be enough to clue the compiler in that it makes no difference that there is no use of the variable after construction?
Assuming the compiler cannot be shut up while still getting notices of legitimate unused variables, is there a way to silence this one only other than by using it? | 2012/09/07 | [
"https://Stackoverflow.com/questions/12326554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115751/"
] | Since it seems to be solely a GCC issue, you can "fix" it by declaring your struct like this:
```
struct __attribute__ ((__unused__)) withProtectedClose
```
This reliably silences the warning on my version 4.6.3 compiler (and the destructor is demonstrably run, in accordance with the standard). It will however **still** warn you about unused variables otherwise.
Most of the time, it's a mistake that you really want to know about, so turning off the warning (`-Wno-unused-variable`) alltogether is not a good alternative. If for no other reason, one will want to remove (unintentionally) unused variables because they confuse people reading the code and put needless burden on the optimizer.
If you need to be portable, use a macro to encapsulate the attribute stuff (empty macro on non-GCC).
To address the actual question "Should compilers ignore unused variables that result in constructors or destructors being run?" -- **No.**
The C++ standard states [3.7.3.3]:
>
> If a variable with automatic storage duration has initialization or a destructor
> with side effects, it shall not be eliminated even if it appears to be unused,
> except that a class object or its copy/move may be eliminated as specified in 12.8.
>
>
>
Insofar, a compiler is *not* allowed to *ignore* the variable. It is, however, allowed to warn about something that is often unintentional. | MSVC doesn't issue this warning in such a case. If your gcc version does, try suppressing it this way:
```
withProtectedClose close;
(close);
``` |
118,850 | Suppose I want to copy the red channel of an image (thus creating a new channel). How do I do that with Python-Fu?
EDIT: basically, I need to create luminosity masks. So far, I tryed the following code:
```
# get active layer
layer = pdb.gimp_image_get_active_layer(image)
# copy the selected layer
layer_copy = pdb.gimp_layer_new_from_drawable(layer, image)
# insert the layer_copy on top of the layers stack
pdb.gimp_image_insert_layer(image, layer_copy, None, 0)
# desaturate the layer
pdb.gimp_drawable_desaturate(layer_copy, DESATURATE_LIGHTNESS)
# select the red channel
ch = pdb.gimp_channel_new_from_component(image, 0, "testchannel")
pdb.gimp_image_insert_channel(image, ch, 0, 1)
```
Unfortunately I got the error `TypeError: wrong parameter type` on the last command `pdb.gimp_image_insert_channel(image, ch, 0, 1)` | 2019/01/07 | [
"https://graphicdesign.stackexchange.com/questions/118850",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/131559/"
] | Your third argument should be None:
```
pdb.gimp_image_insert_channel(i, c, None,0)
```
The doc is mostly written with the script-fu point if view, where items are just integer ids, and "no item" is therefore 0. In python-fu, you pass object references, so "no item" is `None`.
You can do the same thing more simply (but with a bit less control) using:
```
image.insert_channel(channel)
```
Btw, you can also look at the [python-fu object methods](http://www.gimp.org/docs/python/index.html), using `image.active_layer` is a lot more readable than `pdb.gimp_image_get_active_layer(image)`. | The R/G/B channels you see at the top of the Channels list are somewhat virtual since they are the result of the composition of the layers.
To get a layer with only the red component you can use the channel mixer:
```
pdb.plug_in_colors_channel_mixer(img, l, False, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
```
(note that it changes the layer it is called with, so you may want to do a copy first). |
8,039,185 | Let's say I have a database with two tables `Persons` and `PhoneNumbers`, where the `PhoneNumbers` table has a foreign key to `Persons`. If I want to insert a person with a phone number in a single transaction, I can write a query like this:
```
BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
END TRANSACTION;
```
But what if I want to insert a person with multiple phone numbers? The obvious way:
```
BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
END TRANSACTION;
```
won't work, of course, because for the second phone number, `last_insert_rowid()` will return the rowid of the first phone number instead of the person.
Is there a way to do this using basic SQL (SQLite, specifically)?
**Conclusion**
Apparently, there is no direct way to do this. I've made a few benchmarks with @Michal Powaga's suggestions and a few other ideas based on temporary tables, and the fastest way to do it seems to be something like this:
```
CREATE TEMPORARY TABLE IF NOT EXISTS Insert_PhoneNumbers(PersonForeignKey INTEGER, PhoneNumber VARCHAR);
DELETE FROM Insert_PhoneNumbers;
INSERT INTO Insert_PhoneNumbers(PhoneNumber) VALUES ('Phone 1');
INSERT INTO Insert_PhoneNumbers(PhoneNumber) VALUES ('Phone 2');
INSERT INTO Persons(Name) VALUES(...);
UPDATE Insert_PhoneNumbers SET PersonForeignKey=last_insert_rowid();
INSERT INTO PhoneNumbers(PersonForeignKey, Number)
SELECT PersonForeignKey, PhoneNumber
FROM Insert_PhoneNumbers
```
creating and updating a temporary table seems to be very fast (compared to queries on the Persons or PhoneNumbers-tables) and the insert speed won't depend on the number of persons/phone numbers already in the database, so that's the solution I chose. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8039185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70915/"
] | You can store last\_insert\_rowid() after person insertion to temporary table or this might work too:
```
BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number)
VALUES(last_insert_rowid(), 'number 1');
INSERT INTO PhoneNumbers(PersonForeignKey, Number)
SELECT PersonForeignKey, 'number 2'
FROM PhoneNumbers where PhonePrimaryKey = last_insert_rowid();
INSERT INTO PhoneNumbers(PersonForeignKey, Number)
SELECT PersonForeignKey, 'number 3'
FROM PhoneNumbers where PhonePrimaryKey = last_insert_rowid();
END TRANSACTION;
``` | Something like this might work, although it is far from ideal:
```
BEGIN TRANSACTION;
INSERT INTO Persons(Name) VALUES(...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) VALUES(last_insert_rowid(), ...);
INSERT INTO PhoneNumbers(PersonForeignKey, Number) SELECT PersonForeignKey, 123 WHERE PhoneNumberRowId = last_insert_rowid()
INSERT INTO PhoneNumbers(PersonForeignKey, Number) SELECT PersonForeignKey, 456 WHERE PhoneNumberRowId = last_insert_rowid()
END TRANSACTION;
```
Not brilliant, but basically you are chaining the last row ID to get the original primary key. |
63,928,668 | I'm working on a project where i have to detect a red vehicle (please see image below).
[](https://i.stack.imgur.com/hhri1.jpg)
As i believe that this can be achieved with out using Deep learning (overkill in this case), i used histogram Back projection depending on the object color(red). The results were satisfying
[](https://i.stack.imgur.com/xakf2.jpg)
except when there are objects other than the target red-vehicle having the same color distribution as the target (see example below my T-shirt) are in the scene, the algorithm thinks it is also an object of interest and thus detect both the object of interest and the irrelevant object (my T-shirt).
[](https://i.stack.imgur.com/lXhjE.jpg)
The result are
[](https://i.stack.imgur.com/SWwgz.jpg)
In this case, it's easy to only choose the contour that belongs to the car based on ratio and area,since the contour that belongs to the T-shirt is lager and has different ratio
I applied the follwoing example code
```
contours = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
area_thresh1 = 500
area_thresh2 = 1000
aspect_thresh1 = 2
aspect_thresh2 = 4
result1 = image.copy()
result2 = image.copy()
for c in contours:
# get rotated rectangle from contour
# get its dimensions
# get angle relative to horizontal from rotated rectangle
rotrect = cv2.minAreaRect(c)
box = cv2.boxPoints(rotrect)
box = np.int0(box)
(center), (dim1,dim2), angle = rotrect
maxdim = max(dim1,dim2)
mindim = min(dim1,dim2)
area = dim1 * dim2
if area > 0:
aspect = maxdim / mindim
#print(area, aspect)
if area > area_thresh1 and area < area_thresh2 and aspect > aspect_thresh1 and aspect <
aspect_thresh2:
# draw contour on input
cv2.drawContours(result1,[c],0,(255,255,255),1)
# draw rectangle on input
cv2.drawContours(result2,[box],0,(255,255,255),1)
print(area, aspect)
```
However, as I'm working on a video, this doesn't work well in some frames since sometimes it detects shapes that fulfill the conditions like the case below
[](https://i.stack.imgur.com/0RVGa.png)
As you can see in the above binary image, an irrelevant object is detected (the below contour).
**So my question is:**
As you see the red vehicle to be detected always has the same shape (almost rectangle but for sure a convex shape). **So how can i filter only the contour that belongs to the red vehicle using a the shape property ?**(of course I mean a property other than ratio and area since some sopts of my short falls into the same area and ration boundaries of the red vehicle).
**In other words, How can i filter the target object based on the exact shape of the vehicle??**
Thanks in Advance | 2020/09/16 | [
"https://Stackoverflow.com/questions/63928668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12356895/"
] | You can get shape descriptors and use some kind of rules (or machine learning) to decide if that's the right object you're searching for :
```
import numpy as np
import argparse
import cv2
import sys
target = cv2.imread('YourPath\\target.jpg' ,
cv2.IMREAD_COLOR)
mask = cv2.imread('YourPath\\mask.jpg',cv2.IMREAD_GRAYSCALE)
SearchImage = cv2.bitwise_and(target,target,mask = mask)
cv2.imshow("Search Region" , SearchImage)
cv2.waitKey()
#convert RGBto Lab
LabImage = cv2.cvtColor(SearchImage,cv2.COLOR_BGR2LAB)
cv2.imshow("Lab(b)" , LabImage[:, :, 1])
cv2.waitKey()
ret,Binary = cv2.threshold(LabImage[:, :, 1], 0, 255, cv2.THRESH_OTSU)
cv2.imshow('win1', Binary)
cv2.waitKey(0)
#find contours
contours, hierarchy = cv2.findContours(Binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#create an empty image for contours
img_contours = np.zeros(target.shape)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
aspect_ratio = float(w) / h
area = cv2.contourArea(cnt)
x, y, w, h = cv2.boundingRect(cnt)
rect_area = w * h
extent = float(area) / rect_area
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = float(area) / hull_area
equi_diameter = np.sqrt(4 * area / np.pi)
(x, y), (MA, ma), Orientation = cv2.fitEllipse(cnt)
print(" Width = {} Height = {} area = {} aspect ration = {} extent = {}
solidity = {} equi_diameter = {} orientation = {}".format( w , h , area ,
aspect_ratio , extent , solidity , equi_diameter , Orientation))
cv2.imshow('win1', img_contours)
cv2.waitKey(0)
```
OUTPUT:
```
Width = 42
Height = 18
area = 632.5
aspect ratio = 2.3333333333333335
extent = 0.8366402116402116
solidity = 0.9412202380952381
equi_diameter = 28.37823130579125
orientation = 89.93299865722656
```
[](https://i.stack.imgur.com/rdNhB.jpg) | You can use approxPolyDp and calculate the approximate area of the shape and set a threshold for a range where it can be termed as the shape that you're looking for. |
37,243 | I'm trying to create a bilingual critical edition with Latin on the left page and English on the right. I'm trying to figure out `ledpar` and I can't get the following example to compile. It compiles just fine if I comment out the two section headings, but with the section headings LaTeX throws the error on line 19 (which calls the `\Pages` macro) that says
```
You can't use \lastbox in vertical mode.
```
Here is the code I'm using:
```
\documentclass[10pt]{article}
\usepackage{ledmac, ledpar}
\begin{document}
\begin{pages}
\begin{Leftside}
\beginnumbering
\pstart
\section{blah}
lorem ipsum\pend
\end{Leftside}
\begin{Rightside}
\beginnumbering
\pstart
\section{blerg}
asdf.
\pend
\end{Rightside}
\Pages
\end{pages}
\end{document}
``` | 2011/12/06 | [
"https://tex.stackexchange.com/questions/37243",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9830/"
] | Hmm, I actually don't use ledpar very often; I thought it was much more similar to `ledmac`. There are a few things wrong with the code you have above, but they are not the problem. This should work:
```
\documentclass[10pt]{article}
\usepackage{ledmac, ledpar}
\begin{document}
\begin{pages}
\begin{Leftside}
\beginnumbering
\pstart
\leavevmode\section{blah}% <--
lorem ipsum
\pend
\endnumbering% <--
\end{Leftside}
\begin{Rightside}
\beginnumbering
\pstart
\leavevmode\section{blerg}
asdf.
\pend
\endnumbering% <--
\end{Rightside}
\Pages
\end{pages}
\end{document}
```
My earlier comment was wrong: the `\section` commands do need to be inside the `\pstart ... \pend` (unlike in `ledmac`), but the `\leavevmode` will get rid of your error messages if you are using older versions of these packages; e.g.:
```
ledmac.sty 2005/03/24 v0.7 LaTeX port of EDMAC
ledpar.sty 2005/04/08 v0.3b ledmac extension for parallel texts
```
Note that newer versions are available on CTAN: [ledmac](http://mirror.its.dal.ca/ctan/help/Catalogue/entries/ledmac.html); [ledpar](http://mirror.its.dal.ca/ctan/help/Catalogue/entries/ledpar.html). It is possible they have fixed this issue.
**Edit:**
Now that I have both old and new (June 2012) versions of the packages, I can confirm that the `\leavevmode` is no longer necessary. (Though nothing changes if you leave it in.) | The new version of eledmac/eledpar (1.12 / 1.8) which will be released soon provide better tool to manage your case. It provides eledsection.
That is a MWE
```
\documentclass[10pt]{article}
\usepackage{ledmac, ledpar}
\begin{document}
\begin{pages}
\begin{Leftside}
\beginnumbering
\pstart
\eledsection{blah}
\pend
\pstart
lorem ipsum\pend
\end{Leftside}
\begin{Rightside}
\beginnumbering
\pstart
\eledsection{blerg}
\pend
\pstart
asdf.
\pend
\end{Rightside}
\Pages
\end{pages}
\end{document}
```
I invite you to wait some time the new version be posted on CTAN |
37,243 | I'm trying to create a bilingual critical edition with Latin on the left page and English on the right. I'm trying to figure out `ledpar` and I can't get the following example to compile. It compiles just fine if I comment out the two section headings, but with the section headings LaTeX throws the error on line 19 (which calls the `\Pages` macro) that says
```
You can't use \lastbox in vertical mode.
```
Here is the code I'm using:
```
\documentclass[10pt]{article}
\usepackage{ledmac, ledpar}
\begin{document}
\begin{pages}
\begin{Leftside}
\beginnumbering
\pstart
\section{blah}
lorem ipsum\pend
\end{Leftside}
\begin{Rightside}
\beginnumbering
\pstart
\section{blerg}
asdf.
\pend
\end{Rightside}
\Pages
\end{pages}
\end{document}
``` | 2011/12/06 | [
"https://tex.stackexchange.com/questions/37243",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9830/"
] | The new version of eledmac (1.1) provides commands for sectioning inside numbered text (and with critical notes) | The new version of eledmac/eledpar (1.12 / 1.8) which will be released soon provide better tool to manage your case. It provides eledsection.
That is a MWE
```
\documentclass[10pt]{article}
\usepackage{ledmac, ledpar}
\begin{document}
\begin{pages}
\begin{Leftside}
\beginnumbering
\pstart
\eledsection{blah}
\pend
\pstart
lorem ipsum\pend
\end{Leftside}
\begin{Rightside}
\beginnumbering
\pstart
\eledsection{blerg}
\pend
\pstart
asdf.
\pend
\end{Rightside}
\Pages
\end{pages}
\end{document}
```
I invite you to wait some time the new version be posted on CTAN |
10,343,190 | in my edit view i can retain value of the fields but the radio button.
like wen i select the row from grid and click edit it gives me previously saved value for all othr field bt not for radio buttons
how can i set those value
lik if the saved data contain value of gender as F then
```
if(gender='f')
{
<input type="radio" name="forwhom" value="f" checked="checked"></input>
}
else
<input type="radio" name="forwhom" value="m" checked="checked"></input>
```
i'm showing my data using 2 partial views as follows
do i have to write any ajax for it??
please help
regards!!! | 2012/04/27 | [
"https://Stackoverflow.com/questions/10343190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320898/"
] | You could use [Razor](http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx) in this case:
```
@Html.RadioButtonFor(x => x.Gender, "radioValue", new { @checked = true })
```
More about it here:
[How to set Html.RadioButtonFor as selected by default in Asp.net MVC3](http://dotnetech.wordpress.com/2011/03/20/how-to-set-one-html-radiobuttonfor-as-selected-by-default-in-asp-net-mvc3/) | or try this.
```
if(gender = 'f')
{
@Html.RadioButtonFor(x => x.Gender, "radioValue", new { @checked = "true"})
}
else
{
@Html.RadioButtonFor(x => x.Gender, "radioValue", new {@checked = "true"})
}
```
hope to help you out.. thanks. |
57,491,386 | I've read the introduction to R's dplyr programming (<https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html>), which is very useful.
I often build quite complex functions which include several sets of grouping variables. For example, given a dataset df, I may want the function to summarise by some variables (let's say grouping variables G1 and G2) and then summarise by some others (let's say G3), and I'll then use these summaries together to produce some final result
```r
df <- data.frame(xV = 1:3,yV=0:2, G1 =c(1,1,0),G2=c(0,0,1),G3=c(1,1,1))
#Within my function I want to calculate
#a)
df%>%group_by(G1,G2)%>%summarise(MEANS1= mean(xV,na.rm=T))
#As well as (b_
df%>%group_by(G3)%>%summarise(MEAN2= mean(xV,na.rm=T))
```
If I only had to do the first grouping (i.e. (a)) I can build a function, using ...
```r
TAB2<-function(data,x,...){
require(dplyr)
x<-enquo (x)
groupSet1 <- enquos(...)
data%>%group_by(!!!(groupSet1))%>%
summarise(MEAN=mean(!!x,na.rm=T))
}
#Which gives me my results
TAB2(data=df,x=xV,G1,G2)
# A tibble: 2 x 3
# Groups: G1 [2]
G1 G2 MEAN
<dbl> <dbl> <dbl>
1 0 1 3
2 1 0 1.5
```
But if I want to do both (a) and (b) I need in some way to distinguish between the first and second set of grouping variables (G1, G2) and G3 respectively. I can't do it by just chucking the grouping variables after all the other inputs. Is there any way I can specify these two sets in the input, something along the lines of
```r
TAB3<-function(data,x,y, GroupSet1=c(G1,G2) and GroupSet2=(G3)){
x<-enquo (x)
y<-enquo (x)
#a)
df%>%group_by(GroupSet1)%>%summarise(MEANS1= mean(!!x,na.rm=T))
#As well as (b_)
df%>%group_by(GroupSet2)%>%summarise(MEAN2= mean(!!y,na.rm=T))
}
```
I have tried to "quote" the two sets in a similar way to x<-enquo(x) in a range of ways but I always get an error. Could you please help? If it was also possible to pass a list of variables as x and y to summarise\_at it would also make the function as generic as possible, which would be even better. Basically I'm trying to create a template function that can take several variable sets x and y as well as several group sets, with the aim to produce the mean of the variables in the sets x and y by the corresponding group sets (G1, G2 and G3 respectively). | 2019/08/14 | [
"https://Stackoverflow.com/questions/57491386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7969026/"
] | You can try
```
TAB3<-function(data, y, grouping_list){
require(tidyverse)
map(grouping_list, ~group_by_at(data, .) %>%
summarise_at(y, list(Mean= mean), na.rm=T)) }
TAB3(df, "xV", list(c("G1", "G2"), c("G3")))
[[1]]
# A tibble: 2 x 3
# Groups: G1 [2]
G1 G2 Mean
<dbl> <dbl> <dbl>
1 0 1 3
2 1 0 1.5
[[2]]
# A tibble: 1 x 2
G3 Mean
<dbl> <dbl>
1 1 2
``` | If you wanted to use the ellipsis as per your TAB2 example, you could try:
**update based on new info:**
```r
TAB3<-function(df,x,...){
args <- substitute(list(...))
names_env <- setNames(as.list(names(df)), names(df))
arg_list <- eval(args, names_env)
out <- vector(mode = "list", length(arg_list))
for(i in seq_along(arg_list)){
out[[i]] <- df %>% group_by(!!!syms(arg_list[[i]])) %>%
summarise_at(vars(!!!enquos(x)) ,.funs = list(mean=mean), na.rm = T)
}
out
}
TAB3(df, x = c(xV,yV), GroupSet1=c(G1,G2), GroupSet2=G3)
#[[1]]
# A tibble: 2 x 4
# Groups: G1 [2]
# G1 G2 xV_mean yV_mean
# <dbl> <dbl> <dbl> <dbl>
#1 0 1 3 2
#2 1 0 1.5 0.5
#[[2]]
# A tibble: 1 x 3
# G3 xV_mean yV_mean
# <dbl> <dbl> <dbl>
#1 1 2 1
``` |
16,540,936 | When we try to authenticate using the spring authentication manager, its says "bad credentials":
```
Authentication request = new UsernamePasswordAuthenticationToken("john", "johnldap");
result = authenticationManager.authenticate(request);
```
Here the SecurityApplicationContext.xml file:
```
<authentication-manager alias="authenticationManager">
<ldap-authentication-provider server-ref="ldapLocal"
user-dn-pattern="uid={0},ou=People,dc=example,dc=com">
</ldap-authentication-provider>
</authentication-manager>
<ldap-server url="ldap://127.0.0.1:389/dc=example,dc=com" manager-dn="admin" manager-password="xxxxxxxx" id="ldapLocal" />
```
However using "ldapsearch" we can connect successfully:
```
ldapsearch -D "uid=john,ou=People,dc=example,dc=com" -w johnldap -L "objectClass=*"
```
At first time we thought the issue was that we've to tell spring to do a md5 of the password before call LDAP. So we add it to the applicationSecurtyContext.xml:
```
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
</beans:bean>
<authentication-manager alias="authenticationManager">
<ldap-authentication-provider server-ref="ldapLocal"
user-dn-pattern="uid={0},ou=People,dc=example,dc=com">
<password-compare>
<password-encoder ref="passwordEncoder"> </password-encoder>
</password-compare>
</ldap-authentication-provider>
</authentication-manager>
<ldap-server url="ldap://127.0.0.1:389/dc=example,dc=com" manager-dn="admin" manager-password="xxxxxxxx" id="ldapLocal" />
```
But when we add the tag it says:
```
LDAP: error code 34 - invalid DN]
```
What's wrong here? | 2013/05/14 | [
"https://Stackoverflow.com/questions/16540936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1051277/"
] | If I remember correctly the `user-dn-pattern` should not contain the root dn, as it will be automatically appended. So try using:
```
user-dn-pattern="uid={0},ou=People">
```
And I don't think you need the `password-encoder` if you only want to do a simple bind authentication. | I spent a lot of time trying to connect with spring security, looking at stackoverflow I also thought that it may be problem with encoding, because passwords are in md5, though **I had to add mentioned above root dn separately**, password gets encoded by ldap server. Below is my working version:
```
<ldap-server url="ldap://dsa.company.com:389/" manager-dn="cn=manager,dc=company,dc=com"
manager-password="pass"></ldap-server>
<authentication-manager>
<ldap-authentication-provider
user-dn-pattern="cn={0},ou=people,dc=company,dc=com"
group-search-base="ou=groups,dc=company,dc=com" />
</authentication-manager>
``` |
1,829,056 | I know this isn't a math question but this has been on my mind for quite some time. I am a second year university student who is planning on getting a degree in pure mathematics. I really enjoy the rigour and depth of understanding that comes from studying pure mathematics but I was wondering whether getting a degree in pure mathematics makes sense from a financial point of view. Many of my friends are combining mathematics with other majors such as finance, computer science, and statistics. I was wondering whether getting a pure math degree means that you only have opportunities in academia or are other opportunities also open to someone with a pure math degree? By the time I graduate university I will be about $30,000 in debt and would prefer to get a job so I can start paying off student loans. A secondary question is if I do pursue a career in academia how competitive is it to become a tenure professor at a reputable university? Also people that have gone to graduate school and gotten their doctorate, was getting a phd worth it from a financial point of view? | 2016/06/16 | [
"https://math.stackexchange.com/questions/1829056",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/347585/"
] | If you just want money, go into something like finance or even engineering. It's vastly easier, it's vastly easier to find a job, and you're paid better (at least until you're a well-established professor). It's not hard to find a job in industry with a pure math degree; but if that's all you want, there are far better ways of going about it. The point of a doctorate is to prepare you for doing original research in pure math. The situation is different in other fields, but in pure math, the only opportunity to do research is an academia. It's not necessary to take on a second degree in a more marketable field if you're worried about a job in industry, and it's certainly not going to help you if you're pursuing an academic career in pure mth.
As for your secondary question, it's insanely competitive. You have to be extremely good to even have a shot at all, and even then it's random luck: Did your research work out on time, does your advisor have the connections you need, do you get along well with your advisor and department, did you meet the right collaborator at a party that turns into the groundbreaking paper you were looking for, etc. If you want to be a mathematician, that's what your stuck with: Academia is the only place to do pure math, and there are multiple orders of magnitude more people--- all highly talented, hard-working, and dedicated--- than available positions. If you don't want to be a mathematician, don't bother. | If all you are concerned with is **salary** then, no, it is not financially worth it. |
1,829,056 | I know this isn't a math question but this has been on my mind for quite some time. I am a second year university student who is planning on getting a degree in pure mathematics. I really enjoy the rigour and depth of understanding that comes from studying pure mathematics but I was wondering whether getting a degree in pure mathematics makes sense from a financial point of view. Many of my friends are combining mathematics with other majors such as finance, computer science, and statistics. I was wondering whether getting a pure math degree means that you only have opportunities in academia or are other opportunities also open to someone with a pure math degree? By the time I graduate university I will be about $30,000 in debt and would prefer to get a job so I can start paying off student loans. A secondary question is if I do pursue a career in academia how competitive is it to become a tenure professor at a reputable university? Also people that have gone to graduate school and gotten their doctorate, was getting a phd worth it from a financial point of view? | 2016/06/16 | [
"https://math.stackexchange.com/questions/1829056",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/347585/"
] | An academical pursuit in pure mathematics is most likely not a lucrative decision, but it should not be a question about money. Indeed it is easy to say so, since money governs a lot of things in life including choice of education, but mathematics takes a lot of enthusiasm.
There are however more applicable pure mathematical topics than others; Analysis is famously applicable, algebraic geometry is not (but that will most likely change, as mathematics fails to be useless). Just out of interest, you might pursue further studies in differential equations or probability theory, by which mathematical finance (quant, look up salary/bonus if that motivates you) will be an alternative in case academia is not for you.
As far as I know about professor positions, they are insanely competitive. | If all you are concerned with is **salary** then, no, it is not financially worth it. |
1,829,056 | I know this isn't a math question but this has been on my mind for quite some time. I am a second year university student who is planning on getting a degree in pure mathematics. I really enjoy the rigour and depth of understanding that comes from studying pure mathematics but I was wondering whether getting a degree in pure mathematics makes sense from a financial point of view. Many of my friends are combining mathematics with other majors such as finance, computer science, and statistics. I was wondering whether getting a pure math degree means that you only have opportunities in academia or are other opportunities also open to someone with a pure math degree? By the time I graduate university I will be about $30,000 in debt and would prefer to get a job so I can start paying off student loans. A secondary question is if I do pursue a career in academia how competitive is it to become a tenure professor at a reputable university? Also people that have gone to graduate school and gotten their doctorate, was getting a phd worth it from a financial point of view? | 2016/06/16 | [
"https://math.stackexchange.com/questions/1829056",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/347585/"
] | If you just want money, go into something like finance or even engineering. It's vastly easier, it's vastly easier to find a job, and you're paid better (at least until you're a well-established professor). It's not hard to find a job in industry with a pure math degree; but if that's all you want, there are far better ways of going about it. The point of a doctorate is to prepare you for doing original research in pure math. The situation is different in other fields, but in pure math, the only opportunity to do research is an academia. It's not necessary to take on a second degree in a more marketable field if you're worried about a job in industry, and it's certainly not going to help you if you're pursuing an academic career in pure mth.
As for your secondary question, it's insanely competitive. You have to be extremely good to even have a shot at all, and even then it's random luck: Did your research work out on time, does your advisor have the connections you need, do you get along well with your advisor and department, did you meet the right collaborator at a party that turns into the groundbreaking paper you were looking for, etc. If you want to be a mathematician, that's what your stuck with: Academia is the only place to do pure math, and there are multiple orders of magnitude more people--- all highly talented, hard-working, and dedicated--- than available positions. If you don't want to be a mathematician, don't bother. | An academical pursuit in pure mathematics is most likely not a lucrative decision, but it should not be a question about money. Indeed it is easy to say so, since money governs a lot of things in life including choice of education, but mathematics takes a lot of enthusiasm.
There are however more applicable pure mathematical topics than others; Analysis is famously applicable, algebraic geometry is not (but that will most likely change, as mathematics fails to be useless). Just out of interest, you might pursue further studies in differential equations or probability theory, by which mathematical finance (quant, look up salary/bonus if that motivates you) will be an alternative in case academia is not for you.
As far as I know about professor positions, they are insanely competitive. |
39,246,465 | I am creating a table in which first column is column header and second column will be column data. Now I don't know is that possible to get data either via c# or javascript. Below is the example
```
<html>
<body>
<h1>Small Bakery Products</h1>
<table border="1" width="100%">
<tr>
<td>Id</td>
<td>@data.id</td>
</tr>
<tr>
<td>Name</td>
<td>@data.Name</td>
</tr>
<tr>
<td>Description</td>
<td>@data.Description</td>
</tr>
<tr>
<td>Price</td>
<td>@data.Price</td>
</tr>
</table>
</body>
</html>
``` | 2016/08/31 | [
"https://Stackoverflow.com/questions/39246465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I think you're mixing something up.
```
class MySingleton
include Singleton
attr_reader :data
def initialize
@data = {a: 1, b: 2}
end
end
foo = MySingleton.instance.data.clone
#=> {:a=>1, :b=>2}
foo[:c] = 3
#=> 3
foo
#=> {:a=>1, :b=>2, :c=>3}
MySingleton.instance.data
#=> {:a=>1, :b=>2}
``` | The concept of singleton pattern in Ruby has changed over time. Using `include Singleton` to implement explicit singleton classes has become fringe practice. Normally, you contruct an object eg. by calling `Object.new` and work with its singleton class `Object.new.singleton_class`, like this:
```
o = Object.new
class << o
attr_reader :data
end
```
And you have a fully functional singleton with custom selector `#data`. |
39,246,465 | I am creating a table in which first column is column header and second column will be column data. Now I don't know is that possible to get data either via c# or javascript. Below is the example
```
<html>
<body>
<h1>Small Bakery Products</h1>
<table border="1" width="100%">
<tr>
<td>Id</td>
<td>@data.id</td>
</tr>
<tr>
<td>Name</td>
<td>@data.Name</td>
</tr>
<tr>
<td>Description</td>
<td>@data.Description</td>
</tr>
<tr>
<td>Price</td>
<td>@data.Price</td>
</tr>
</table>
</body>
</html>
``` | 2016/08/31 | [
"https://Stackoverflow.com/questions/39246465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've tried with `.clone` and `.dup` and they both seem to work for me.
```
require 'singleton'
class MySingleton
include Singleton
attr_accessor :data
end
MySingleton.instance.data = {}
foo = MySingleton.instance.data
foo[:bar] = 'buzz'
puts foo # {:bar=>"buzz"}
puts MySingleton.instance.data # {:bar=>"buzz"}
MySingleton.instance.data = {}
foo = MySingleton.instance.data.dup # or .clone
foo[:bar] = 'buzz'
puts foo # {:bar=>"buzz"}
puts MySingleton.instance.data # {}
``` | The concept of singleton pattern in Ruby has changed over time. Using `include Singleton` to implement explicit singleton classes has become fringe practice. Normally, you contruct an object eg. by calling `Object.new` and work with its singleton class `Object.new.singleton_class`, like this:
```
o = Object.new
class << o
attr_reader :data
end
```
And you have a fully functional singleton with custom selector `#data`. |
32,694,304 | MySQL table name demo with below listed values peter and john with edit links
**Example**
```
Peter EDIT
John EDIT
```
on clicking **edit** link i'm opening edit\_name.php page. In edit\_name.php i'm updating my clicked edited value with update button..
My requirement is in edit\_name.php i should receive clicked name value
**for example**
If i click on peter edit button i should get peter value in edit\_name.php file and if i click on john edit button i should get john value in edit\_name.php etc..
please somebody help me in getting value of clicked in my edit\_name.php file
**php code**
```
<div>
<?php
$sql="select * from demo";
$data = $con->query($sql);
if($data->num_rows > 0)
{
while($row = $data->fetch_array(MYSQL_ASSOC))
{
$str = ""
?>
<div class="show_edit_page">
<div>
<?php echo $row['name'];?>
<a href="#" class="ajax_edit" data-id="<?php echo $row['id'];?>">EDIT</a>
</div>
</div>
<?php
}
}
?>
</div>
<div id="content"></div>
```
**Jquery Code**
jquery code to open edit\_name.php file on clicking edit link
```
$('.show_edit_page').on('click','.ajax_edit',function(){
var id = $(this).data('data-id');
$('#content').load('edit_name.php');
});
``` | 2015/09/21 | [
"https://Stackoverflow.com/questions/32694304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303332/"
] | You could give the name as URL parameter to the load URL:
```
('.show_edit_page').on('click','.ajax_edit',function(){
var id = $(this).attr('data-id');
$('#content').load('edit_name.php?name='+id);
});
```
then catch the name parameter in edit\_name.php file with:
```
$theName = $_REQUEST('name');
```
That should do...
Also the `.data` I would replace with `.attr` on line 2 | You have to update for accordingly.First you have to send that name via jQuery then you will receive that value in **PHP page**
```
$('.show_edit_page').on('click','.ajax_edit',function(){
var id = $(this).data('data-id');
var name = FetchNameValue; //Get this value using jQuery
$('#content').load('edit_name.php?name='+name); //Send value to edit_name.php
});
```
Once you send that value to PHP page then change code at php side
Use `$_GET['name']` to get value of name in PHP page.
I hope this will help you in case you have any query please tell me know. |
14,244,602 | I am trying to do to a user-pass validation. Updated code:
```
$username="------";
$password="------";
$database="------";
$host = "------";
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$username = $_POST['username'];
$password = $_POST['password'];
echo 'username: ' . $username . '<br>'; //myname
echo 'password: ' . $password . '<br>'; //mypass
function checkpass()
{
//$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='$_POST[username]' and PASSWORD='$_POST[password]' ") or die(mysql_error());
$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());
return mysql_num_rows($result);
}
checkpass();
echo 'checkpass:'. checkpass();
```
In the first query checkpass returns 1. In the second one it returns 0. Why? | 2013/01/09 | [
"https://Stackoverflow.com/questions/14244602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571648/"
] | Let's set aside the issues with mysql interface (not good to use going forward) and the fact that **you really really don't want to** put any kind of user affected variables straight into your sql strings [SQL injection!!!!], you say the following in your description that this:
`$result = mysql_query("SELECT * FROM REG_USERS where
USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());`
doesn't work.
Why would it? `$username` and `$password` are set to nothing. In your first example, you first set them to something, but then you don't use them (you use the straight `$_POST` variables instead).
In your second example, you don't set them.
So does the following work (note you don't need to concatenate the variables to get them into the string here)?
```
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM REG_USERS where
USERNAME='$username' and PASSWORD='$password'") or die(mysql_error());
```
Again, make sure you never actually do this in real code (just putting variables right into the SQL string). Use prepared statements instead. | Here's a solution using `mysqli_`:
```
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT USERNAME FROM REG_USERS WHERE USERNAME = ? AND PASSWORD = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $_POST[username], $_POST[password]);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $USERNAME);
/* fetch value */
mysqli_stmt_fetch($stmt);
echo "The username is $USERNAME";
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
``` |
14,244,602 | I am trying to do to a user-pass validation. Updated code:
```
$username="------";
$password="------";
$database="------";
$host = "------";
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$username = $_POST['username'];
$password = $_POST['password'];
echo 'username: ' . $username . '<br>'; //myname
echo 'password: ' . $password . '<br>'; //mypass
function checkpass()
{
//$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='$_POST[username]' and PASSWORD='$_POST[password]' ") or die(mysql_error());
$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());
return mysql_num_rows($result);
}
checkpass();
echo 'checkpass:'. checkpass();
```
In the first query checkpass returns 1. In the second one it returns 0. Why? | 2013/01/09 | [
"https://Stackoverflow.com/questions/14244602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571648/"
] | OK now we have the WHOLE code it's obvious.
`$username` and `$password` aren't global. The function doesn't know what they are set to.
```
$username = $_POST['username'];
$password = $_POST['password'];
echo 'username: ' . $username . '<br>'; //myname
echo 'password: ' . $password . '<br>'; //mypass
function checkpass()
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='$_POST[username]' and PASSWORD='$_POST[password]' ") or die(mysql_error());
$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());
return mysql_num_rows($result);
}
```
**NB I know about mysqli. OP isn't asking about it, I'm not obsessing about it** but I have added mysql\_real\_escape\_string for good measure. | Here's a solution using `mysqli_`:
```
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT USERNAME FROM REG_USERS WHERE USERNAME = ? AND PASSWORD = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $_POST[username], $_POST[password]);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $USERNAME);
/* fetch value */
mysqli_stmt_fetch($stmt);
echo "The username is $USERNAME";
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
``` |
14,244,602 | I am trying to do to a user-pass validation. Updated code:
```
$username="------";
$password="------";
$database="------";
$host = "------";
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$username = $_POST['username'];
$password = $_POST['password'];
echo 'username: ' . $username . '<br>'; //myname
echo 'password: ' . $password . '<br>'; //mypass
function checkpass()
{
//$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='$_POST[username]' and PASSWORD='$_POST[password]' ") or die(mysql_error());
$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());
return mysql_num_rows($result);
}
checkpass();
echo 'checkpass:'. checkpass();
```
In the first query checkpass returns 1. In the second one it returns 0. Why? | 2013/01/09 | [
"https://Stackoverflow.com/questions/14244602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571648/"
] | OK now we have the WHOLE code it's obvious.
`$username` and `$password` aren't global. The function doesn't know what they are set to.
```
$username = $_POST['username'];
$password = $_POST['password'];
echo 'username: ' . $username . '<br>'; //myname
echo 'password: ' . $password . '<br>'; //mypass
function checkpass()
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='$_POST[username]' and PASSWORD='$_POST[password]' ") or die(mysql_error());
$result = mysql_query("SELECT * FROM REG_USERS where USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());
return mysql_num_rows($result);
}
```
**NB I know about mysqli. OP isn't asking about it, I'm not obsessing about it** but I have added mysql\_real\_escape\_string for good measure. | Let's set aside the issues with mysql interface (not good to use going forward) and the fact that **you really really don't want to** put any kind of user affected variables straight into your sql strings [SQL injection!!!!], you say the following in your description that this:
`$result = mysql_query("SELECT * FROM REG_USERS where
USERNAME='" . $username . "' and PASSWORD='" . $password . "'") or die(mysql_error());`
doesn't work.
Why would it? `$username` and `$password` are set to nothing. In your first example, you first set them to something, but then you don't use them (you use the straight `$_POST` variables instead).
In your second example, you don't set them.
So does the following work (note you don't need to concatenate the variables to get them into the string here)?
```
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM REG_USERS where
USERNAME='$username' and PASSWORD='$password'") or die(mysql_error());
```
Again, make sure you never actually do this in real code (just putting variables right into the SQL string). Use prepared statements instead. |
44,781 | At what point in time does a person's sense of self (or soul) arrive when using a transporter?
Is there any time where a person would have no sense of self during transport? | 2013/11/09 | [
"https://scifi.stackexchange.com/questions/44781",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/12012/"
] | In the Next Generation episode "Realm of Fear" we saw a transporter cycle from Reginald Barclay's point of view. Barclay was aware of himself and his surroundings throughout transport. So we can conclude that the sense of self is always present during transport.
However, in the episode "Relics" we learned that Scotty kept himself alive for over 75 years inside the transport buffer without sensing the passage of time. So while the sense of self is always present the time sense (the rate at which the brain state changes) can be altered during transport. | While @KyleJones's answer is the first thing to pop into my head, there's also a short bit of dialogue at the end of ENT 2x10, [Vanishing Point](http://en.memory-alpha.org/wiki/Vanishing_Point_%28episode%29), that helps here:
>
> Trip: "You were sorta... trapped in the pattern buffer. But only for a few seconds."
>
> Reed: "8.3 seconds, to be precise."
>
> Hoshi: "Are you saying that I was just on the surface?"
>
> Trip: "You insisted on going second?"
>
>
>
>
And in the next scene...
>
> Hoshi: "So you're saying all of that happened in 8 seconds."
>
> Phlox: "Actually it probably happened in the last, uh, 1 or 2 seconds, as your matter stream was coalescing. [turns to Archer] She seems fine."
>
>
>
>
So this would seem to imply that while stored in the pattern buffer (as Scotty was in [Relics](http://en.memory-alpha.org/wiki/Relics_%28episode%29)), your consciousness (and sense of self along with it) are inert, and you experience nothing.
(Aside, Hoshi's transition from real life -> pattern buffer -> dream -> real life was seamless from her perspective, which also explains why we didn't see this "inert" state while viewing the transport from Barclay's perspective in [Realm of Fear](http://en.memory-alpha.org/wiki/Realm_of_Fear_%28episode%29)) |
121,468 | So I'm fairly new to more secure forms of key management, I've been used to storing my keys inside key files on my computer.
Recently I wanted to try and see if I could setup SSH authentication to my webserver using a key stored on my Nitrokey Pro making my keychain more portable and secure in the process.
I followed [this guide](http://xmodulo.com/linux-security-with-nitrokey-usb-smart-card.html) pretty much step by step but noticed that in the end, I did not need my Nitrokey Pro to be inserted into my computer at all for the authentication to succeed.
I have a feeling that upon exporting my key it somehow got added to my local key storage making the Nitrokey redundant but I am not knowledgable enough about the exact workings to be sure.
Would anyone be able to help me ensure that I can only SSH into my web server while my Nitrokey is inserted into my computer?
Notes:
* OS: OSX El Capitan 10.11.4
* Nitrokey Pro
* Even while the Nitrokey is inserted into my computer it does NOT ask me to enter a pin when I attempt to SSH.
* OpenSC 0.15.0
* gpg 2.0.28
I tried removing from ~/.ssh the following:
```
id.rsa
private_key.pem
```
after attempting to SSH to my web server again I get:
>
> Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
>
>
>
I assume this indicates that the SSH session cannot find my key to authenticate with,
I checked if my computer was detecting the Nitrokey by running:
>
> gpg --card-status
>
>
>
and received card information like I would expect. | 2016/04/25 | [
"https://security.stackexchange.com/questions/121468",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/68045/"
] | >
> I have a feeling that upon exporting my key it somehow got added to my local key storage making the NitroKey redundant but I am not knowledgable enough about the exact workings to be sure.
>
>
>
If that was done properly, it should not be possible. If the private key is stored in the "smartcard", it should not be exportable and for every private key operation, you need that card.
I don't have NitroKey and I am not knowledgeable about the nitrokey applications internals so few commands that should bring some more light:
* Post devbug log of your connection using the key stored on the cards: `ssh -vvv server`
* How does the `ssh-add -L` look like?
* Can you see the keys in the "smartcard" when running `pkcs11-tool --login -O --module /path/to/usr/lib64/pkcs11/opensc-pkcs11.so` | Nitrokey's guide you mention focused specifically on Linux, which can quickly lead to confusion and frustration for Mac users, since it is so close yet so far away from being the same. I'm not familiar with Nitrokey, but anything using the PCKS11 standard should be cross-compatible once you get it working. :-)
For MacOS, you don't actually need to go down the opensc road. Seemingly one of Apple's best kept secrets is that it [natively supports PKCS11 on its own](https://support.apple.com/guide/deployment/configure-macos-smart-cardonly-authentication-depfce8de48b/web), at least under more recent OS releases. (I'm really not sure about El Capitan from five years ago)
So, where you see a reference to opensc, the Mac-native alternative is [SmartCardServices](https://support.apple.com/guide/deployment/advanced-smart-card-options-dep7b2ede1e3/web). (but, hey, if you need or want opensc, it's a great tool)
Try the MacOS man page for ssh-keychain ([online at manpagez.com](https://www.manpagez.com/man/8/ssh-keychain/)). You'll find that ssh using SmartCard authentication surpisingly needs only one config line in your `~/.ssh/config` file:
```
PKCS11Provider /usr/lib/ssh-keychain.dylib
```
The first time I tried ssh-ing into my remote host, it seemed to take a while, but subsequent connections were quick to prompt for my PIN.
The amount of digging to find that *one line* was certainly non-trivial!
---
*For webcrawlers, because I haven't found them to know these terms are largely synonymous:
SmartCard - AKA: smart card, PIV, CAC* |
222,854 | I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied.
This is my server block from `nginx.conf`:
```
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
}
```
How would I proceed? Thanks very much! | 2011/01/15 | [
"https://serverfault.com/questions/222854",
"https://serverfault.com",
"https://serverfault.com/users/48051/"
] | Creative use of the location and deny rules negated in regex, something like:
```
location / {
root html;
index index.html index.htm index.php;
}
location ~* !^/(index.(php|html|htm)$)|(phpmyadmin/) {
deny all;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
```
That's untested but you get the idea.
<http://wiki.nginx.org/HttpAccessModule>
<http://wiki.nginx.org/HttpCoreModule#location>
Also, this may help you write it:
<http://www.regextester.com/> | It is easier to declare *servers* that are called with a domain name, and declare a *default* server that will include direct-IP accesses.
For instance your domain configuration could be used for, say, `mydomain.com`
```
server {
listen 80;
server_name mydomain.com *.mydomain.com;
root /var/www/html/mydomain.com
...
```
Having your regular files in the directory `/var/www/html/mydomain.com`.
And the default entry would only allow access to some specific files in a different location.
Note the *default* keyword after the `listen 80`.
```
server {
listen 80 default;
server_name _ *;
root /var/www/html/restricted
...
```
And you put the default files in `/var/www/html/restricted`, that will be served for *localhost* and raw IP addresses. |
222,854 | I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied.
This is my server block from `nginx.conf`:
```
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
}
```
How would I proceed? Thanks very much! | 2011/01/15 | [
"https://serverfault.com/questions/222854",
"https://serverfault.com",
"https://serverfault.com/users/48051/"
] | The easiest path would be to start out by denying all access, then only granting access to those directories you want. As ring0 pointed out, you can use the default (default\_server in 0.8) flag on the listen directive. However, if you already have a server you want to use as a default for unknown named access to your host, you can also just catch requests without a host header or with your server's ip address with something like this (replacing 1.2.3.4 with your server's ip:
```
upstream _php {
server unix:/var/run/php-fpm/php-fpm.sock;
}
server {
server_name "" 1.2.3.4;
root /path/to/root;
index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# deny everything that doesn't match another location
location / { deny all; }
# allow loading /index.php
location = / { } # need to allow GET / to internally redirect to /index.php
location = /index.php { fastcgi_pass _php; }
# allow access to phpmyadmin
location /phpmyadmin/ { } # Allow access to static files in /phpmyadmin/
location ~ ^/phpmyadmin/.*\.php$ { fastcgi_pass _php; } # phpmyadmin php files
}
```
the fastcgi\_params will be inherited by both locations that fastcgi\_pass, and only /index.php and /phpmyadmin/ are allowed. I've also added an upstream block for php, which makes it easier should you ever need to add to or change it in the future. | It is easier to declare *servers* that are called with a domain name, and declare a *default* server that will include direct-IP accesses.
For instance your domain configuration could be used for, say, `mydomain.com`
```
server {
listen 80;
server_name mydomain.com *.mydomain.com;
root /var/www/html/mydomain.com
...
```
Having your regular files in the directory `/var/www/html/mydomain.com`.
And the default entry would only allow access to some specific files in a different location.
Note the *default* keyword after the `listen 80`.
```
server {
listen 80 default;
server_name _ *;
root /var/www/html/restricted
...
```
And you put the default files in `/var/www/html/restricted`, that will be served for *localhost* and raw IP addresses. |
222,854 | I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied.
This is my server block from `nginx.conf`:
```
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
}
```
How would I proceed? Thanks very much! | 2011/01/15 | [
"https://serverfault.com/questions/222854",
"https://serverfault.com",
"https://serverfault.com/users/48051/"
] | It is easier to declare *servers* that are called with a domain name, and declare a *default* server that will include direct-IP accesses.
For instance your domain configuration could be used for, say, `mydomain.com`
```
server {
listen 80;
server_name mydomain.com *.mydomain.com;
root /var/www/html/mydomain.com
...
```
Having your regular files in the directory `/var/www/html/mydomain.com`.
And the default entry would only allow access to some specific files in a different location.
Note the *default* keyword after the `listen 80`.
```
server {
listen 80 default;
server_name _ *;
root /var/www/html/restricted
...
```
And you put the default files in `/var/www/html/restricted`, that will be served for *localhost* and raw IP addresses. | You can setting directly all path to the index.php and setting only on this file fastcgi php7 for nginx
```
//redirect all to index.php
location / {
autoindex off;
set $redirect_url $uri;
try_files $uri $uri/ /index.php$is_args$query_string;
}
location = /index.php {
include fastcgi.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
//Extra Params script PHP
fastcgi_param PATH_INFO $redirect_url;
fastcgi_param HTTP_HOST $server_name;
}
``` |
222,854 | I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied.
This is my server block from `nginx.conf`:
```
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
}
```
How would I proceed? Thanks very much! | 2011/01/15 | [
"https://serverfault.com/questions/222854",
"https://serverfault.com",
"https://serverfault.com/users/48051/"
] | The easiest path would be to start out by denying all access, then only granting access to those directories you want. As ring0 pointed out, you can use the default (default\_server in 0.8) flag on the listen directive. However, if you already have a server you want to use as a default for unknown named access to your host, you can also just catch requests without a host header or with your server's ip address with something like this (replacing 1.2.3.4 with your server's ip:
```
upstream _php {
server unix:/var/run/php-fpm/php-fpm.sock;
}
server {
server_name "" 1.2.3.4;
root /path/to/root;
index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# deny everything that doesn't match another location
location / { deny all; }
# allow loading /index.php
location = / { } # need to allow GET / to internally redirect to /index.php
location = /index.php { fastcgi_pass _php; }
# allow access to phpmyadmin
location /phpmyadmin/ { } # Allow access to static files in /phpmyadmin/
location ~ ^/phpmyadmin/.*\.php$ { fastcgi_pass _php; } # phpmyadmin php files
}
```
the fastcgi\_params will be inherited by both locations that fastcgi\_pass, and only /index.php and /phpmyadmin/ are allowed. I've also added an upstream block for php, which makes it easier should you ever need to add to or change it in the future. | Creative use of the location and deny rules negated in regex, something like:
```
location / {
root html;
index index.html index.htm index.php;
}
location ~* !^/(index.(php|html|htm)$)|(phpmyadmin/) {
deny all;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
```
That's untested but you get the idea.
<http://wiki.nginx.org/HttpAccessModule>
<http://wiki.nginx.org/HttpCoreModule#location>
Also, this may help you write it:
<http://www.regextester.com/> |
222,854 | I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied.
This is my server block from `nginx.conf`:
```
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
}
```
How would I proceed? Thanks very much! | 2011/01/15 | [
"https://serverfault.com/questions/222854",
"https://serverfault.com",
"https://serverfault.com/users/48051/"
] | Creative use of the location and deny rules negated in regex, something like:
```
location / {
root html;
index index.html index.htm index.php;
}
location ~* !^/(index.(php|html|htm)$)|(phpmyadmin/) {
deny all;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
```
That's untested but you get the idea.
<http://wiki.nginx.org/HttpAccessModule>
<http://wiki.nginx.org/HttpCoreModule#location>
Also, this may help you write it:
<http://www.regextester.com/> | You can setting directly all path to the index.php and setting only on this file fastcgi php7 for nginx
```
//redirect all to index.php
location / {
autoindex off;
set $redirect_url $uri;
try_files $uri $uri/ /index.php$is_args$query_string;
}
location = /index.php {
include fastcgi.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
//Extra Params script PHP
fastcgi_param PATH_INFO $redirect_url;
fastcgi_param HTTP_HOST $server_name;
}
``` |
222,854 | I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied.
This is my server block from `nginx.conf`:
```
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /srv/http/nginx/$fastcgi_script_name;
include fastcgi_params;
}
}
```
How would I proceed? Thanks very much! | 2011/01/15 | [
"https://serverfault.com/questions/222854",
"https://serverfault.com",
"https://serverfault.com/users/48051/"
] | The easiest path would be to start out by denying all access, then only granting access to those directories you want. As ring0 pointed out, you can use the default (default\_server in 0.8) flag on the listen directive. However, if you already have a server you want to use as a default for unknown named access to your host, you can also just catch requests without a host header or with your server's ip address with something like this (replacing 1.2.3.4 with your server's ip:
```
upstream _php {
server unix:/var/run/php-fpm/php-fpm.sock;
}
server {
server_name "" 1.2.3.4;
root /path/to/root;
index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# deny everything that doesn't match another location
location / { deny all; }
# allow loading /index.php
location = / { } # need to allow GET / to internally redirect to /index.php
location = /index.php { fastcgi_pass _php; }
# allow access to phpmyadmin
location /phpmyadmin/ { } # Allow access to static files in /phpmyadmin/
location ~ ^/phpmyadmin/.*\.php$ { fastcgi_pass _php; } # phpmyadmin php files
}
```
the fastcgi\_params will be inherited by both locations that fastcgi\_pass, and only /index.php and /phpmyadmin/ are allowed. I've also added an upstream block for php, which makes it easier should you ever need to add to or change it in the future. | You can setting directly all path to the index.php and setting only on this file fastcgi php7 for nginx
```
//redirect all to index.php
location / {
autoindex off;
set $redirect_url $uri;
try_files $uri $uri/ /index.php$is_args$query_string;
}
location = /index.php {
include fastcgi.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
//Extra Params script PHP
fastcgi_param PATH_INFO $redirect_url;
fastcgi_param HTTP_HOST $server_name;
}
``` |
13,376,644 | I've an application which is a scrollView filled with over 150 images .. I've followed this [tutorial](http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content%27) to create it .. the application is over 550MBs and it has about 500 (150 for iPhone 5 & 150 for Retina & 150 for non-retina & buttons) photos .. The application runs very well on the simulator with no problems but on a real device when I open the application it keeps loading then a crash
so can anyone help me with this, please?
Thanks in advance. | 2012/11/14 | [
"https://Stackoverflow.com/questions/13376644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1766119/"
] | Try to load only those images needed for displaying. ie while scrolling those images that are hidden should be taken off from the scrollview. Maybe you can make a design similar to the working of reusable UITableViewCell. ie a custom implementation for showing only the needed images and reusing them while scrolling.
There is another way, not a straight forward one, you can use a UITableView and add images to each cell and then rotate the tableview so that it will look like an horizontal scroll.
The advantage of doing this method is that the UITableView will handle all the reusability issue and we dont need to worry about. But I am not sure whether its the right way to do this.
Btw.. I have uploaded an app with the UITableView rotated horizontal scroll view to the appstore without getting rejected ;) | It is not an good way to do that ,u can upload your photo on server side and when open the app. loading the image from server.
```
id path = @"http://upload.wikimedia.org/wikipedia/commons/c/c7/Sholay-Main_Male_Cast.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
imageView.image = img;
```
LooK at this [answer](https://stackoverflow.com/questions/2510223/xcode-iphone-programming-loading-a-jpg-into-a-uiimageview-from-url) |
25,774 | Where can we find Deligne's paper " Theorie de Hodge I"? | 2010/05/24 | [
"https://mathoverflow.net/questions/25774",
"https://mathoverflow.net",
"https://mathoverflow.net/users/3945/"
] | [Voici](http://math.harvard.edu/~tdp/Deligne-Theorie.de.Hodge-1-single-page.pdf). | It is in the conference volume of the 1970 ICM at Nice. Not so easy to find online, it seems, if that is what you meant. There is a summary in a review:
<http://www.ams.org/journals/bull/2009-46-04/S0273-0979-09-01268-3/S0273-0979-09-01268-3.pdf> |
25,774 | Where can we find Deligne's paper " Theorie de Hodge I"? | 2010/05/24 | [
"https://mathoverflow.net/questions/25774",
"https://mathoverflow.net",
"https://mathoverflow.net/users/3945/"
] | Amazingly, ALL the ICM talks since the beginning of time can now be found online at [<http://mathunion.org/ICM/>](http://mathunion.org/ICM/) | It is in the conference volume of the 1970 ICM at Nice. Not so easy to find online, it seems, if that is what you meant. There is a summary in a review:
<http://www.ams.org/journals/bull/2009-46-04/S0273-0979-09-01268-3/S0273-0979-09-01268-3.pdf> |
60,487,295 | example data :
```
var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]
```
if i pass id as 1 result : [{name:"john",class:"1"}].
please help me with the above question please. | 2020/03/02 | [
"https://Stackoverflow.com/questions/60487295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12964227/"
] | You can use `_.find()` to get an item with the path of `a.id` that equals the `id` you are looking for. Then use `_.get()` to take the item out of the `a` property, and omit the `id`.
**Note**: This will give you a single item, and not an array of a single item. You can always wrap it in an array, if you absolutely need it.
```js
const { flow, find, get, omit } = _
const fn = id => flow(
arr => find(arr, ['a.id', id]), // find the item which has the id
item => get(item, 'a'), // extract it from a
item => omit(item, 'id'), // remove the id
)
const data = [{"a":{"id":"1","name":"alex","class":"1"}},{"a":{"id":"2","name":"john","class":"2"}},{"a":{"id":"3","name":"ketty","class":"3"}}]
const result = fn('1')(data)
console.log(result)
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
```
With lodash/fp you can just state the iteratees (the properties you wish to use), since lodash/fp functions are curried, and iteratees first:
```js
const { flow, find, get, omit } = _
const fn = id => flow(
find(['a.id', id]),
get('a'),
omit('id'),
)
const data = [{"a":{"id":"1","name":"alex","class":"1"}},{"a":{"id":"2","name":"john","class":"2"}},{"a":{"id":"3","name":"ketty","class":"3"}}]
const result = fn('1')(data)
console.log(result)
```
```html
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
``` | its really simple to do:-
```
var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]
let idToFind = 1;
let filtered = data.filter(f=>f['a']['id']==idToFind);
``` |
40,588,209 | I have classes as
```
class Citizen{
var name:String
var age:Int
var lawPrevilige = 0
init(name:String,age:Int){
self.name = name
self.age = age
}
}
class Politician{
var name:String
var age:Int
var lawPrevilige = 1
init(name:String,age:Int){
self.name = name
self.age = age
}
}
```
And a class to manipulate those
```
class PoliceDept{
var departMentName = "InterPol"
var departMentAddress:String = "Earth"
//this method should be able to access object of any class with the same properties.
func investigateAnyOne(person:AnyObject){
if let p = person as? Citizen{
print(p.name)
}else if let po = person as? Politician{
print(po.name)
}
}
}
```
Now the question is if I have a class `Disabled People`, `UnderAge People` etc with the exact properties name and age..So how can i make method `investigateAnyOne` of Police Dept act on AnyObject without the TypeCasting. Is that possible?
Downcasting to every types of object for 10-12 classes makes code messy..Should i create multiple if else statement to check the type of class or any other way conforming to protocol.
The question is what should i do if there are many other types of people who i want to investiaget.. | 2016/11/14 | [
"https://Stackoverflow.com/questions/40588209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Big O notations assume that n is large. n=4 is irrelevant to the complexity analysis.
In the general case, if you look at the ratio between both : `n.log(n) / n = log(n)` provided that n>0.
When n becomes large, this ratio tends to infinity, meaning that `n.log(n)` takes "infinitely" more time than `n`, and thus `n.log(n)` dominates `n`. | [big-o](/questions/tagged/big-o "show questions tagged 'big-o'") describes how fast functions grow asymphotically. `nlogn` grows faster than `n` so in your notation, `O(nlogn) > O(n)`, however it's not a proper notation.
Actually `O(nlogn)` is a set as well as `O(n)` is. There is also a relation between them:
[](https://i.stack.imgur.com/69vQ7.png)
Just for clarification needed according to comments: all logarithms grow same fast according to [big-o](/questions/tagged/big-o "show questions tagged 'big-o'"):
[](https://i.stack.imgur.com/00gxt.png) |
16,177,459 | I'm using `setlocale` and `strftime` to display localized month names in Brazilian Portuguese:
```
setlocale(LC_ALL, 'pt_BR');
$meses = array();
for($m=1; $m<=12; $m++) {
$meses[$m] = strftime('%B', mktime(0, 0, 0, $m, 1));
}
```
This works fine in my dev environment, but on the production server it fails for March (which in Portuguese is "março"). If I `utf8_encode` the month names, it works on the server, but on my dev environment I get a double-encoded output. I suspect that's because of different locale encodings on each machine. I guess the proper solution would be to install a UTF8 locale setting for pt\_BR on the server, but I'd like to avoid that if possible (long story short, the server admins are, er, difficult).
Is it possible to detect the encoding of the current locale from PHP, so I can code around this issue, and make my code work regardless of the locale/encoding settings? | 2013/04/23 | [
"https://Stackoverflow.com/questions/16177459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/825789/"
] | Use
```
echo setlocale(LC_CTYPE, 0); // en_US.UTF-8
```
to get the current encoding and then work around it.
Passing zero to `setLocale` gives you locale values. In this case we are getting the value for `LC_CTYPE` setting. | To get the encoding used by strftime use
```
mb_internal_encoding()
```
to convert the stftime encoded string to utf-8, use
```
mb_convert_encoding(strftime($format, $timestamp), 'UTF-8', mb_internal_encoding());
``` |
16,177,459 | I'm using `setlocale` and `strftime` to display localized month names in Brazilian Portuguese:
```
setlocale(LC_ALL, 'pt_BR');
$meses = array();
for($m=1; $m<=12; $m++) {
$meses[$m] = strftime('%B', mktime(0, 0, 0, $m, 1));
}
```
This works fine in my dev environment, but on the production server it fails for March (which in Portuguese is "março"). If I `utf8_encode` the month names, it works on the server, but on my dev environment I get a double-encoded output. I suspect that's because of different locale encodings on each machine. I guess the proper solution would be to install a UTF8 locale setting for pt\_BR on the server, but I'd like to avoid that if possible (long story short, the server admins are, er, difficult).
Is it possible to detect the encoding of the current locale from PHP, so I can code around this issue, and make my code work regardless of the locale/encoding settings? | 2013/04/23 | [
"https://Stackoverflow.com/questions/16177459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/825789/"
] | In comments below the question we could resolve the problem. It was caused because the locale names differed on both systems one used `pt_BR.uft-8` the other `pt_BR.UTF8`.
Finally we agreed to define the locale in a config file and use that. | To get the encoding used by strftime use
```
mb_internal_encoding()
```
to convert the stftime encoded string to utf-8, use
```
mb_convert_encoding(strftime($format, $timestamp), 'UTF-8', mb_internal_encoding());
``` |
685,608 | given the 2 PDE
$$ \Delta u-au\_{tt}+u\_{t}=0$$
and $$ \Delta u + Du\*Df=0 $$
here $ \Delta u $ is the Laplacian $ Du= grad(u) $ is the gradient and \* means scalar product $u\_{t} = \frac{\partial u}{\partial t}$
my doubt is what term should i include to get the linear part of the equations $ u\_{t} $ and $Du\*Df $ from the Euler Lagrange equations in $ R^{n} $ thanks | 2014/02/18 | [
"https://math.stackexchange.com/questions/685608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/17341/"
] | Well, for the second case, the Lagrangian you want is
$$
\Lambda\_D(u) = \tfrac12 \int\_D\ e^{f(x)}\ |\nabla u|^2\ \mathrm{d}x
$$
where $D$ is an appropriate domain in $\mathbb{R}^n$. The first case is similar (if you are assuming that $a$ is a constant), for then, it will just be
$$
\Lambda\_D(u) = \tfrac12 \int\_{D'}\ e^{t}\ \bigl(|\nabla u|^2-a|u\_t|^2\bigr)\ \mathrm{d}x\mathrm{d}t
$$
where $D'$ is an appropriate domain in $\mathbb{R}^n\times \mathbb{R}$. If $a$ is not a constant, there are conditions. | Here we will assume that the definition of the [Laplacian](http://en.wikipedia.org/wiki/Laplace_operator) is $\Delta=\vec{\nabla}^2$, and that $a$ is a non-zero constant.
I) The [Lagrangian density](http://en.wikipedia.org/wiki/Lagrangian)
>
> $$\tag{1a} {\cal L}\_1~=~ \frac{e^{-t/a}}{2}\left(a\dot{u}^2 - (\vec{\nabla} u)^2\right)$$
>
>
>
has [Euler-Lagrange equation](http://en.wikipedia.org/wiki/Euler-Lagrange_equation)
$$0~\stackrel{(1a)}{=}~\frac{\partial {\cal L}\_1}{\partial u}
~\stackrel{EL}{=}~\frac{d}{dt}\frac{\partial {\cal L}\_1}{\partial \dot{u}}
+\vec{\nabla}\cdot\frac{\partial {\cal L}\_1}{\partial \vec{\nabla}u}$$
$$\tag{1b} ~\stackrel{(1a)}{=}~ \frac{d}{dt}\left(e^{-t/a}a\dot{u}\right) - \vec{\nabla}\cdot \left(e^{-t/a}\vec{\nabla}u\right)
~=~e^{-t/a}\left(a\ddot{u}-\dot{u}-\Delta u\right) $$
equal to OP's first PDE
>
> $$\tag{1c} a\ddot{u}-\dot{u}-\Delta u~\stackrel{(1b)}{=}~0.$$
>
>
>
II) The Lagrangian density
>
> $$\tag{2a} {\cal L}\_2~=~ \frac{e^f}{2} (\vec{\nabla} u)^2$$
>
>
>
has Euler-Lagrange equation
$$ 0~\stackrel{(2a)}{=}~\frac{\partial {\cal L}\_2}{\partial u}
~\stackrel{EL}{=}~\vec{\nabla}\cdot\frac{\partial {\cal L}\_2}{\partial \vec{\nabla}u}$$
$$\tag{2b}~\stackrel{(2a)}{=}~\vec{\nabla}\cdot \left(e^f\vec{\nabla}u\right)
~=~e^f\left(\Delta u +\vec{\nabla}f \cdot \vec{\nabla}u\right) $$
equal to OP's second PDE
>
> $$\tag{2c} \Delta u +\vec{\nabla}f \cdot \vec{\nabla}u~\stackrel{(2b)}{=}~0.$$
>
>
>
--
[Note added: OP's question was originally cross-posted to mathoverflow and migrated back to Math.SE, so that OP's question appeared in duplicates on Math.SE. This answer (which was composed without knowing of the duplicate entry) originally appeared under the [original Math.SE question](https://math.stackexchange.com/q/680624/11127), but is now moved here to collect all answers in one place.] |
33,436,494 | Trying to use the statement:
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) < DATE_ADD(USEC_TO_TIMESTAMP(NOW()), 60, 'MINUTE')
```
to get data from my bigquery data. It seems to return same set of result even when time is not within the range. `timeCollected` is of the format `2015-10-29 16:05:06`.
I'm trying to build a query that is meant to return is data that is not older than an hour. So data collected within the last hour should be returned, the rest should be ignored. | 2015/10/30 | [
"https://Stackoverflow.com/questions/33436494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100757/"
] | The query you made means "return to me anything that has a collection time smaller than an hour in the future" which will literally mean your whole table. You want the following (from what I got through your comment, at least) :
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) > DATE_ADD(USEC_TO_TIMESTAMP(NOW()), -60, 'MINUTE')
```
This means that any timeCollected that is NOT greater than an hour ago will not be returned. I believe this is what you want.
Also, unless you need it, Select \* is not ideal in BigQuery. Since the data is saved by column, you can save money by selecting only what you need down the line. I don't know your use case, so \* may be warranted though | To get table data collected within the last hour:
```
SELECT * FROM [data.example@-3600000--1]
```
<https://cloud.google.com/bigquery/table-decorators> |
33,436,494 | Trying to use the statement:
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) < DATE_ADD(USEC_TO_TIMESTAMP(NOW()), 60, 'MINUTE')
```
to get data from my bigquery data. It seems to return same set of result even when time is not within the range. `timeCollected` is of the format `2015-10-29 16:05:06`.
I'm trying to build a query that is meant to return is data that is not older than an hour. So data collected within the last hour should be returned, the rest should be ignored. | 2015/10/30 | [
"https://Stackoverflow.com/questions/33436494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100757/"
] | The query you made means "return to me anything that has a collection time smaller than an hour in the future" which will literally mean your whole table. You want the following (from what I got through your comment, at least) :
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) > DATE_ADD(USEC_TO_TIMESTAMP(NOW()), -60, 'MINUTE')
```
This means that any timeCollected that is NOT greater than an hour ago will not be returned. I believe this is what you want.
Also, unless you need it, Select \* is not ideal in BigQuery. Since the data is saved by column, you can save money by selecting only what you need down the line. I don't know your use case, so \* may be warranted though | Using Standard SQL:
```
SELECT * FROM data WHERE timestamp > **TIMESTAMP_SUB**(CURRENT_TIMESTAMP(), INTERVAL 60 MINUTE)
``` |
33,436,494 | Trying to use the statement:
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) < DATE_ADD(USEC_TO_TIMESTAMP(NOW()), 60, 'MINUTE')
```
to get data from my bigquery data. It seems to return same set of result even when time is not within the range. `timeCollected` is of the format `2015-10-29 16:05:06`.
I'm trying to build a query that is meant to return is data that is not older than an hour. So data collected within the last hour should be returned, the rest should be ignored. | 2015/10/30 | [
"https://Stackoverflow.com/questions/33436494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100757/"
] | Using Standard SQL:
```
SELECT * FROM data
WHERE timestamp > TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL -60 MINUTE)
``` | To get table data collected within the last hour:
```
SELECT * FROM [data.example@-3600000--1]
```
<https://cloud.google.com/bigquery/table-decorators> |
33,436,494 | Trying to use the statement:
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) < DATE_ADD(USEC_TO_TIMESTAMP(NOW()), 60, 'MINUTE')
```
to get data from my bigquery data. It seems to return same set of result even when time is not within the range. `timeCollected` is of the format `2015-10-29 16:05:06`.
I'm trying to build a query that is meant to return is data that is not older than an hour. So data collected within the last hour should be returned, the rest should be ignored. | 2015/10/30 | [
"https://Stackoverflow.com/questions/33436494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100757/"
] | To get table data collected within the last hour:
```
SELECT * FROM [data.example@-3600000--1]
```
<https://cloud.google.com/bigquery/table-decorators> | Using Standard SQL:
```
SELECT * FROM data WHERE timestamp > **TIMESTAMP_SUB**(CURRENT_TIMESTAMP(), INTERVAL 60 MINUTE)
``` |
33,436,494 | Trying to use the statement:
```
SELECT *
FROM data.example
WHERE TIMESTAMP(timeCollected) < DATE_ADD(USEC_TO_TIMESTAMP(NOW()), 60, 'MINUTE')
```
to get data from my bigquery data. It seems to return same set of result even when time is not within the range. `timeCollected` is of the format `2015-10-29 16:05:06`.
I'm trying to build a query that is meant to return is data that is not older than an hour. So data collected within the last hour should be returned, the rest should be ignored. | 2015/10/30 | [
"https://Stackoverflow.com/questions/33436494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100757/"
] | Using Standard SQL:
```
SELECT * FROM data
WHERE timestamp > TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL -60 MINUTE)
``` | Using Standard SQL:
```
SELECT * FROM data WHERE timestamp > **TIMESTAMP_SUB**(CURRENT_TIMESTAMP(), INTERVAL 60 MINUTE)
``` |
44,721,213 | How can I plot 3D figures in scilab? I'm looking for something like [pcshow](https://in.mathworks.com/help/vision/ref/pcshow.html) in matlab. | 2017/06/23 | [
"https://Stackoverflow.com/questions/44721213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8205017/"
] | Do this instead:
```
bool (*myArray)[2] = calloc(N, sizeof(*myArray));
```
---
Or, if you do not wish to modify your declaration, just get rid of the first calloc here and modify your for loop:
```
myArray = calloc(N, 2*sizeof(bool)); // you do not need that
for (int i=0; i < 2; i++)
{
myArray[i] = calloc(N, sizeof(bool));
}
```
---
PS: In C we [don't cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc), we do that when we wish to compile C++. | The reason you can't reallocate `myArray` is that `myArray` is not a pointer. It is an array of two pointers to `bool`. It is also, contrary to your description, not a "2-dimension array".
All you need to do is
```
for (int i=0; i < 2; ++i)
{
myArray[i] = calloc(N, sizeof(bool));
}
```
and you can then use as a '2\*N' array, for example to set all elements to `true`;
```
for (int i = 0; i < 2; ++i)
{
for (j = 0; j < N; ++j)
myArray[i][j] = true;
}
```
If you swap the order of indices (e.g. use `myArray[j][i]` in the inner loop above) and use `myArray` as a 'N\*2' array rather than as a '2\*N' array, the result will be undefined behaviour. There is no solution to change that, without changing the declaration of `myArray` - which you have said you do not want to do. |
44,721,213 | How can I plot 3D figures in scilab? I'm looking for something like [pcshow](https://in.mathworks.com/help/vision/ref/pcshow.html) in matlab. | 2017/06/23 | [
"https://Stackoverflow.com/questions/44721213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8205017/"
] | This code:
```
bool* myArray[2];
int N;
```
doesn't declare a 2-dimensional array but an array of pointers. This is an important difference because 2-dimensional arrays are not *arrays of pointers to arrays* -- they are just stored contiguously, like 1-dimensional arrays are (one "row" after the other).
So, as you state you cannot change the declaration, let's instead explain what you need for an array of pointers. With your declaration, you declare exactly 2 pointers, so `N` can only mean the "second dimension" as in the number of elements in the arrays those pointers point to. With this declaration, you can have 2 times an array of `N` bools. Allocating them would look like this:
```
myArray[0] = calloc(N, sizeof(bool));
myArray[1] = calloc(N, sizeof(bool));
```
There's no need to allocate space for `myArray` itself, with your declaration, it already has automatic storage. | The reason you can't reallocate `myArray` is that `myArray` is not a pointer. It is an array of two pointers to `bool`. It is also, contrary to your description, not a "2-dimension array".
All you need to do is
```
for (int i=0; i < 2; ++i)
{
myArray[i] = calloc(N, sizeof(bool));
}
```
and you can then use as a '2\*N' array, for example to set all elements to `true`;
```
for (int i = 0; i < 2; ++i)
{
for (j = 0; j < N; ++j)
myArray[i][j] = true;
}
```
If you swap the order of indices (e.g. use `myArray[j][i]` in the inner loop above) and use `myArray` as a 'N\*2' array rather than as a '2\*N' array, the result will be undefined behaviour. There is no solution to change that, without changing the declaration of `myArray` - which you have said you do not want to do. |
939,971 | Setfocus() only works on windows, not browser tabs. Any ideas? | 2009/06/02 | [
"https://Stackoverflow.com/questions/939971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17675/"
] | if you are talking about switching tabs, you cant do it. sorry. | If this is strictly for IE and for an intranet where you have significant control over software versions, etc, you might be able to solve this by making an addon for IE. |
299,518 | I have installed the latest version of iTerm2 and I have found that INSERT while inserting a file under vim is not showing on the screen. Also, I am not able to see parameters under top command.
[](https://i.stack.imgur.com/FC8wC.png) | 2017/09/24 | [
"https://apple.stackexchange.com/questions/299518",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/256830/"
] | That was the issue of the colour. I have previously changed the background colour to white Hence, it was not showing. I have changed the colour of the "BOLD" text to black and now I am able to see the `--- INSERT ---` and the bold text on the TOP.
Also, I have deleted all of the setting to check.
Ref: <http://iterm2.com/faq.html>
```
defaults delete com.googlecode.iterm2
``` | Not sure about top, but in Vim, try `:set showmode`. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The iPhone SDK requires Mac OS, and you need to install the SDK even if you plan to develop applications with, say, [MonoTouch](http://www.mono-project.com/MonoTouch) or [Corona](http://www.anscamobile.com/faq/).
I don't know if Mac OS can be run as a virtual machine inside Linux. Anyway, you may consider buying a Mac Mini. It is not very expensive and powerful enough for software development. | xCode without Mac OS is definitely not possible. The real question here is, wether it's possible to install the complete Mac operating system in a virtual environment or not. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The [OSX86](http://www.osx86project.org/) project might solve your problem. It's not as convenient as buying a cheap Mac, but you can install it on a regular PC and it seems there are ways to install XCode on it.
If you end up buying a Mac, be sure to look at the specs for IPhone development first. If I remember correctly, you need a mac based on an x86 core (such as the Mac Mini) to develop IPhone software. | As far as I know iPhone development under unix is only possible if you jailbreak your iPhone. Which I would not recommend. You could try to buy a used Intel mac mini to develop for the iPhone. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The iPhone SDK requires Mac OS, and you need to install the SDK even if you plan to develop applications with, say, [MonoTouch](http://www.mono-project.com/MonoTouch) or [Corona](http://www.anscamobile.com/faq/).
I don't know if Mac OS can be run as a virtual machine inside Linux. Anyway, you may consider buying a Mac Mini. It is not very expensive and powerful enough for software development. | The [OSX86](http://www.osx86project.org/) project might solve your problem. It's not as convenient as buying a cheap Mac, but you can install it on a regular PC and it seems there are ways to install XCode on it.
If you end up buying a Mac, be sure to look at the specs for IPhone development first. If I remember correctly, you need a mac based on an x86 core (such as the Mac Mini) to develop IPhone software. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The iPhone SDK requires Mac OS, and you need to install the SDK even if you plan to develop applications with, say, [MonoTouch](http://www.mono-project.com/MonoTouch) or [Corona](http://www.anscamobile.com/faq/).
I don't know if Mac OS can be run as a virtual machine inside Linux. Anyway, you may consider buying a Mac Mini. It is not very expensive and powerful enough for software development. | Last Saturday I tested a very nice soft called... VMware !
So is it possible to install mac OSX leopard on this kind of virtual machine ? |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | xCode without Mac OS is definitely not possible. The real question here is, wether it's possible to install the complete Mac operating system in a virtual environment or not. | Martin,
I am doing some apps development for an iPhone and I have a Windows 7. You can install VMWare and install the Mac OS 10.6 through this and load xCode from Mac. The key is in finding the correct place to download VMWare and Mac OS.
Good Luck. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The [OSX86](http://www.osx86project.org/) project might solve your problem. It's not as convenient as buying a cheap Mac, but you can install it on a regular PC and it seems there are ways to install XCode on it.
If you end up buying a Mac, be sure to look at the specs for IPhone development first. If I remember correctly, you need a mac based on an x86 core (such as the Mac Mini) to develop IPhone software. | Martin,
I am doing some apps development for an iPhone and I have a Windows 7. You can install VMWare and install the Mac OS 10.6 through this and load xCode from Mac. The key is in finding the correct place to download VMWare and Mac OS.
Good Luck. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The iPhone SDK requires Mac OS, and you need to install the SDK even if you plan to develop applications with, say, [MonoTouch](http://www.mono-project.com/MonoTouch) or [Corona](http://www.anscamobile.com/faq/).
I don't know if Mac OS can be run as a virtual machine inside Linux. Anyway, you may consider buying a Mac Mini. It is not very expensive and powerful enough for software development. | Martin,
I am doing some apps development for an iPhone and I have a Windows 7. You can install VMWare and install the Mac OS 10.6 through this and load xCode from Mac. The key is in finding the correct place to download VMWare and Mac OS.
Good Luck. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | xCode without Mac OS is definitely not possible. The real question here is, wether it's possible to install the complete Mac operating system in a virtual environment or not. | Last Saturday I tested a very nice soft called... VMware !
So is it possible to install mac OSX leopard on this kind of virtual machine ? |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | xCode without Mac OS is definitely not possible. The real question here is, wether it's possible to install the complete Mac operating system in a virtual environment or not. | As far as I know iPhone development under unix is only possible if you jailbreak your iPhone. Which I would not recommend. You could try to buy a used Intel mac mini to develop for the iPhone. |
1,372,372 | My question is very simple:
* Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?
Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1372372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127493/"
] | The iPhone SDK requires Mac OS, and you need to install the SDK even if you plan to develop applications with, say, [MonoTouch](http://www.mono-project.com/MonoTouch) or [Corona](http://www.anscamobile.com/faq/).
I don't know if Mac OS can be run as a virtual machine inside Linux. Anyway, you may consider buying a Mac Mini. It is not very expensive and powerful enough for software development. | As far as I know iPhone development under unix is only possible if you jailbreak your iPhone. Which I would not recommend. You could try to buy a used Intel mac mini to develop for the iPhone. |
2,632,400 | I'm trying to compute this limit $\lim\_{(x,y) \to (0,0)}2x\sin^2(\frac{1}{y})$, but WolframAlpha says that it does not exist.
I'm not quite sure why. I do understand that there are oscillations coming from the $\sin(1/y)$. However, $x \to 0$ as well. Shouldn't that crush the function to zero?
Also, I know that $\lim\_{x \to 0} x \sin(\frac{1}{x}) = 0$. Isn't that pretty much the same idea as the limit in question? | 2018/02/02 | [
"https://math.stackexchange.com/questions/2632400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99142/"
] | It is equal to $0$ according to Wolfram alpha.
[](https://i.stack.imgur.com/rklfM.png)
The domain of the function should exclude the $x$-axis, that is the domain $D = \{ (x,y) : y \neq 0\}$.
Let $\epsilon > 0$, we choose $\delta = \frac{\epsilon}2$, if $(x,y) \in D$ and $\sqrt{(x-0)^2+(y-0)^2} < \delta$
then
$$ \left|2x\sin^2 \left( \frac1y\right)-0\right| = \left|2x\sin^2 \left( \frac1y\right)\right|\leq 2|x| \leq 2 \delta < \epsilon.$$ | $$|2x\sin^2(1/y)|\le 2|x|\cdot |1|\le 2|x|.$$
Since $2|x|\to 0$ as $x\to 0$, the limit is not undefined. |
43,698,606 | I have a simple web application that I've deployed to Microsoft Azure.
```
User.aspx
Admin.aspx
```
I am going to be the only admin so I don't want to put in authorization system if I don't have to. What are some simple ways to lock down my admin page so I can be the only admin and not have to login? Just looking to "keep honest people honest" kinda thing. | 2017/04/29 | [
"https://Stackoverflow.com/questions/43698606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] | Best solution would be *not to publish the admin page* to a public server. If possible, run a local instance instead which connects to the database.
Otherwise you can think of some possible (not the best) options, which you can also combine:
* set some sort of identification in the url: Admin.aspx?user=admin&pwd=admin123&uniquecode=has4d2ehfw545fg
If any parameter is omitted then redirect to user.aspx.
* in the Admin.aspx webform, add an extra input field containing some sort of (changing) information which the server can verify.
* filter on IP address. | Do a redirect based on client's IP address.
In the admin.aspx Page\_load event check the IP address and if not whitelisted then redirect to Users.aspx.
To get users's IP address see [this](https://stackoverflow.com/a/19286308/1093508) question. |
578,641 | Please tell me if my assumption is correct.
So nuclear fusion does not occur with nuclei (with a nucleon number higher than 56) because the binding energy of the product nucleus is lower than the binding energy of the nuclei fusing together.
Due to the product nucleus having a lower binding energy (and thus lower mass defect), this must mean that mass has been gained through the reaction which is impossible because energy is released...????
Please let me know if I am wrong, I am really struggling to understand the concept of binding energy :( | 2020/09/09 | [
"https://physics.stackexchange.com/questions/578641",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/273464/"
] | This notation seems a bit confusing to me and I would recommend reading a different text on the topic.
However, in the terms that you present, $\Omega(N,V,E)$ is the number of different (non-repeated) microstates compatible with the macrostate $(N,V,E)$. This is different from $\mathcal{N}$, which is the random collection of microstates compatibles with $(N,V,E)$. Think on an extreme example: you are interested in a macrostate $(N,V,E)$ which only have one compatible microstate, say $x$, then $P(x)=1\rightarrow\Omega=1$. However, the collection (or ensemble) of states have still $\mathcal{N}$ elements, in particular, these elements are all copies of the state $x$.
I don't understand the relationship between your doubt about $\mathcal{N}$ and the differences in quantum and classical states. Briefly, the statistics differ because of the intrinsic random nature of a quantum state (ket). While in classical systems the source of randomness is just due to the degeneracy of microstates compatible with a macrostate, a quantum microstate has also a stochastic nature that requires a different formalism (E.g. density matrix). | This notation seems familiar. There is a small error here, if all the *quantum* states were equally likely, then degenerate eigenvalues would be more likely observed and $P\_i \neq \dfrac{1}{\Omega}$. I have given the corrected statement here. Besides that, let me answer your questions.
>
> My question is, isn't $\mathcal{N} = \Omega$?
>
>
>
No, $\mathcal{N}$ can be any very large number; it is the number of systems in the ensemble. $\Omega$ is number of the microstates of the system $\Omega = \sum\_{i}\Omega (E\_{i})$. The probability is given by $P\_{i} = \dfrac{\Omega (E\_{i})}{\Omega}$. Hope this also explains that $\Omega$ is not the *density of states*.
>
> From my understanding, in classical ensembles, we have phase
> coordinates defining our system, in quantum systems, we have wave
> functions defining our system. Am I right in saying that?
>
>
>
The variables of state have no correlation with the likelihood of observing a system in a particular state. Phase coordinates in classical systems (defining the state) are not the same as a basis set chosen for the wavefunction (variables of state describing the system).
**Correction:** The correct statement in the book should be 'each eigenvalue is equally probable' or that $P\_i = \dfrac{\text{deg}\_{i}}{\Omega}$ where $\text{deg}\_{i}$ is the the number of quantum system corresponding to the eigenvalue $E\_{i}$, that is its degeneracy. |
11,173,363 | Below is some jQuery code the i wrote to make a simple animation. However I'm SO new to it i have no idea how to condense it down and get baffled by tutorials!
```
<!-- Login Form Div Animation -->
<script type="text/javascript">
$(document).ready(function() {
$('#button-active').hide();
if ($("#LoginButton").hasClass("inactive")) {
$("#TopLoginForm").hide();
} else {
$("#TopLoginForm").show();
}
$("#LoginButton").click( function() {
if ($("#LoginButton").hasClass("inactive")) {
$("#LoginButton").animate({
marginTop: "-40px"
}, 500 );
$("#button-inactive").animate({
opacity: "0"
}, 500 );
$('#button-inactive').remove();
$('#button-active').hide();
$('#button-active').delay(30).fadeIn(1000);
$('#LoginWelcome').delay(0).fadeOut(1000);
$('#TopLoginForm').delay(800).fadeIn(1000);
$("#LoginButton").addClass("button");
$("#LoginButton.button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
</script>
<!-- End Login Form Div Animation -->
```
The live code can be seen on www.trainingthemlive.co.uk/temp its at the top of the page | 2012/06/23 | [
"https://Stackoverflow.com/questions/11173363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477407/"
] | One big thing regarding optimization in jQuery is knowing that the jQuery function `jQuery()` often aliased as `$()` is indeed a function.
That means that using `$('#some_id')` is actually calling a function which **looks for** the HTML element with the id #some\_id. This is costly performance wise because **looking for** something in the DOM means traversing a tree and checking/ comparing the properties of the nodes.
You should fetch an HTML element from the DOM (with jQuery) and save the reference into a variable. And later on in the script you'll reference that HTML element using the same variable so as not to traverse the DOM again **looking for** the same element.
By using jQuery's `method chaining` approach (as suggested by @meloncholy) you would obtain the same benefits as defining a variable plus a more compact syntax. This is useful for manipulating an object you don't need a reference to later on, so you just stack-up all the manipulations you need done to it.
An example would be:
```
var some_object = $('#some_id');
some_object.hide();
if (some_object.hasClass('some_class')) {
...
```
I can't say that there will be a **noticeable** performance improvement to a script this size. If you had a few hundred lines of jQuery code all abusing the `jQuery()` function and a few hundred HTML elements in the tree and then you refactored the jQuery code as I indicated then you would have a speedup. | Best i get can do. You had a lot of repeating functions
```
$(document).ready(function() {
//Start hidden
$('#button-active').hide();
$("#TopLoginForm").hide();
// clicking "login"
$("#LoginButton").click( function() {
if ($("#LoginButton").hasClass("inactive")) {
$("#LoginButton").animate({
marginTop: "-40px"
}, 500 );
$('#LoginWelcome').fadeOut(1000);
$('#button-active').fadeIn(1000);
$('#TopLoginForm').fadeIn(1000);
$("#LoginButton").addClass("button");
$("#LoginButton.button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
``` |
11,173,363 | Below is some jQuery code the i wrote to make a simple animation. However I'm SO new to it i have no idea how to condense it down and get baffled by tutorials!
```
<!-- Login Form Div Animation -->
<script type="text/javascript">
$(document).ready(function() {
$('#button-active').hide();
if ($("#LoginButton").hasClass("inactive")) {
$("#TopLoginForm").hide();
} else {
$("#TopLoginForm").show();
}
$("#LoginButton").click( function() {
if ($("#LoginButton").hasClass("inactive")) {
$("#LoginButton").animate({
marginTop: "-40px"
}, 500 );
$("#button-inactive").animate({
opacity: "0"
}, 500 );
$('#button-inactive').remove();
$('#button-active').hide();
$('#button-active').delay(30).fadeIn(1000);
$('#LoginWelcome').delay(0).fadeOut(1000);
$('#TopLoginForm').delay(800).fadeIn(1000);
$("#LoginButton").addClass("button");
$("#LoginButton.button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
</script>
<!-- End Login Form Div Animation -->
```
The live code can be seen on www.trainingthemlive.co.uk/temp its at the top of the page | 2012/06/23 | [
"https://Stackoverflow.com/questions/11173363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477407/"
] | The big thing you can do is avoid running the same query twice, if you know the results haven't changed. Chain or cache the results of your jQuery calls! Instead of:
```
$('#button-active').hide();
$('#button-active').delay(30).fadeIn(1000);
```
you can use the chainability of jQuery objects. In fact, you're already doing it in the second line--why not take the extra step?
```
$('#button-active').hide().delay(30).fadeIn(1000);
```
For readability:
```
$('#button-active')
.hide()
.delay(30)
.fadeIn(1000);
```
But that's not the whole answer. Chaining is concise and great, if you need to do a bunch of stuff to one object or collection in sequence. But if you need to access one object, like `button-active`, at several different points during execution, you should store the query as a variable.
```
var $activeButton = $('#button-active'); // a common convention is to use the $ prefix on variables storing jQuery objects, but this is arguable & optional
```
All together, with a few other efficiency tricks:
```
;$(document).ready(function() {
var inactiveClass = "inactive"
, buttonClass = "button"
, fadeDuration = 1000
, animateDuration = 500
, shortDelay = 30
, longDelay = 800
, loginInactiveButtonAnimateTarget = {
marginTop: -40
}
, inactiveButtonAnimateTarget = {
opacity: 0
}
, loginButtonClickHandler = function() {
document.forms["LoginForm"].submit() // not modifying this, but if this is the "TopLoginForm" then you could do this simpler
}
, $activeButton = $('#button-active').hide() /* the .hide() method chains, so it returns the button-active object */
, $loginButton = $('#LoginButton')
, $topLoginForm = $('#TopLoginForm')
, $loginWelcome = $('#LoginWelcome')
, $inactiveButton = $('#button-inactive')
if ($loginButton.hasClass(inactiveClass)) {
$topLoginForm.hide()
} else {
$topLoginForm.show()
}
$loginButton.click(function() {
if ($loginButton.hasClass(inactiveClass)) {
$loginButton.animate(loginnactiveButtonAnimateTarget, animateDuration)
$inactiveButton.animate(inactiveButtonAnimateTarget, animateDuration).remove()
$activeButton.hide().delay(shortDelay).fadeIn(fadeDuration)
$loginWelcome.delay(0).fadeOut(fadeDuration)
$loginForm.delay(longDelay).fadeIn(fadeDuration)
$loginButton.addClass(buttonClass).click(loginButtonClickHandler)
}
})
});
``` | Best i get can do. You had a lot of repeating functions
```
$(document).ready(function() {
//Start hidden
$('#button-active').hide();
$("#TopLoginForm").hide();
// clicking "login"
$("#LoginButton").click( function() {
if ($("#LoginButton").hasClass("inactive")) {
$("#LoginButton").animate({
marginTop: "-40px"
}, 500 );
$('#LoginWelcome').fadeOut(1000);
$('#button-active').fadeIn(1000);
$('#TopLoginForm').fadeIn(1000);
$("#LoginButton").addClass("button");
$("#LoginButton.button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
``` |
11,173,363 | Below is some jQuery code the i wrote to make a simple animation. However I'm SO new to it i have no idea how to condense it down and get baffled by tutorials!
```
<!-- Login Form Div Animation -->
<script type="text/javascript">
$(document).ready(function() {
$('#button-active').hide();
if ($("#LoginButton").hasClass("inactive")) {
$("#TopLoginForm").hide();
} else {
$("#TopLoginForm").show();
}
$("#LoginButton").click( function() {
if ($("#LoginButton").hasClass("inactive")) {
$("#LoginButton").animate({
marginTop: "-40px"
}, 500 );
$("#button-inactive").animate({
opacity: "0"
}, 500 );
$('#button-inactive').remove();
$('#button-active').hide();
$('#button-active').delay(30).fadeIn(1000);
$('#LoginWelcome').delay(0).fadeOut(1000);
$('#TopLoginForm').delay(800).fadeIn(1000);
$("#LoginButton").addClass("button");
$("#LoginButton.button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
</script>
<!-- End Login Form Div Animation -->
```
The live code can be seen on www.trainingthemlive.co.uk/temp its at the top of the page | 2012/06/23 | [
"https://Stackoverflow.com/questions/11173363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477407/"
] | One big thing regarding optimization in jQuery is knowing that the jQuery function `jQuery()` often aliased as `$()` is indeed a function.
That means that using `$('#some_id')` is actually calling a function which **looks for** the HTML element with the id #some\_id. This is costly performance wise because **looking for** something in the DOM means traversing a tree and checking/ comparing the properties of the nodes.
You should fetch an HTML element from the DOM (with jQuery) and save the reference into a variable. And later on in the script you'll reference that HTML element using the same variable so as not to traverse the DOM again **looking for** the same element.
By using jQuery's `method chaining` approach (as suggested by @meloncholy) you would obtain the same benefits as defining a variable plus a more compact syntax. This is useful for manipulating an object you don't need a reference to later on, so you just stack-up all the manipulations you need done to it.
An example would be:
```
var some_object = $('#some_id');
some_object.hide();
if (some_object.hasClass('some_class')) {
...
```
I can't say that there will be a **noticeable** performance improvement to a script this size. If you had a few hundred lines of jQuery code all abusing the `jQuery()` function and a few hundred HTML elements in the tree and then you refactored the jQuery code as I indicated then you would have a speedup. | Here's my take on simplifying it:
```
<script type="text/javascript">
$(document).ready(function() {
var loginButton = $("#LoginButton");
var topLoginForm = $("#TopLoginForm").toggle(!loginButton.hasClass("inactive"));
loginButton.click( function() {
var this$ = $(this);
if (this$.hasClass("inactive")) {
this$.animate({marginTop: "-40px"}, 500 );
$("#button-inactive").animate({opacity: "0"}, 500, function() {$(this).remove();} );
$('#button-active').hide().delay(30).fadeIn(1000);
$('#LoginWelcome').fadeOut(1000);
topLoginForm.delay(800).fadeIn(1000);
loginButton.addClass("button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
</script>
<!-- End Login Form Div Animation -->
```
Techniques used to simplify it:
* Chain multiple commands on the same jQuery object
* Use toggle(boolean) instead of if/else
* Save any jQuery object to a local variable that is used more than once
* Use completion function on animation so it isn't removed until after the animation finishes
* Remove `.delay(0)` since it doesn't do anything
* Use `this` in the event handler rather than rerunning the current selector |
11,173,363 | Below is some jQuery code the i wrote to make a simple animation. However I'm SO new to it i have no idea how to condense it down and get baffled by tutorials!
```
<!-- Login Form Div Animation -->
<script type="text/javascript">
$(document).ready(function() {
$('#button-active').hide();
if ($("#LoginButton").hasClass("inactive")) {
$("#TopLoginForm").hide();
} else {
$("#TopLoginForm").show();
}
$("#LoginButton").click( function() {
if ($("#LoginButton").hasClass("inactive")) {
$("#LoginButton").animate({
marginTop: "-40px"
}, 500 );
$("#button-inactive").animate({
opacity: "0"
}, 500 );
$('#button-inactive').remove();
$('#button-active').hide();
$('#button-active').delay(30).fadeIn(1000);
$('#LoginWelcome').delay(0).fadeOut(1000);
$('#TopLoginForm').delay(800).fadeIn(1000);
$("#LoginButton").addClass("button");
$("#LoginButton.button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
</script>
<!-- End Login Form Div Animation -->
```
The live code can be seen on www.trainingthemlive.co.uk/temp its at the top of the page | 2012/06/23 | [
"https://Stackoverflow.com/questions/11173363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477407/"
] | The big thing you can do is avoid running the same query twice, if you know the results haven't changed. Chain or cache the results of your jQuery calls! Instead of:
```
$('#button-active').hide();
$('#button-active').delay(30).fadeIn(1000);
```
you can use the chainability of jQuery objects. In fact, you're already doing it in the second line--why not take the extra step?
```
$('#button-active').hide().delay(30).fadeIn(1000);
```
For readability:
```
$('#button-active')
.hide()
.delay(30)
.fadeIn(1000);
```
But that's not the whole answer. Chaining is concise and great, if you need to do a bunch of stuff to one object or collection in sequence. But if you need to access one object, like `button-active`, at several different points during execution, you should store the query as a variable.
```
var $activeButton = $('#button-active'); // a common convention is to use the $ prefix on variables storing jQuery objects, but this is arguable & optional
```
All together, with a few other efficiency tricks:
```
;$(document).ready(function() {
var inactiveClass = "inactive"
, buttonClass = "button"
, fadeDuration = 1000
, animateDuration = 500
, shortDelay = 30
, longDelay = 800
, loginInactiveButtonAnimateTarget = {
marginTop: -40
}
, inactiveButtonAnimateTarget = {
opacity: 0
}
, loginButtonClickHandler = function() {
document.forms["LoginForm"].submit() // not modifying this, but if this is the "TopLoginForm" then you could do this simpler
}
, $activeButton = $('#button-active').hide() /* the .hide() method chains, so it returns the button-active object */
, $loginButton = $('#LoginButton')
, $topLoginForm = $('#TopLoginForm')
, $loginWelcome = $('#LoginWelcome')
, $inactiveButton = $('#button-inactive')
if ($loginButton.hasClass(inactiveClass)) {
$topLoginForm.hide()
} else {
$topLoginForm.show()
}
$loginButton.click(function() {
if ($loginButton.hasClass(inactiveClass)) {
$loginButton.animate(loginnactiveButtonAnimateTarget, animateDuration)
$inactiveButton.animate(inactiveButtonAnimateTarget, animateDuration).remove()
$activeButton.hide().delay(shortDelay).fadeIn(fadeDuration)
$loginWelcome.delay(0).fadeOut(fadeDuration)
$loginForm.delay(longDelay).fadeIn(fadeDuration)
$loginButton.addClass(buttonClass).click(loginButtonClickHandler)
}
})
});
``` | Here's my take on simplifying it:
```
<script type="text/javascript">
$(document).ready(function() {
var loginButton = $("#LoginButton");
var topLoginForm = $("#TopLoginForm").toggle(!loginButton.hasClass("inactive"));
loginButton.click( function() {
var this$ = $(this);
if (this$.hasClass("inactive")) {
this$.animate({marginTop: "-40px"}, 500 );
$("#button-inactive").animate({opacity: "0"}, 500, function() {$(this).remove();} );
$('#button-active').hide().delay(30).fadeIn(1000);
$('#LoginWelcome').fadeOut(1000);
topLoginForm.delay(800).fadeIn(1000);
loginButton.addClass("button").click( function() {
document.forms["LoginForm"].submit();
});
}
});
});
</script>
<!-- End Login Form Div Animation -->
```
Techniques used to simplify it:
* Chain multiple commands on the same jQuery object
* Use toggle(boolean) instead of if/else
* Save any jQuery object to a local variable that is used more than once
* Use completion function on animation so it isn't removed until after the animation finishes
* Remove `.delay(0)` since it doesn't do anything
* Use `this` in the event handler rather than rerunning the current selector |
13,723,536 | We want to create logical folders within a bucket but not more than for 100 buckets. Assuming that we only have only one AWS account, we want to distribute the uploaded documents among those 100 buckets. What would be the best practice to enforce a IAM policy for all buckets, so that having multiple users, only the document creator, may view/delete the uploaded document?
Tks. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13723536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm not sure that I fully understand your use case. Why do you want to distribute your buckets among your users?
Regarding the best practices for using IAM for "home directory" for a user, you can find in [AWS Docs](http://docs.amazonwebservices.com/AmazonS3/latest/dev/UsingIAMPolicies.html):
```
{
"Statement":[{
"Effect":"Allow",
"Action":["s3:PutObject","s3:GetObject","s3:GetObjectVersion",
"s3:DeleteObject","s3:DeleteObjectVersion"],
"Resource":"arn:aws:s3:::my_bucket/home/user_name/*"
}
]
}
``` | As [mentioned by @Guy](https://stackoverflow.com/a/13747567/1037948), folders per user is better than buckets per user, but in either case you can use the [policy variable](http://docs.aws.amazon.com/IAM/latest/UserGuide/PolicyVariables.html) `${aws:username}` for one rule rather than multiple rules. See [example in their documentation](http://docs.aws.amazon.com/IAM/latest/UserGuide/ExampleIAMPolicies.html#iampolicy-example-allDDBaccess).
In your case, I think you could put it in the bucket arn like:
```
{
"Statement":[{
"Effect":"Allow",
"Action":["s3:*"],
"Resource":"arn:aws:s3:::bucket-for-${aws:username}/*"
}]
}
``` |
8,540 | Presumably people in Okinawa didn't walk around barefoot. If the original purpose of karate is self-defense, wouldn't it make more sense to train in similar clothing to what you'd be wearing if you were attacked? | 2018/09/07 | [
"https://martialarts.stackexchange.com/questions/8540",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/9320/"
] | Whilst I cannot answer the origins, there are many reasons why I still instruct barefoot to a barefoot class.
1. Safety - when we involve blocks of kicks - any design in the shoes worn, hard plastics or metal especially, could damage the blocker in an inconsistent way (making it harder for the blocker to build confidence)
2. Grip is consistent - whilst shoes could be soled with any material - the sole of my foot is the same material as all my students - this means the floor is slippery to everyone or no-one
3. Weight - swinging your foot around - especially high from the ground - requires strength and flexibility, add the weight of a shoe and you increase the likelihood of loss of control. I have seen many people tear muscles whilst warming up wearing ankle weights or similar.
4. Fashion - not seriously - but part of martial arts is looking and acting as a group - we all wear the same outfit as we don our 'soldier' mentality. Shoes would be an individual distraction unless they became part of the attire (like sparring kit sort of has).
I suspect many of the safety aspects from above are why barefoot training is so wide spread in the MA community.
In response to training in attire similar to when you would need to defend yourself - this is also difficult - it is probably most likely we get attacked at night, in an unlit area, in the rain, on gravel.
It would be practically impossible to teach a class in those conditions - we make it safe before we make it real. | Some kicking styles do use shoes: in [Savate](https://en.wikipedia.org/wiki/Savate), shoes are worn in training and sparing.
In Japanese culture, wearing shoes indoor is considered impolite and dirty. Thus, shoes are taken off at the front door. All dojo are indoor buildings thus I can safely assume that shoes would not be worn there. An array of socks and indoor slippers do exists but they are not terribly practical for physical activities. They do not drain sweat very well becoming slippery and dangerous.
While I like the primary sources to say this is the reasons most Japanese martial arts train bare foot, it is a possible explanation.
In addition, dogi are under vestments worn as "exercise cloths". We rarely, if ever, train in street cloths. Maybe we should but generally sport wear is just more practical. |
8,540 | Presumably people in Okinawa didn't walk around barefoot. If the original purpose of karate is self-defense, wouldn't it make more sense to train in similar clothing to what you'd be wearing if you were attacked? | 2018/09/07 | [
"https://martialarts.stackexchange.com/questions/8540",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/9320/"
] | In Japanese styles, it is unquestionably about cleanliness. They don't wear outside shoes in one's home, and zori are used for that purpose. But zori make it somewhat difficult to train in, and as well, expensive tatami mats do not wear well with shoes worn. So, they train barefoot. I've seen many a Japanese instructor painstakingly give the hairy eyeball to a repairman walking over the tatami mat with his boots on to fix the plumbing, a ceiling leak, or some electrical thing; and when the ordeal was over, have students wash down the mat whereupon the miserable heathen stepped.
In Korean styles, there's several answers. One answer is that they don't train barefoot - they wear light sneakers built for the purpose of training. However, with many taekwondo schools, they do lots of jump and spin kicks, and so, a mat is needed to protect the students from hard landings; these mats do not wear well when shoes are worn. As a result, instructors are usually the ones who wear the training sneakers - not the students. However, those training sneakers are made so as not to be so "grabby" to the mats, and occasionally, you find students training in them. But most mats are made for the human foot - not shoes - and so, the grabbiness of a mat is reduced when barefoot compared to shoes.
In other Korean styles, such as Yudo and Kumdo, and derivatives, their customs come directly from their Japanese style counterparts - Judo and Kendo, respectively, and so, they're barefoot. It seems curious to me that Kendo/Kumdo students do not wear shoes, despite that they rarely ever lift the foot off the floor, and, they usually compete on bare wood flooring - perfect for shoes.
In styles where head kicks are allowed, no one wants to get a face full of shoe (not that a sweaty sole is any better). But there is a safety and/or a comfort issue.
I can also say this, having competed in many a tournament hosted in a high school gymnasium. Such places are ripe for dust balls, dirt, parking lot pebbles, and the occasional spilled orange soda and dropped hot dog - none of which is comfortable to step in. Trying to compete on such a gymnasium floor is very difficult - the dust can create a slippery surface; conversely, a well-managed floor which has just been lacquered can be very grabby on the foot. Training shoes can meet the middle ground. Also, I've competed in hotels. They have carpets, but you never know if the wedding party the night before had a mishap whereupon someone broke a champagne glass. I always make it a practice to wear training shoes on hotel flooring for just this reason. As a result, for me and may like me, training for a tournament on a gym floor or a hotel means wearing shoes, so for tournament season, always train with shoes in the dojang.
Keep in mind that we train for what we expect to encounter. If we are training for sport, then we have different expectations than for practicing for self-defense. In practicing for self-defense, I think it unconscionable not to practice with street shoes at least once in a while - noting the wear and tear on a training mat, there can always be occasional practice on a grass, beach, or asphalt surface. | Whilst I cannot answer the origins, there are many reasons why I still instruct barefoot to a barefoot class.
1. Safety - when we involve blocks of kicks - any design in the shoes worn, hard plastics or metal especially, could damage the blocker in an inconsistent way (making it harder for the blocker to build confidence)
2. Grip is consistent - whilst shoes could be soled with any material - the sole of my foot is the same material as all my students - this means the floor is slippery to everyone or no-one
3. Weight - swinging your foot around - especially high from the ground - requires strength and flexibility, add the weight of a shoe and you increase the likelihood of loss of control. I have seen many people tear muscles whilst warming up wearing ankle weights or similar.
4. Fashion - not seriously - but part of martial arts is looking and acting as a group - we all wear the same outfit as we don our 'soldier' mentality. Shoes would be an individual distraction unless they became part of the attire (like sparring kit sort of has).
I suspect many of the safety aspects from above are why barefoot training is so wide spread in the MA community.
In response to training in attire similar to when you would need to defend yourself - this is also difficult - it is probably most likely we get attacked at night, in an unlit area, in the rain, on gravel.
It would be practically impossible to teach a class in those conditions - we make it safe before we make it real. |
8,540 | Presumably people in Okinawa didn't walk around barefoot. If the original purpose of karate is self-defense, wouldn't it make more sense to train in similar clothing to what you'd be wearing if you were attacked? | 2018/09/07 | [
"https://martialarts.stackexchange.com/questions/8540",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/9320/"
] | This answer does not directly address the karate aspect, but I think it is still relevant, as Collett89 has pointed out in his comment.
The development of your feet and legs depends upon the environment you put them in. Training barefoot forces you to use your feet to a greater degree than when in shoes. For some people and their shoes, this is a much greater degree.
This excerpt is from *Higher Judo: Ground Work* by Moshe Feldenkrais published by Frederick Warne & Co., Ltd. London, 1952, p18. Feldenkrais trained with Jigaro Kano, the founder of judo.
>
> First of all Judo is practised with bare feet. Many
> people have never made any but the most primitive use
> of their feet, with the result that the only use and idea
> associated with them, is that of a plate-like support
> to the body. This being the only use made of the feet
> for many years on end, the muscles are most of the time
> maintained in a fixed state of contraction-precisely
> the one that makes the feet fit for the service demanded
> of them. In extreme cases the exclusion of other patterns is so complete, that the feet become frozen in the
> flat, plate-like position and are almost useless for any
> other purpose than motionless standing. When required
> to change shape, that is, to alter the pattern of contraction of the different muscles and consequently the relative
> configuration of the numerous bones of the feet, some
> muscles are too weak and do not contract powerfully
> enough, other muscles and ligaments are too short and
> their stretching to the unaccustomed length is painful.
> Such persons are forced to assume queer positions of
> the legs, pelvis and the rest of the body to make movement possible while maintaining the feet in the accustomed way. They tire more quickly than other people,
> become irritable, their movements lack swing and ease
> and they are peculiar in many other ways.
>
>
>
I have personally met people who use their feet as "plate-like support to the body". I find this description still apt today. | Some kicking styles do use shoes: in [Savate](https://en.wikipedia.org/wiki/Savate), shoes are worn in training and sparing.
In Japanese culture, wearing shoes indoor is considered impolite and dirty. Thus, shoes are taken off at the front door. All dojo are indoor buildings thus I can safely assume that shoes would not be worn there. An array of socks and indoor slippers do exists but they are not terribly practical for physical activities. They do not drain sweat very well becoming slippery and dangerous.
While I like the primary sources to say this is the reasons most Japanese martial arts train bare foot, it is a possible explanation.
In addition, dogi are under vestments worn as "exercise cloths". We rarely, if ever, train in street cloths. Maybe we should but generally sport wear is just more practical. |
8,540 | Presumably people in Okinawa didn't walk around barefoot. If the original purpose of karate is self-defense, wouldn't it make more sense to train in similar clothing to what you'd be wearing if you were attacked? | 2018/09/07 | [
"https://martialarts.stackexchange.com/questions/8540",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/9320/"
] | In Japanese styles, it is unquestionably about cleanliness. They don't wear outside shoes in one's home, and zori are used for that purpose. But zori make it somewhat difficult to train in, and as well, expensive tatami mats do not wear well with shoes worn. So, they train barefoot. I've seen many a Japanese instructor painstakingly give the hairy eyeball to a repairman walking over the tatami mat with his boots on to fix the plumbing, a ceiling leak, or some electrical thing; and when the ordeal was over, have students wash down the mat whereupon the miserable heathen stepped.
In Korean styles, there's several answers. One answer is that they don't train barefoot - they wear light sneakers built for the purpose of training. However, with many taekwondo schools, they do lots of jump and spin kicks, and so, a mat is needed to protect the students from hard landings; these mats do not wear well when shoes are worn. As a result, instructors are usually the ones who wear the training sneakers - not the students. However, those training sneakers are made so as not to be so "grabby" to the mats, and occasionally, you find students training in them. But most mats are made for the human foot - not shoes - and so, the grabbiness of a mat is reduced when barefoot compared to shoes.
In other Korean styles, such as Yudo and Kumdo, and derivatives, their customs come directly from their Japanese style counterparts - Judo and Kendo, respectively, and so, they're barefoot. It seems curious to me that Kendo/Kumdo students do not wear shoes, despite that they rarely ever lift the foot off the floor, and, they usually compete on bare wood flooring - perfect for shoes.
In styles where head kicks are allowed, no one wants to get a face full of shoe (not that a sweaty sole is any better). But there is a safety and/or a comfort issue.
I can also say this, having competed in many a tournament hosted in a high school gymnasium. Such places are ripe for dust balls, dirt, parking lot pebbles, and the occasional spilled orange soda and dropped hot dog - none of which is comfortable to step in. Trying to compete on such a gymnasium floor is very difficult - the dust can create a slippery surface; conversely, a well-managed floor which has just been lacquered can be very grabby on the foot. Training shoes can meet the middle ground. Also, I've competed in hotels. They have carpets, but you never know if the wedding party the night before had a mishap whereupon someone broke a champagne glass. I always make it a practice to wear training shoes on hotel flooring for just this reason. As a result, for me and may like me, training for a tournament on a gym floor or a hotel means wearing shoes, so for tournament season, always train with shoes in the dojang.
Keep in mind that we train for what we expect to encounter. If we are training for sport, then we have different expectations than for practicing for self-defense. In practicing for self-defense, I think it unconscionable not to practice with street shoes at least once in a while - noting the wear and tear on a training mat, there can always be occasional practice on a grass, beach, or asphalt surface. | This answer does not directly address the karate aspect, but I think it is still relevant, as Collett89 has pointed out in his comment.
The development of your feet and legs depends upon the environment you put them in. Training barefoot forces you to use your feet to a greater degree than when in shoes. For some people and their shoes, this is a much greater degree.
This excerpt is from *Higher Judo: Ground Work* by Moshe Feldenkrais published by Frederick Warne & Co., Ltd. London, 1952, p18. Feldenkrais trained with Jigaro Kano, the founder of judo.
>
> First of all Judo is practised with bare feet. Many
> people have never made any but the most primitive use
> of their feet, with the result that the only use and idea
> associated with them, is that of a plate-like support
> to the body. This being the only use made of the feet
> for many years on end, the muscles are most of the time
> maintained in a fixed state of contraction-precisely
> the one that makes the feet fit for the service demanded
> of them. In extreme cases the exclusion of other patterns is so complete, that the feet become frozen in the
> flat, plate-like position and are almost useless for any
> other purpose than motionless standing. When required
> to change shape, that is, to alter the pattern of contraction of the different muscles and consequently the relative
> configuration of the numerous bones of the feet, some
> muscles are too weak and do not contract powerfully
> enough, other muscles and ligaments are too short and
> their stretching to the unaccustomed length is painful.
> Such persons are forced to assume queer positions of
> the legs, pelvis and the rest of the body to make movement possible while maintaining the feet in the accustomed way. They tire more quickly than other people,
> become irritable, their movements lack swing and ease
> and they are peculiar in many other ways.
>
>
>
I have personally met people who use their feet as "plate-like support to the body". I find this description still apt today. |
8,540 | Presumably people in Okinawa didn't walk around barefoot. If the original purpose of karate is self-defense, wouldn't it make more sense to train in similar clothing to what you'd be wearing if you were attacked? | 2018/09/07 | [
"https://martialarts.stackexchange.com/questions/8540",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/9320/"
] | In Japanese styles, it is unquestionably about cleanliness. They don't wear outside shoes in one's home, and zori are used for that purpose. But zori make it somewhat difficult to train in, and as well, expensive tatami mats do not wear well with shoes worn. So, they train barefoot. I've seen many a Japanese instructor painstakingly give the hairy eyeball to a repairman walking over the tatami mat with his boots on to fix the plumbing, a ceiling leak, or some electrical thing; and when the ordeal was over, have students wash down the mat whereupon the miserable heathen stepped.
In Korean styles, there's several answers. One answer is that they don't train barefoot - they wear light sneakers built for the purpose of training. However, with many taekwondo schools, they do lots of jump and spin kicks, and so, a mat is needed to protect the students from hard landings; these mats do not wear well when shoes are worn. As a result, instructors are usually the ones who wear the training sneakers - not the students. However, those training sneakers are made so as not to be so "grabby" to the mats, and occasionally, you find students training in them. But most mats are made for the human foot - not shoes - and so, the grabbiness of a mat is reduced when barefoot compared to shoes.
In other Korean styles, such as Yudo and Kumdo, and derivatives, their customs come directly from their Japanese style counterparts - Judo and Kendo, respectively, and so, they're barefoot. It seems curious to me that Kendo/Kumdo students do not wear shoes, despite that they rarely ever lift the foot off the floor, and, they usually compete on bare wood flooring - perfect for shoes.
In styles where head kicks are allowed, no one wants to get a face full of shoe (not that a sweaty sole is any better). But there is a safety and/or a comfort issue.
I can also say this, having competed in many a tournament hosted in a high school gymnasium. Such places are ripe for dust balls, dirt, parking lot pebbles, and the occasional spilled orange soda and dropped hot dog - none of which is comfortable to step in. Trying to compete on such a gymnasium floor is very difficult - the dust can create a slippery surface; conversely, a well-managed floor which has just been lacquered can be very grabby on the foot. Training shoes can meet the middle ground. Also, I've competed in hotels. They have carpets, but you never know if the wedding party the night before had a mishap whereupon someone broke a champagne glass. I always make it a practice to wear training shoes on hotel flooring for just this reason. As a result, for me and may like me, training for a tournament on a gym floor or a hotel means wearing shoes, so for tournament season, always train with shoes in the dojang.
Keep in mind that we train for what we expect to encounter. If we are training for sport, then we have different expectations than for practicing for self-defense. In practicing for self-defense, I think it unconscionable not to practice with street shoes at least once in a while - noting the wear and tear on a training mat, there can always be occasional practice on a grass, beach, or asphalt surface. | Some kicking styles do use shoes: in [Savate](https://en.wikipedia.org/wiki/Savate), shoes are worn in training and sparing.
In Japanese culture, wearing shoes indoor is considered impolite and dirty. Thus, shoes are taken off at the front door. All dojo are indoor buildings thus I can safely assume that shoes would not be worn there. An array of socks and indoor slippers do exists but they are not terribly practical for physical activities. They do not drain sweat very well becoming slippery and dangerous.
While I like the primary sources to say this is the reasons most Japanese martial arts train bare foot, it is a possible explanation.
In addition, dogi are under vestments worn as "exercise cloths". We rarely, if ever, train in street cloths. Maybe we should but generally sport wear is just more practical. |
35,081,658 | I am using Jenkins for continuous build for java projects and i am using deploy plugin,it takes a war/ear file and deploys that to a running remote application server at the end of a build successful.
I am stuck at one scenario of deployment,if my new build fails then we have to push rollback version of build to a tomcat,i am using deploy plugin but there is no such options.
Could you please help me which plugin i have to use to push rollback version of a build on Tomcat in case of unstable build using Jenkins. | 2016/01/29 | [
"https://Stackoverflow.com/questions/35081658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2311960/"
] | This CSS causes the issue:
```
@media screen and (max-width: 800px)
.title {
width: 440px;
}
```
At VERY small screen sizes the 440px will exceed the screen. Try 90% or something instead. | you apply fix `width` change all `width` to media query
Example
```
.footer {
margin:0 auto;
width: 1024px;
height: 350px;
}
c2leftimage {
margin: 0 auto;
width: 453px;
}
.c2rightimage {
margin: 0 auto;
width: 453px;
height: 453px;
}
``` |
35,081,658 | I am using Jenkins for continuous build for java projects and i am using deploy plugin,it takes a war/ear file and deploys that to a running remote application server at the end of a build successful.
I am stuck at one scenario of deployment,if my new build fails then we have to push rollback version of build to a tomcat,i am using deploy plugin but there is no such options.
Could you please help me which plugin i have to use to push rollback version of a build on Tomcat in case of unstable build using Jenkins. | 2016/01/29 | [
"https://Stackoverflow.com/questions/35081658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2311960/"
] | Fixed widths are your problem(of images or texts) - try to have it in percent, not fixed(in pixels)...at least for device widths smaller that 500px or so. | you apply fix `width` change all `width` to media query
Example
```
.footer {
margin:0 auto;
width: 1024px;
height: 350px;
}
c2leftimage {
margin: 0 auto;
width: 453px;
}
.c2rightimage {
margin: 0 auto;
width: 453px;
height: 453px;
}
``` |
35,081,658 | I am using Jenkins for continuous build for java projects and i am using deploy plugin,it takes a war/ear file and deploys that to a running remote application server at the end of a build successful.
I am stuck at one scenario of deployment,if my new build fails then we have to push rollback version of build to a tomcat,i am using deploy plugin but there is no such options.
Could you please help me which plugin i have to use to push rollback version of a build on Tomcat in case of unstable build using Jenkins. | 2016/01/29 | [
"https://Stackoverflow.com/questions/35081658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2311960/"
] | This CSS causes the issue:
```
@media screen and (max-width: 800px)
.title {
width: 440px;
}
```
At VERY small screen sizes the 440px will exceed the screen. Try 90% or something instead. | As i have seen you have add width in PX you have used only one media query
```
@media screen and (max-width: 800px)
```
try to add more query and rest all widths and also you need to make images responsive to do for images add these properties
img{display: block;
max-width:100%;
height: auto;} |
35,081,658 | I am using Jenkins for continuous build for java projects and i am using deploy plugin,it takes a war/ear file and deploys that to a running remote application server at the end of a build successful.
I am stuck at one scenario of deployment,if my new build fails then we have to push rollback version of build to a tomcat,i am using deploy plugin but there is no such options.
Could you please help me which plugin i have to use to push rollback version of a build on Tomcat in case of unstable build using Jenkins. | 2016/01/29 | [
"https://Stackoverflow.com/questions/35081658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2311960/"
] | Fixed widths are your problem(of images or texts) - try to have it in percent, not fixed(in pixels)...at least for device widths smaller that 500px or so. | As i have seen you have add width in PX you have used only one media query
```
@media screen and (max-width: 800px)
```
try to add more query and rest all widths and also you need to make images responsive to do for images add these properties
img{display: block;
max-width:100%;
height: auto;} |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Note that
$$\begin{align}
\int\_1^{2^n}\frac{1}{u}\,du&=\int\_1^2\frac{1}{u}\,du+\int\_2^4\frac{1}{u}\,du+\int\_4^8\frac{1}{u}\,du+\cdots +\int\_{2^{n-1}}^{2^n}\frac{1}{u}\,du\\\\
&\ge \left(\frac{1}{1}\right)\left(2-1\right)+\left(\frac{1}{2}\right)\left(4-2\right)+\left(\frac{1}{4}\right)\left(8-4\right)+\cdots +\left(\frac{1}{2^{n-1}}\right)\left(2^n-2^{n-1}\right)\\\\
&=1+1+1+\cdots +1\\\\
&=n
\end{align}$$
Therefore, we find that
$$\int\_1^{2^n}\frac{1}{u}\,du\ge n \to \infty \,\,\text{as}\,\,n\to \infty$$
And we are done! | $$\int\_{ac}^{bc}\frac{dx}{x}=\int\_{cx=ac}^{cx=bc}\frac{d(cx)}{cx}=\int\_{a}^{b}\frac{dx}{x}$$
$$\therefore\int\_{1}^{\infty}\frac{dx}{x}=\sum\_{n=0}^\infty\int\_{2^n}^{2^{n+1}}\frac{dx}{x}=\\
\sum\_{n=0}^\infty\int\_{1}^{2}\frac{dx}{x}=+\infty$$ |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Let $x = y/2.$ Then
$$\int\_1^\infty\frac{dx}{x} = \int\_2^\infty\frac{dy}{y}.$$
That is a contradiction unless both integrals equal $\infty.$ | $$\int\_{ac}^{bc}\frac{dx}{x}=\int\_{cx=ac}^{cx=bc}\frac{d(cx)}{cx}=\int\_{a}^{b}\frac{dx}{x}$$
$$\therefore\int\_{1}^{\infty}\frac{dx}{x}=\sum\_{n=0}^\infty\int\_{2^n}^{2^{n+1}}\frac{dx}{x}=\\
\sum\_{n=0}^\infty\int\_{1}^{2}\frac{dx}{x}=+\infty$$ |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Maybe this one. Change variables $x=t^{1/2}, dx = (1/2)t^{-1/2}\,dt$.
Then
$$
\int\_1^\infty \frac{1}{x}\;dx =
\int\_1^\infty \frac{1}{t^{1/2}}\;\frac{t^{-1/2}}{2}\;dt
= \frac{1}{2}\int\_1^\infty \frac{1}{t}\;dt
$$
Now $\int\_1^\infty \frac{dx}{x} > \int\_1^2 \frac{dx}{2} = \frac{1}{2} > 0$. So conclude it is $+\infty$.
Or, if we are allowed properties of $e^x$:
Substitute $x=e^t, dx=e^t\,dt$ so
$$
\int\_1^\infty \frac{1}{x}\;dx = \int\_0^\infty \frac{1}{e^t}\;e^t\;dt
=\int\_0^\infty dt = \infty.
$$ | Note that
$$\begin{align}
\int\_1^{2^n}\frac{1}{u}\,du&=\int\_1^2\frac{1}{u}\,du+\int\_2^4\frac{1}{u}\,du+\int\_4^8\frac{1}{u}\,du+\cdots +\int\_{2^{n-1}}^{2^n}\frac{1}{u}\,du\\\\
&\ge \left(\frac{1}{1}\right)\left(2-1\right)+\left(\frac{1}{2}\right)\left(4-2\right)+\left(\frac{1}{4}\right)\left(8-4\right)+\cdots +\left(\frac{1}{2^{n-1}}\right)\left(2^n-2^{n-1}\right)\\\\
&=1+1+1+\cdots +1\\\\
&=n
\end{align}$$
Therefore, we find that
$$\int\_1^{2^n}\frac{1}{u}\,du\ge n \to \infty \,\,\text{as}\,\,n\to \infty$$
And we are done! |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | This was pointed out in the comments above, so since no one else wrote this in an answer, I will.
You have (by definition)
$$\begin{align}
\int\_1^\infty \frac{1}{x}\; dx
&= \lim\_{t\to \infty}\int\_1^t \frac{1}{x}\; dx \\
&= \lim\_{t\to \infty} \ln(x)\large]\_1^t \\
&= \lim\_{t\to \infty} \ln(t) - \ln(1) \\
&= \lim\_{t\to \infty} \ln(t) \\
&= \infty.
\end{align}
$$ | $$\int\_{ac}^{bc}\frac{dx}{x}=\int\_{cx=ac}^{cx=bc}\frac{d(cx)}{cx}=\int\_{a}^{b}\frac{dx}{x}$$
$$\therefore\int\_{1}^{\infty}\frac{dx}{x}=\sum\_{n=0}^\infty\int\_{2^n}^{2^{n+1}}\frac{dx}{x}=\\
\sum\_{n=0}^\infty\int\_{1}^{2}\frac{dx}{x}=+\infty$$ |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Since
$$
\int\_a^{2a}\frac{\mathrm{d}x}x=\log(2)
$$
we have that
$$
\begin{align}
\int\_1^{2^n}\frac{\mathrm{d}x}x
&=\int\_1^2\frac{\mathrm{d}x}x+\int\_2^4\frac{\mathrm{d}x}x+\cdots+\int\_{2^{n-1}}^{2^n}\frac{\mathrm{d}x}x\\[6pt]
&=n\log(2)
\end{align}
$$
Let $n\to\infty$. | Note that
$$\begin{align}
\int\_1^{2^n}\frac{1}{u}\,du&=\int\_1^2\frac{1}{u}\,du+\int\_2^4\frac{1}{u}\,du+\int\_4^8\frac{1}{u}\,du+\cdots +\int\_{2^{n-1}}^{2^n}\frac{1}{u}\,du\\\\
&\ge \left(\frac{1}{1}\right)\left(2-1\right)+\left(\frac{1}{2}\right)\left(4-2\right)+\left(\frac{1}{4}\right)\left(8-4\right)+\cdots +\left(\frac{1}{2^{n-1}}\right)\left(2^n-2^{n-1}\right)\\\\
&=1+1+1+\cdots +1\\\\
&=n
\end{align}$$
Therefore, we find that
$$\int\_1^{2^n}\frac{1}{u}\,du\ge n \to \infty \,\,\text{as}\,\,n\to \infty$$
And we are done! |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Since
$$
\int\_a^{2a}\frac{\mathrm{d}x}x=\log(2)
$$
we have that
$$
\begin{align}
\int\_1^{2^n}\frac{\mathrm{d}x}x
&=\int\_1^2\frac{\mathrm{d}x}x+\int\_2^4\frac{\mathrm{d}x}x+\cdots+\int\_{2^{n-1}}^{2^n}\frac{\mathrm{d}x}x\\[6pt]
&=n\log(2)
\end{align}
$$
Let $n\to\infty$. | $$\int\_{ac}^{bc}\frac{dx}{x}=\int\_{cx=ac}^{cx=bc}\frac{d(cx)}{cx}=\int\_{a}^{b}\frac{dx}{x}$$
$$\therefore\int\_{1}^{\infty}\frac{dx}{x}=\sum\_{n=0}^\infty\int\_{2^n}^{2^{n+1}}\frac{dx}{x}=\\
\sum\_{n=0}^\infty\int\_{1}^{2}\frac{dx}{x}=+\infty$$ |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Maybe this one. Change variables $x=t^{1/2}, dx = (1/2)t^{-1/2}\,dt$.
Then
$$
\int\_1^\infty \frac{1}{x}\;dx =
\int\_1^\infty \frac{1}{t^{1/2}}\;\frac{t^{-1/2}}{2}\;dt
= \frac{1}{2}\int\_1^\infty \frac{1}{t}\;dt
$$
Now $\int\_1^\infty \frac{dx}{x} > \int\_1^2 \frac{dx}{2} = \frac{1}{2} > 0$. So conclude it is $+\infty$.
Or, if we are allowed properties of $e^x$:
Substitute $x=e^t, dx=e^t\,dt$ so
$$
\int\_1^\infty \frac{1}{x}\;dx = \int\_0^\infty \frac{1}{e^t}\;e^t\;dt
=\int\_0^\infty dt = \infty.
$$ | $$\int\_{ac}^{bc}\frac{dx}{x}=\int\_{cx=ac}^{cx=bc}\frac{d(cx)}{cx}=\int\_{a}^{b}\frac{dx}{x}$$
$$\therefore\int\_{1}^{\infty}\frac{dx}{x}=\sum\_{n=0}^\infty\int\_{2^n}^{2^{n+1}}\frac{dx}{x}=\\
\sum\_{n=0}^\infty\int\_{1}^{2}\frac{dx}{x}=+\infty$$ |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Let $x = y/2.$ Then
$$\int\_1^\infty\frac{dx}{x} = \int\_2^\infty\frac{dy}{y}.$$
That is a contradiction unless both integrals equal $\infty.$ | Note that
$$\begin{align}
\int\_1^{2^n}\frac{1}{u}\,du&=\int\_1^2\frac{1}{u}\,du+\int\_2^4\frac{1}{u}\,du+\int\_4^8\frac{1}{u}\,du+\cdots +\int\_{2^{n-1}}^{2^n}\frac{1}{u}\,du\\\\
&\ge \left(\frac{1}{1}\right)\left(2-1\right)+\left(\frac{1}{2}\right)\left(4-2\right)+\left(\frac{1}{4}\right)\left(8-4\right)+\cdots +\left(\frac{1}{2^{n-1}}\right)\left(2^n-2^{n-1}\right)\\\\
&=1+1+1+\cdots +1\\\\
&=n
\end{align}$$
Therefore, we find that
$$\int\_1^{2^n}\frac{1}{u}\,du\ge n \to \infty \,\,\text{as}\,\,n\to \infty$$
And we are done! |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Let $x = y/2.$ Then
$$\int\_1^\infty\frac{dx}{x} = \int\_2^\infty\frac{dy}{y}.$$
That is a contradiction unless both integrals equal $\infty.$ | Maybe this one. Change variables $x=t^{1/2}, dx = (1/2)t^{-1/2}\,dt$.
Then
$$
\int\_1^\infty \frac{1}{x}\;dx =
\int\_1^\infty \frac{1}{t^{1/2}}\;\frac{t^{-1/2}}{2}\;dt
= \frac{1}{2}\int\_1^\infty \frac{1}{t}\;dt
$$
Now $\int\_1^\infty \frac{dx}{x} > \int\_1^2 \frac{dx}{2} = \frac{1}{2} > 0$. So conclude it is $+\infty$.
Or, if we are allowed properties of $e^x$:
Substitute $x=e^t, dx=e^t\,dt$ so
$$
\int\_1^\infty \frac{1}{x}\;dx = \int\_0^\infty \frac{1}{e^t}\;e^t\;dt
=\int\_0^\infty dt = \infty.
$$ |
1,363,900 | I was reading up on the harmonic series,
$H=\sum\limits\_{n=1}^\infty\frac1n$, on Wikipedia, and it's divergent, as can be shown by a comparison test using the fact that
$\begin{aligned}H&=1+\frac12+\left(\frac13+\frac14\right)+\left(\frac15+\frac16+\frac17+\frac18\right)+\cdots\\&\geq 1+\frac12+\left(\frac14+\frac14\right)+\left(\frac18+\frac18+\frac18+\frac18\right)+\cdots\\&=1+\frac12+\frac12+\frac12+\cdots,\end{aligned}$
where the expression on the right clearly diverges.
But after this proof idea was given, the proof idea using the integral test was given. I understand why $H\_n=\sum\_{k=1}^n\frac1k\geq \int\_1^n \frac{dx}x$, but how is it shown that $\int\_1^\infty \frac{dx}x$ is divergent without using the harmonic series in the following way:
$H\_n-1\leq \int\_1^n \frac{dx}x\leq H\_n$, and then using this in the following way, by comparison test:
$\lim\limits\_{n\to\infty}H\_n=\infty\implies\lim\limits\_{n\to\infty}(H\_n-1)=\infty\implies\lim\limits\_{n\to\infty}\int\_1^n \frac{dx}x=\infty$.
So to summarize, is there a way to prove that $\int\_1^\infty \frac{dx}x$ without using the fact that $H$ diverges? | 2015/07/16 | [
"https://math.stackexchange.com/questions/1363900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215489/"
] | Let $x = y/2.$ Then
$$\int\_1^\infty\frac{dx}{x} = \int\_2^\infty\frac{dy}{y}.$$
That is a contradiction unless both integrals equal $\infty.$ | This was pointed out in the comments above, so since no one else wrote this in an answer, I will.
You have (by definition)
$$\begin{align}
\int\_1^\infty \frac{1}{x}\; dx
&= \lim\_{t\to \infty}\int\_1^t \frac{1}{x}\; dx \\
&= \lim\_{t\to \infty} \ln(x)\large]\_1^t \\
&= \lim\_{t\to \infty} \ln(t) - \ln(1) \\
&= \lim\_{t\to \infty} \ln(t) \\
&= \infty.
\end{align}
$$ |
60,173,826 | Got this API response:
```
...
"campaigns": [
{
"id": 2,
"name": {
"en": "Example Campaign",
"de": "Beispiel Kampagne"
},
"targetagegroup": null,
...
```
I'm decoding into:
```swift
class Campaign: Codable {
var id: Int?
var name: [String:String]?
var targetagegroup: String?
...
}
```
All works fine.
But with this response:
```
...
"someproperty": null,
"slogan": {
"en": "foo",
"de": "bar"
},
"someotherproperty": null,
...
```
When decoding into:
```swift
class User: Codable {
...
var someproperty: String?
var slogan: [String:String]?
var someotherproperty: String?
...
}
```
I'm getting the following error:
```
typeMismatch(Swift.Dictionary<Swift.String, Swift.String>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "detailresponse", intValue: nil), CodingKeys(stringValue: "element", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "participants", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "slogan", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, String> but found a string/data instead.", underlyingError: nil))
```
Not sure why decoding a User gives me issues with when decoding a Campaign doesn't. | 2020/02/11 | [
"https://Stackoverflow.com/questions/60173826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12596139/"
] | Your second object doesn't appear to be valid JSON.
```
{
"someproperty": null,
"slogan": {
"en": "foo",
"de": "bar"
},
"someotherproperty": null,
}
```
That decodes for me just fine. | Like I said in my comment, i think you receive a plain string into your "slogan" property in your JSON result. And not an object like you describe.
I tried in a playground :
```swift
struct Campain: Codable {
var slogan: [String:String]?
}
let json = "{\"slogan\": \"\"}"
let campain = JSONDecoder().decode(Campain.self, from: json.data(using: .utf8)!)
print(campain)
```
Gives me the error :
```
DecodingError
▿ typeMismatch : 2 elements
- .0 : Swift.Dictionary<Swift.String, Swift.String>
▿ .1 : Context
▿ codingPath : 1 element
- 0 : CodingKeys(stringValue: "slogan", intValue: nil)
- debugDescription : "Expected to decode Dictionary<String, String> but found a string/data instead."
- underlyingError : nil
```
If i put a real object in the JSON (same as your example), it works. |
60,173,826 | Got this API response:
```
...
"campaigns": [
{
"id": 2,
"name": {
"en": "Example Campaign",
"de": "Beispiel Kampagne"
},
"targetagegroup": null,
...
```
I'm decoding into:
```swift
class Campaign: Codable {
var id: Int?
var name: [String:String]?
var targetagegroup: String?
...
}
```
All works fine.
But with this response:
```
...
"someproperty": null,
"slogan": {
"en": "foo",
"de": "bar"
},
"someotherproperty": null,
...
```
When decoding into:
```swift
class User: Codable {
...
var someproperty: String?
var slogan: [String:String]?
var someotherproperty: String?
...
}
```
I'm getting the following error:
```
typeMismatch(Swift.Dictionary<Swift.String, Swift.String>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "detailresponse", intValue: nil), CodingKeys(stringValue: "element", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "participants", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "slogan", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, String> but found a string/data instead.", underlyingError: nil))
```
Not sure why decoding a User gives me issues with when decoding a Campaign doesn't. | 2020/02/11 | [
"https://Stackoverflow.com/questions/60173826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12596139/"
] | The error clearly says
>
> The value for key `slogan`
>
> at index 1 of array `participants`
>
> at index 0 of array `element`
>
> in `detailresponse`
>
>
>
is a string rather than the expected dictionary.
Please check the JSON | Like I said in my comment, i think you receive a plain string into your "slogan" property in your JSON result. And not an object like you describe.
I tried in a playground :
```swift
struct Campain: Codable {
var slogan: [String:String]?
}
let json = "{\"slogan\": \"\"}"
let campain = JSONDecoder().decode(Campain.self, from: json.data(using: .utf8)!)
print(campain)
```
Gives me the error :
```
DecodingError
▿ typeMismatch : 2 elements
- .0 : Swift.Dictionary<Swift.String, Swift.String>
▿ .1 : Context
▿ codingPath : 1 element
- 0 : CodingKeys(stringValue: "slogan", intValue: nil)
- debugDescription : "Expected to decode Dictionary<String, String> but found a string/data instead."
- underlyingError : nil
```
If i put a real object in the JSON (same as your example), it works. |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | Use `[disabled]` attribute with one flag for it.
**component.html**
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input" [(ngModel)]="isDisabled" id="remember-me" name="rememberMe">
<label class="form-check-label" for="remember-me">I have signed the agreements</label>
</div>
<button type="button" [disabled]="!isDisabled" class="btn btn-outline-danger">Continue</button>
```
**component.ts**
```
isDisabled: boolean = false;
```
This will solve your problem.. | use `ng-disabled` property :
```html
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
</head>
<body> <input type="checkbox" class="form-check-input id="agreements" ng-model="checked">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger" ng-model="button" ng-disabled="checked">Continue</button> </body>
</html>
``` |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | Use `[disabled]` attribute with one flag for it.
**component.html**
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input" [(ngModel)]="isDisabled" id="remember-me" name="rememberMe">
<label class="form-check-label" for="remember-me">I have signed the agreements</label>
</div>
<button type="button" [disabled]="!isDisabled" class="btn btn-outline-danger">Continue</button>
```
**component.ts**
```
isDisabled: boolean = false;
```
This will solve your problem.. | I think having a Reactive Form in place with required validators would give you more control over the form implementation.
You could create a Reactive Form that looks something like this:
```
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
form: FormGroup = this.fb.group({
agreement: [null, Validators.required]
});
constructor(private fb: FormBuilder) {}
}
```
And then you could use the `[disabled]` property binding syntax and bind it to `form.invalid` property to disable the button when the form is invalid:
```
<form [formGroup]="form">
<div class="form-check my-5">
<input
type="checkbox"
class="form-check-input"
id="agreements">
<label
class="form-check-label"
for="agreements">
I have signed the agreements
</label>
</div>
<button
type="button"
class="btn btn-outline-danger"
[disabled]="form.invalid">
Continue
</button>
</form>
```
---
>
> Here's a [**Sample Working Demo**](https://stackblitz.com/edit/angular-disabled-submit-button-on-invalid-form?file=src%2Fapp%2Fapp.component.html) for your ref.
>
>
> |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | Use `[disabled]` attribute with one flag for it.
**component.html**
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input" [(ngModel)]="isDisabled" id="remember-me" name="rememberMe">
<label class="form-check-label" for="remember-me">I have signed the agreements</label>
</div>
<button type="button" [disabled]="!isDisabled" class="btn btn-outline-danger">Continue</button>
```
**component.ts**
```
isDisabled: boolean = false;
```
This will solve your problem.. | You can use [disabled] attribute to enable/disable submit button:
>
> TS file:
>
>
>
```
export class AppComponent {
isDisabled: boolean = true;
updateStatus($event){
$event.target.checked === true ? this.isDisabled = false: this.isDisabled = true;
}
}
```
>
> HTML file
>
>
>
```
<div>
<input type="checkbox" id="remember-me"(change)="updateStatus($event)">
<label for="remember-me" >I have signed the agreements</label>
</div>
<button [disabled]="isDisabled" type="button">Continue</button>
``` |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | Use `[disabled]` attribute with one flag for it.
**component.html**
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input" [(ngModel)]="isDisabled" id="remember-me" name="rememberMe">
<label class="form-check-label" for="remember-me">I have signed the agreements</label>
</div>
<button type="button" [disabled]="!isDisabled" class="btn btn-outline-danger">Continue</button>
```
**component.ts**
```
isDisabled: boolean = false;
```
This will solve your problem.. | Here is a sample working demo
<https://stackblitz.com/edit/angular-fz73re> |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | I think having a Reactive Form in place with required validators would give you more control over the form implementation.
You could create a Reactive Form that looks something like this:
```
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
form: FormGroup = this.fb.group({
agreement: [null, Validators.required]
});
constructor(private fb: FormBuilder) {}
}
```
And then you could use the `[disabled]` property binding syntax and bind it to `form.invalid` property to disable the button when the form is invalid:
```
<form [formGroup]="form">
<div class="form-check my-5">
<input
type="checkbox"
class="form-check-input"
id="agreements">
<label
class="form-check-label"
for="agreements">
I have signed the agreements
</label>
</div>
<button
type="button"
class="btn btn-outline-danger"
[disabled]="form.invalid">
Continue
</button>
</form>
```
---
>
> Here's a [**Sample Working Demo**](https://stackblitz.com/edit/angular-disabled-submit-button-on-invalid-form?file=src%2Fapp%2Fapp.component.html) for your ref.
>
>
> | use `ng-disabled` property :
```html
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
</head>
<body> <input type="checkbox" class="form-check-input id="agreements" ng-model="checked">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger" ng-model="button" ng-disabled="checked">Continue</button> </body>
</html>
``` |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | use `ng-disabled` property :
```html
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
</head>
<body> <input type="checkbox" class="form-check-input id="agreements" ng-model="checked">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger" ng-model="button" ng-disabled="checked">Continue</button> </body>
</html>
``` | You can use [disabled] attribute to enable/disable submit button:
>
> TS file:
>
>
>
```
export class AppComponent {
isDisabled: boolean = true;
updateStatus($event){
$event.target.checked === true ? this.isDisabled = false: this.isDisabled = true;
}
}
```
>
> HTML file
>
>
>
```
<div>
<input type="checkbox" id="remember-me"(change)="updateStatus($event)">
<label for="remember-me" >I have signed the agreements</label>
</div>
<button [disabled]="isDisabled" type="button">Continue</button>
``` |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | I think having a Reactive Form in place with required validators would give you more control over the form implementation.
You could create a Reactive Form that looks something like this:
```
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
form: FormGroup = this.fb.group({
agreement: [null, Validators.required]
});
constructor(private fb: FormBuilder) {}
}
```
And then you could use the `[disabled]` property binding syntax and bind it to `form.invalid` property to disable the button when the form is invalid:
```
<form [formGroup]="form">
<div class="form-check my-5">
<input
type="checkbox"
class="form-check-input"
id="agreements">
<label
class="form-check-label"
for="agreements">
I have signed the agreements
</label>
</div>
<button
type="button"
class="btn btn-outline-danger"
[disabled]="form.invalid">
Continue
</button>
</form>
```
---
>
> Here's a [**Sample Working Demo**](https://stackblitz.com/edit/angular-disabled-submit-button-on-invalid-form?file=src%2Fapp%2Fapp.component.html) for your ref.
>
>
> | You can use [disabled] attribute to enable/disable submit button:
>
> TS file:
>
>
>
```
export class AppComponent {
isDisabled: boolean = true;
updateStatus($event){
$event.target.checked === true ? this.isDisabled = false: this.isDisabled = true;
}
}
```
>
> HTML file
>
>
>
```
<div>
<input type="checkbox" id="remember-me"(change)="updateStatus($event)">
<label for="remember-me" >I have signed the agreements</label>
</div>
<button [disabled]="isDisabled" type="button">Continue</button>
``` |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | I think having a Reactive Form in place with required validators would give you more control over the form implementation.
You could create a Reactive Form that looks something like this:
```
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
form: FormGroup = this.fb.group({
agreement: [null, Validators.required]
});
constructor(private fb: FormBuilder) {}
}
```
And then you could use the `[disabled]` property binding syntax and bind it to `form.invalid` property to disable the button when the form is invalid:
```
<form [formGroup]="form">
<div class="form-check my-5">
<input
type="checkbox"
class="form-check-input"
id="agreements">
<label
class="form-check-label"
for="agreements">
I have signed the agreements
</label>
</div>
<button
type="button"
class="btn btn-outline-danger"
[disabled]="form.invalid">
Continue
</button>
</form>
```
---
>
> Here's a [**Sample Working Demo**](https://stackblitz.com/edit/angular-disabled-submit-button-on-invalid-form?file=src%2Fapp%2Fapp.component.html) for your ref.
>
>
> | Here is a sample working demo
<https://stackblitz.com/edit/angular-fz73re> |
59,409,741 | I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked.
What is the correct way for this?
```
<div class="form-check my-5">
<input type="checkbox" class="form-check-input id="agreements">
<label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>
<button type="button" class="btn btn-outline-danger">Continue</button>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59409741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8526376/"
] | Here is a sample working demo
<https://stackblitz.com/edit/angular-fz73re> | You can use [disabled] attribute to enable/disable submit button:
>
> TS file:
>
>
>
```
export class AppComponent {
isDisabled: boolean = true;
updateStatus($event){
$event.target.checked === true ? this.isDisabled = false: this.isDisabled = true;
}
}
```
>
> HTML file
>
>
>
```
<div>
<input type="checkbox" id="remember-me"(change)="updateStatus($event)">
<label for="remember-me" >I have signed the agreements</label>
</div>
<button [disabled]="isDisabled" type="button">Continue</button>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.