qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
25,353,460 |
I have set up a query and a cursor. My problem is my cursor seems to be moving 1 column at a time.
my table is set up with first column as the description string, second column is the grade value and the third column is the weight value.
this is my query:
```
String[] columns = {Calc_db.COLUMN_GRADE_VALUE, Calc_db.COLUMN_WEIGHT_VALUE};
Cursor cursor = openClass.getBd().query(Calc_db.TABLE_NAME, columns, null, null, null, null, null);
```
I am trying to retrieve the grade and weight value so I can put them in a list.
```
cursor.moveToFirst();
while (cursor.moveToNext()){
Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE));
//cursor.moveToNext();
Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE));
gradeWeightList.add(dbGrade);
gradeWeightList.add(dbWeight);
```
My problem is the cursor is going through 1 column at a time for each loop iteration. It is also going through all 3 columns even though I am only selecting for the second 2 (grade and weight).
example:
If i input : description, 0.7, 0.5 (row 1) decript, 0.6, 0.4 (row 2)
I receive:
loop 1: grade = 0.7, weight = 0.0
loop 2: grade = 0.7, weight = 0.5
loop 3: grade = 0.7, weight = 0.5
loop 4: grade = 0.6, weight = 0.5
loop 5: grade = 0.6, weight = 0.4
What I want is for
loop 1: grade = 0.7, weight = 0.5
loop 2: grade = 0.6, weight = 0.4
|
2014/08/17
|
['https://Stackoverflow.com/questions/25353460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943131/']
|
I see some bugs in your code. **First bug**:
```
cursor.moveToFirst();
while (cursor.moveToNext()) {
...
}
```
This code will skip the first row. You are moving to the first row with `moveToFirst`, then you are moving to the second row with `moveToNext` when the `while` loop condition is evaluated. In general, I prefer to iterate over a cursor using a `for` loop like so:
```
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
...
}
```
This code will work no matter what position the cursor was at before the `for` loop started.
**Second bug**:
```
Double dbGrade = cursor.getDouble(...);
Double dbWeight = cursor.getDouble(...);
gradeWeightList.add(dbGrade);
gradeWeightList.add(dbWeight);
```
Notice you are adding both doubles to the same list (which you call `gradeWeightList`). I presume you have different lists for the grades and weights? While you could simply change the line that is incorrect, you might want to consider making a class that encapsulates the grade data, e.g.
```
public class GradeData {
double grade;
double gradeWeight;
/* constructors and methods omitted */
}
```
... and use a single list of this type of object. For each row, make a new instance of this class, set its properties, and add it to your list. That way you aren't trying to manage disparate lists and keep them all in sync, especially if you decide that your grade data needs more attributes (which in your current implementation would mean adding a third list).
|
You first go in to the first row by `moveToFirst` and then in the if statement you move the cursor to the second row. You should do something like this:
```
if(cursor.moveToFirst) {
do {
// Your Code
} while (cursor.moveToNext())
}
```
|
25,353,460 |
I have set up a query and a cursor. My problem is my cursor seems to be moving 1 column at a time.
my table is set up with first column as the description string, second column is the grade value and the third column is the weight value.
this is my query:
```
String[] columns = {Calc_db.COLUMN_GRADE_VALUE, Calc_db.COLUMN_WEIGHT_VALUE};
Cursor cursor = openClass.getBd().query(Calc_db.TABLE_NAME, columns, null, null, null, null, null);
```
I am trying to retrieve the grade and weight value so I can put them in a list.
```
cursor.moveToFirst();
while (cursor.moveToNext()){
Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE));
//cursor.moveToNext();
Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE));
gradeWeightList.add(dbGrade);
gradeWeightList.add(dbWeight);
```
My problem is the cursor is going through 1 column at a time for each loop iteration. It is also going through all 3 columns even though I am only selecting for the second 2 (grade and weight).
example:
If i input : description, 0.7, 0.5 (row 1) decript, 0.6, 0.4 (row 2)
I receive:
loop 1: grade = 0.7, weight = 0.0
loop 2: grade = 0.7, weight = 0.5
loop 3: grade = 0.7, weight = 0.5
loop 4: grade = 0.6, weight = 0.5
loop 5: grade = 0.6, weight = 0.4
What I want is for
loop 1: grade = 0.7, weight = 0.5
loop 2: grade = 0.6, weight = 0.4
|
2014/08/17
|
['https://Stackoverflow.com/questions/25353460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943131/']
|
I see some bugs in your code. **First bug**:
```
cursor.moveToFirst();
while (cursor.moveToNext()) {
...
}
```
This code will skip the first row. You are moving to the first row with `moveToFirst`, then you are moving to the second row with `moveToNext` when the `while` loop condition is evaluated. In general, I prefer to iterate over a cursor using a `for` loop like so:
```
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
...
}
```
This code will work no matter what position the cursor was at before the `for` loop started.
**Second bug**:
```
Double dbGrade = cursor.getDouble(...);
Double dbWeight = cursor.getDouble(...);
gradeWeightList.add(dbGrade);
gradeWeightList.add(dbWeight);
```
Notice you are adding both doubles to the same list (which you call `gradeWeightList`). I presume you have different lists for the grades and weights? While you could simply change the line that is incorrect, you might want to consider making a class that encapsulates the grade data, e.g.
```
public class GradeData {
double grade;
double gradeWeight;
/* constructors and methods omitted */
}
```
... and use a single list of this type of object. For each row, make a new instance of this class, set its properties, and add it to your list. That way you aren't trying to manage disparate lists and keep them all in sync, especially if you decide that your grade data needs more attributes (which in your current implementation would mean adding a third list).
|
For those of interested this is how I fixed my problem:
(Thanks for the advice Karakuri)
```
public List<Entry> populateList(){
List<Entry> gradeWeightList = new ArrayList<Entry>();
Cursor cursor = data.getBd().query(Calc_db.TABLE_NAME, null, null, null, null, null, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String dbDescript = cursor.getString(cursor.getColumnIndex(Calc_db.COLUMN_DESCRIPTION_VALUE));
Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE));
Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE));
Entry e1 = new Entry (dbDescript, dbGrade, dbWeight);
gradeWeightList.add(e1);
}
cursor.close();
return gradeWeightList;
}
```
Entry Class
```
public class Entry {
private double GRADE;
private double WEIGHT;
private String DESCRIPT;
public Entry(){
GRADE = 0;
WEIGHT = 0;
DESCRIPT = " ";
}
public Entry(String description, double grade, double weight){
GRADE = grade;
WEIGHT = weight;
DESCRIPT = description;
}
public String getDESCRIPT(){
return DESCRIPT;
}
public double getGRADE(){
return GRADE;
}
public double getWEIGHT(){
return WEIGHT;
}
public void setDESCRIPT(String description){
DESCRIPT = description;
}
public void setGRADE(double grade){
GRADE = grade;
}
public void setWEIGHT(double weight){
WEIGHT = weight;
}
```
}
|
25,353,460 |
I have set up a query and a cursor. My problem is my cursor seems to be moving 1 column at a time.
my table is set up with first column as the description string, second column is the grade value and the third column is the weight value.
this is my query:
```
String[] columns = {Calc_db.COLUMN_GRADE_VALUE, Calc_db.COLUMN_WEIGHT_VALUE};
Cursor cursor = openClass.getBd().query(Calc_db.TABLE_NAME, columns, null, null, null, null, null);
```
I am trying to retrieve the grade and weight value so I can put them in a list.
```
cursor.moveToFirst();
while (cursor.moveToNext()){
Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE));
//cursor.moveToNext();
Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE));
gradeWeightList.add(dbGrade);
gradeWeightList.add(dbWeight);
```
My problem is the cursor is going through 1 column at a time for each loop iteration. It is also going through all 3 columns even though I am only selecting for the second 2 (grade and weight).
example:
If i input : description, 0.7, 0.5 (row 1) decript, 0.6, 0.4 (row 2)
I receive:
loop 1: grade = 0.7, weight = 0.0
loop 2: grade = 0.7, weight = 0.5
loop 3: grade = 0.7, weight = 0.5
loop 4: grade = 0.6, weight = 0.5
loop 5: grade = 0.6, weight = 0.4
What I want is for
loop 1: grade = 0.7, weight = 0.5
loop 2: grade = 0.6, weight = 0.4
|
2014/08/17
|
['https://Stackoverflow.com/questions/25353460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943131/']
|
You first go in to the first row by `moveToFirst` and then in the if statement you move the cursor to the second row. You should do something like this:
```
if(cursor.moveToFirst) {
do {
// Your Code
} while (cursor.moveToNext())
}
```
|
For those of interested this is how I fixed my problem:
(Thanks for the advice Karakuri)
```
public List<Entry> populateList(){
List<Entry> gradeWeightList = new ArrayList<Entry>();
Cursor cursor = data.getBd().query(Calc_db.TABLE_NAME, null, null, null, null, null, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String dbDescript = cursor.getString(cursor.getColumnIndex(Calc_db.COLUMN_DESCRIPTION_VALUE));
Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE));
Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE));
Entry e1 = new Entry (dbDescript, dbGrade, dbWeight);
gradeWeightList.add(e1);
}
cursor.close();
return gradeWeightList;
}
```
Entry Class
```
public class Entry {
private double GRADE;
private double WEIGHT;
private String DESCRIPT;
public Entry(){
GRADE = 0;
WEIGHT = 0;
DESCRIPT = " ";
}
public Entry(String description, double grade, double weight){
GRADE = grade;
WEIGHT = weight;
DESCRIPT = description;
}
public String getDESCRIPT(){
return DESCRIPT;
}
public double getGRADE(){
return GRADE;
}
public double getWEIGHT(){
return WEIGHT;
}
public void setDESCRIPT(String description){
DESCRIPT = description;
}
public void setGRADE(double grade){
GRADE = grade;
}
public void setWEIGHT(double weight){
WEIGHT = weight;
}
```
}
|
61,611,313 |
I have a dropdown and a button, how would I go on about making the dropdown the same size as the button?
```css
:root {
--navbarbgc: rgb(83, 79, 79);
--dropwidth: 100px;
}
body {
margin: 0;
}
ul {
list-style: none;
}
.navbar {
background-color: var(--navbarbgc);
}
.navbar>ul>li>button {
width: var(--dropwidth);
}
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
justify-content: center;
}
```
```html
<div class="navbar">
<ul>
<li><button id="navdropbutton">Dropdown</button>
<ul id="navdrop">
<li>Option1</li>
<li>Option2</li>
<li>Option3</li>
<li>Option4</li>
<li>Option5</li>
<li>Option6</li>
<li>Option7</li>
</ul>
</li>
</ul>
</div>
```
I tried making a variable and then putting the same size to them but that didn't work.
|
2020/05/05
|
['https://Stackoverflow.com/questions/61611313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13124037/']
|
What I did
Added class `button-li` to the `li` element which has `button`
And added this css
```
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
justify-content: center;
padding: 0;
width: 100%;
}
.button-li {
display: inline-block;
position: relative;
}
```
Fiddle <https://jsfiddle.net/vsm15jok/>
|
Here I gave **button** **width** of **100px**, removed **padding** from **#navdrop** and gave **width** of **100px** to **#navdrop** (same as button) then I just centered the text using **text-align**. you should **NOT** be using **justify-content** because it does nothing for you right now. use **justify-content** with Flex
```
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
width: 100px;
padding-left: 0px;
text-align: center;
}
#navdropbutton {
width: 100px;
}
```
**Fiddle**:
<https://jsfiddle.net/10c2axds/1/>
|
61,611,313 |
I have a dropdown and a button, how would I go on about making the dropdown the same size as the button?
```css
:root {
--navbarbgc: rgb(83, 79, 79);
--dropwidth: 100px;
}
body {
margin: 0;
}
ul {
list-style: none;
}
.navbar {
background-color: var(--navbarbgc);
}
.navbar>ul>li>button {
width: var(--dropwidth);
}
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
justify-content: center;
}
```
```html
<div class="navbar">
<ul>
<li><button id="navdropbutton">Dropdown</button>
<ul id="navdrop">
<li>Option1</li>
<li>Option2</li>
<li>Option3</li>
<li>Option4</li>
<li>Option5</li>
<li>Option6</li>
<li>Option7</li>
</ul>
</li>
</ul>
</div>
```
I tried making a variable and then putting the same size to them but that didn't work.
|
2020/05/05
|
['https://Stackoverflow.com/questions/61611313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13124037/']
|
What I did
Added class `button-li` to the `li` element which has `button`
And added this css
```
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
justify-content: center;
padding: 0;
width: 100%;
}
.button-li {
display: inline-block;
position: relative;
}
```
Fiddle <https://jsfiddle.net/vsm15jok/>
|
you can add w-100 to the dropdown-menu class part
```
<div class="dropdown" style="margin-right: 5px;width: 23%;">
<button class="btn btn-block btn-warning dropdown-toggle btn-lg" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
OPERAZIONI
</button>
<div class="dropdown-menu w-100" aria-labelledby="dropdownMenu2">
<button type="button" class=" dropdown-item border border-warning rounded">
<a class="bottonePreferenze" data-link="/pg/ac_Operazione" href="/pg/ac_Operazione">
<i class="fa fa-cube fa-2x"></i>
<span>ANAGRAFICA OPERAZIONI</span>
</a></button>
</div>
</div>
```
|
61,611,313 |
I have a dropdown and a button, how would I go on about making the dropdown the same size as the button?
```css
:root {
--navbarbgc: rgb(83, 79, 79);
--dropwidth: 100px;
}
body {
margin: 0;
}
ul {
list-style: none;
}
.navbar {
background-color: var(--navbarbgc);
}
.navbar>ul>li>button {
width: var(--dropwidth);
}
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
justify-content: center;
}
```
```html
<div class="navbar">
<ul>
<li><button id="navdropbutton">Dropdown</button>
<ul id="navdrop">
<li>Option1</li>
<li>Option2</li>
<li>Option3</li>
<li>Option4</li>
<li>Option5</li>
<li>Option6</li>
<li>Option7</li>
</ul>
</li>
</ul>
</div>
```
I tried making a variable and then putting the same size to them but that didn't work.
|
2020/05/05
|
['https://Stackoverflow.com/questions/61611313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13124037/']
|
Here I gave **button** **width** of **100px**, removed **padding** from **#navdrop** and gave **width** of **100px** to **#navdrop** (same as button) then I just centered the text using **text-align**. you should **NOT** be using **justify-content** because it does nothing for you right now. use **justify-content** with Flex
```
#navdrop {
position: absolute;
background-color: var(--navbarbgc);
width: 100px;
padding-left: 0px;
text-align: center;
}
#navdropbutton {
width: 100px;
}
```
**Fiddle**:
<https://jsfiddle.net/10c2axds/1/>
|
you can add w-100 to the dropdown-menu class part
```
<div class="dropdown" style="margin-right: 5px;width: 23%;">
<button class="btn btn-block btn-warning dropdown-toggle btn-lg" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
OPERAZIONI
</button>
<div class="dropdown-menu w-100" aria-labelledby="dropdownMenu2">
<button type="button" class=" dropdown-item border border-warning rounded">
<a class="bottonePreferenze" data-link="/pg/ac_Operazione" href="/pg/ac_Operazione">
<i class="fa fa-cube fa-2x"></i>
<span>ANAGRAFICA OPERAZIONI</span>
</a></button>
</div>
</div>
```
|
424,696 |
I need to write a very simple shell script that will check if the system is configured to enforce multi-factor authentication.
To verify that the system is configured to enforce multi-factor authentication, run the following commands:
```
/usr/sbin/system_profiler SPConfigurationProfileDataType | /usr/bin/grep enforceSmartCard
```
If the results do not show "**enforceSmartCard=1**", this is a finding.
I created this very simple script, but I am pretty sure there is a more effective, elegant and efficient way to achieve the same result.
Basically if it was you, what kind of modifications would you apply to the script below to achieve the same results?
Thank you so much in advance for your help.
```
#!/bin/zsh
myVAR=`/usr/sbin/system_profiler SPConfigurationProfileDataType | /usr/bin/grep enforceSmartCard`
if [ $myVAR = "enforceSmartCard=1" ]
then
echo "The system is configured to enforce multi-factor authentication"
else
echo "The system is not configured to enforce multi-factor authentication"
fi
```
|
2021/07/27
|
['https://apple.stackexchange.com/questions/424696', 'https://apple.stackexchange.com', 'https://apple.stackexchange.com/users/219530/']
|
This might be a little more elegant, not necessarily *simpler*: I'm wrapping the parts of the pipeline in their own functions
```bsh
profile () { /usr/sbin/system_profiler SPConfigurationProfileDataType; }
enforces2fa () { /usr/bin/grep -F -q 'enforceSmartCard=1'; }
if profile | enforces2fa; then
echo "The system is configured to enforce multi-factor authentication"
else
echo "The system is not configured to enforce multi-factor authentication"
fi
```
Some notes
* prefer `$(...)` over ``...`` for command substitution: it's easier to read.
* `if` takes a *command* and branches based on the command's *exit status*. At a bash prompt, enter `help if` for more details.
+ `[` is a bash builtin command, not just syntax.
* if "enforceSmartCard=1" is the only text on the line, add `-x` to the grep options.
Additionally, you can modify the PATH in your script to streamline the functions
```bsh
PATH=$(getconf PATH) # /usr/bin:/bin:/usr/sbin:/sbin
profile () { system_profiler SPConfigurationProfileDataType; }
enforces2fa () { grep -F -q 'enforceSmartCard=1'; }
```
This is only in effect for the duration of the running script, and will not affect your interactive shell.
|
I'd be inclined to read the value of the **`enforceSmartCard`** key directly from the *`com.apple.security.smartcard.plist`* file located in the *`/Library/Preferences`* folder.
This can be done using the `defaults` command-line tool, which will be significantly faster than the `system_profiler`, and you won't need to `grep` its output:
**```
defaults read /Library/Preferences/com.apple.security.smartcard enforceSmartCard
```**
Here are the possible outputs for the `system_profiler | grep` and `defaults` commands, together with their meaning:
| `system_profiler | grep` | `defaults` | |
| --- | --- | --- |
| `enforceSmartCard=0` | 0 | The `enforceSmartCard` key is set,and its value is `false` |
| `enforceSmartCard=1` | 1 | The `enforceSmartCard` key is set,and its value is `true` |
| *non-zero exit status* | *Error message* and*non-zero exit status* | The `enforceSmartCard` key is *not*set, **or** (`defaults` only) the propertylist does not exist |
The default value for `enforceSmartCard` is `false`, therefore a non-zero exit status is essentially equivalent in meaning—for our purposes—to `enforceSmartCard=0`. In the case of the `defaults` command, an error message is also printed that looks something like this:
```
The domain/default pair of (/Library/Preferences/com.apple.security.smartcard, enforceSmartCard) does not exist
```
so, provided there isn't a typographical error when you issue the command, then either the file */Library/Preferences/com.apple.security.smartcard.plist* does not exist, or it does and the `enforceSmartCard` key is not set. Either way, the error message is of little value, so this can be suppressed by redirecting *`stderr`* into the void:
```
defaults read /Library/Preferences/com.apple.security.smartcard enforceSmartCard 2>/dev/null
```
Thus, the predicate we discriminate upon will be whether or not this command outputs `"1"` (without quotes): if it does, then a user must authenticate using their smart card (in addition to whatever other form of authentication would be required); any other result (either an output of `"0"`, or a non-zero exit status with no output) infers that a user may authenticate without using a smart card.
Here's the final script that should be equivalent to yours:
```
#!/usr/bin/env zsh
plist=/Library/Preferences/com.apple.security.smartcard
(( $( defaults read "$plist" \
enforceSmartCard 2>/dev/null )
)) && i=1 _not= ||
i=2 _not=not
printf '%s ' The system is ${_not} configured to \
enforce multi-factor authentication \
>/dev/fd/$i
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
Try this:
```
$("#textbox").bind('paste',function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/3/).
|
Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around.
```
$(function() {
$( "#inputFieldId" ).autocomplete({
source: function( event, ui ) {
alert("do your functions here");
return false;
}
});
});
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input):
[DEMO](http://jsfiddle.net/K682b/6/)
```
$("#textbox").on('input',function() {alert("Change detected!");});
```
|
```
if you write anything in your textbox, the event gets fired.
code as follows :
```
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
<script type="text/javascript">
$(function () {
$("#textbox").bind('input', function() {
alert("letter entered");
});
});
</script>
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input):
[DEMO](http://jsfiddle.net/K682b/6/)
```
$("#textbox").on('input',function() {alert("Change detected!");});
```
|
Try this:
```
$("#textbox").bind('paste',function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/3/).
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input):
[DEMO](http://jsfiddle.net/K682b/6/)
```
$("#textbox").on('input',function() {alert("Change detected!");});
```
|
Try the below Code:
```
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
```
$(this).bind('input propertychange', function() {
//your code here
});
```
This is works for typing, paste, right click mouse paste etc.
|
Try the below Code:
```
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
Binding to both events is the typical way to do it. You can also bind to the paste event.
You can bind to multiple events like this:
```
$("#textbox").on('change keyup paste', function() {
console.log('I am pretty sure the text box changed');
});
```
If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a `lastValue` variable to ensure that the text actually did change:
```
var lastValue = '';
$("#textbox").on('change keyup paste mouseup', function() {
if ($(this).val() != lastValue) {
lastValue = $(this).val();
console.log('The text box really changed this time');
}
});
```
And if you want to be `super duper` pedantic then you should use an interval timer to cater for auto fill, plugins, etc:
```
var lastValue = '';
setInterval(function() {
if ($("#textbox").val() != lastValue) {
lastValue = $("#textbox").val();
console.log('I am definitely sure the text box realy realy changed this time');
}
}, 500);
```
|
Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around.
```
$(function() {
$( "#inputFieldId" ).autocomplete({
source: function( event, ui ) {
alert("do your functions here");
return false;
}
});
});
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
```
if you write anything in your textbox, the event gets fired.
code as follows :
```
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
<script type="text/javascript">
$(function () {
$("#textbox").bind('input', function() {
alert("letter entered");
});
});
</script>
```
|
Try the below Code:
```
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
Binding to both events is the typical way to do it. You can also bind to the paste event.
You can bind to multiple events like this:
```
$("#textbox").on('change keyup paste', function() {
console.log('I am pretty sure the text box changed');
});
```
If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a `lastValue` variable to ensure that the text actually did change:
```
var lastValue = '';
$("#textbox").on('change keyup paste mouseup', function() {
if ($(this).val() != lastValue) {
lastValue = $(this).val();
console.log('The text box really changed this time');
}
});
```
And if you want to be `super duper` pedantic then you should use an interval timer to cater for auto fill, plugins, etc:
```
var lastValue = '';
setInterval(function() {
if ($("#textbox").val() != lastValue) {
lastValue = $("#textbox").val();
console.log('I am definitely sure the text box realy realy changed this time');
}
}, 500);
```
|
```
if you write anything in your textbox, the event gets fired.
code as follows :
```
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
<script type="text/javascript">
$(function () {
$("#textbox").bind('input', function() {
alert("letter entered");
});
});
</script>
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
```
if you write anything in your textbox, the event gets fired.
code as follows :
```
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
<script type="text/javascript">
$(function () {
$("#textbox").bind('input', function() {
alert("letter entered");
});
});
</script>
```
|
Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around.
```
$(function() {
$( "#inputFieldId" ).autocomplete({
source: function( event, ui ) {
alert("do your functions here");
return false;
}
});
});
```
|
17,317,465 |
I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.
HTML:
```
<input type="text" id="textbox" />
```
JS:
```
$("#textbox").change(function() {alert("Change detected!");});
```
See [demo on JSFiddle](http://jsfiddle.net/K682b/)
My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...
```
$("#textbox").keyup(function() {alert("Keyup detected!");});
```
...but it's a known fact that the keyup event isn't fired on right-click-and-paste.
Any workaround? Is having both listeners going to cause any problems?
|
2013/06/26
|
['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']
|
On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input):
[DEMO](http://jsfiddle.net/K682b/6/)
```
$("#textbox").on('input',function() {alert("Change detected!");});
```
|
Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around.
```
$(function() {
$( "#inputFieldId" ).autocomplete({
source: function( event, ui ) {
alert("do your functions here");
return false;
}
});
});
```
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick.
Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to "The given data was invalid.", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get.
What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it.
Here's the solution I've come up with:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$arrValid = array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
);
$p_oRequest->validate(
$arrValid,
array(
'name.required' => 'Name is missing',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'User Id is missing',
'user_id.integer' => 'User Id must be an integer',
)
);
} catch (\Illuminate\Validation\ValidationException $e ) {
/**
* Validation failed
* Tell the end-user why
*/
$arrError = $e->errors(); // Useful method - thank you Laravel
/**
* Compile a string of error-messages
*/
foreach ($arrValid as $key=>$value ) {
$arrImplode[] = implode( ', ', $arrError[$key] );
}
$message = implode(', ', $arrImplode);
/**
* Populate the respose array for the JSON
*/
$arrResponse = array(
'result' => 0,
'reason' => $message,
'data' => array(),
'statusCode' => $e->status,
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution.
In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.
|
Your messages should be validation rules, so instead of:
```
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
```
you should have:
```
'name.required' => 'Name is required',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.integer' => 'Curator User Id must be an integer',
```
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones.
In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'.
Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect:
```
public function render($request, Exception $exception) {
if (! $exception instanceof \Illuminate\Validation\ValidationException)) {
// ... render code for other Exceptions here
}
}
```
Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method:
```
if ($exception instanceof ValidationException && $request->expectsJson()) {
return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422);
}
```
Background
==========
Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user.
The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.
|
Your messages should be validation rules, so instead of:
```
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
```
you should have:
```
'name.required' => 'Name is required',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.integer' => 'Curator User Id must be an integer',
```
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
I've only just seen this but all you need to do is move the validate call **before** the try/catch
```
$p_oRequest->validate(
[
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
],
[
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
]
);
try {
...
} catch(\Exception $e) {
return back()->withErrors($e->getMessage())->withInput();
}
```
Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like
```
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
```
|
Your messages should be validation rules, so instead of:
```
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
```
you should have:
```
'name.required' => 'Name is required',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.integer' => 'Curator User Id must be an integer',
```
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick.
Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to "The given data was invalid.", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get.
What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it.
Here's the solution I've come up with:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$arrValid = array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
);
$p_oRequest->validate(
$arrValid,
array(
'name.required' => 'Name is missing',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'User Id is missing',
'user_id.integer' => 'User Id must be an integer',
)
);
} catch (\Illuminate\Validation\ValidationException $e ) {
/**
* Validation failed
* Tell the end-user why
*/
$arrError = $e->errors(); // Useful method - thank you Laravel
/**
* Compile a string of error-messages
*/
foreach ($arrValid as $key=>$value ) {
$arrImplode[] = implode( ', ', $arrError[$key] );
}
$message = implode(', ', $arrImplode);
/**
* Populate the respose array for the JSON
*/
$arrResponse = array(
'result' => 0,
'reason' => $message,
'data' => array(),
'statusCode' => $e->status,
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution.
In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.
|
The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones.
In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'.
Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect:
```
public function render($request, Exception $exception) {
if (! $exception instanceof \Illuminate\Validation\ValidationException)) {
// ... render code for other Exceptions here
}
}
```
Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method:
```
if ($exception instanceof ValidationException && $request->expectsJson()) {
return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422);
}
```
Background
==========
Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user.
The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick.
Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to "The given data was invalid.", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get.
What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it.
Here's the solution I've come up with:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$arrValid = array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
);
$p_oRequest->validate(
$arrValid,
array(
'name.required' => 'Name is missing',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'User Id is missing',
'user_id.integer' => 'User Id must be an integer',
)
);
} catch (\Illuminate\Validation\ValidationException $e ) {
/**
* Validation failed
* Tell the end-user why
*/
$arrError = $e->errors(); // Useful method - thank you Laravel
/**
* Compile a string of error-messages
*/
foreach ($arrValid as $key=>$value ) {
$arrImplode[] = implode( ', ', $arrError[$key] );
}
$message = implode(', ', $arrImplode);
/**
* Populate the respose array for the JSON
*/
$arrResponse = array(
'result' => 0,
'reason' => $message,
'data' => array(),
'statusCode' => $e->status,
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution.
In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.
|
I've only just seen this but all you need to do is move the validate call **before** the try/catch
```
$p_oRequest->validate(
[
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
],
[
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
]
);
try {
...
} catch(\Exception $e) {
return back()->withErrors($e->getMessage())->withInput();
}
```
Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like
```
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
```
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick.
Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to "The given data was invalid.", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get.
What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it.
Here's the solution I've come up with:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$arrValid = array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
);
$p_oRequest->validate(
$arrValid,
array(
'name.required' => 'Name is missing',
'name.alpha_num' => 'Name must be alphanumeric',
'user_id.required' => 'User Id is missing',
'user_id.integer' => 'User Id must be an integer',
)
);
} catch (\Illuminate\Validation\ValidationException $e ) {
/**
* Validation failed
* Tell the end-user why
*/
$arrError = $e->errors(); // Useful method - thank you Laravel
/**
* Compile a string of error-messages
*/
foreach ($arrValid as $key=>$value ) {
$arrImplode[] = implode( ', ', $arrError[$key] );
}
$message = implode(', ', $arrImplode);
/**
* Populate the respose array for the JSON
*/
$arrResponse = array(
'result' => 0,
'reason' => $message,
'data' => array(),
'statusCode' => $e->status,
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution.
In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.
|
Put the response in a variable and use dd() to print it. You will find it on the "messages" method. Worked for me.
`dd($response);`
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones.
In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'.
Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect:
```
public function render($request, Exception $exception) {
if (! $exception instanceof \Illuminate\Validation\ValidationException)) {
// ... render code for other Exceptions here
}
}
```
Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method:
```
if ($exception instanceof ValidationException && $request->expectsJson()) {
return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422);
}
```
Background
==========
Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user.
The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.
|
I've only just seen this but all you need to do is move the validate call **before** the try/catch
```
$p_oRequest->validate(
[
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
],
[
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
]
);
try {
...
} catch(\Exception $e) {
return back()->withErrors($e->getMessage())->withInput();
}
```
Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like
```
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
```
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones.
In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'.
Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect:
```
public function render($request, Exception $exception) {
if (! $exception instanceof \Illuminate\Validation\ValidationException)) {
// ... render code for other Exceptions here
}
}
```
Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method:
```
if ($exception instanceof ValidationException && $request->expectsJson()) {
return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422);
}
```
Background
==========
Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user.
The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.
|
Put the response in a variable and use dd() to print it. You will find it on the "messages" method. Worked for me.
`dd($response);`
|
46,257,191 |
I'm not getting the response I expect.
This is the controller code for a Location web-service request:
```
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Action method to add a location with the supplied Data
*
* @param \Illuminate\Http\Request $p_oRequest Request
*
* @return JSON
*/
public function add(Request $p_oRequest)
{
try {
$p_oRequest->validate(
array(
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
),
array(
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
)
);
} catch (\Exception $ex) {
$arrResponse = array(
'result' => 0,
'reason' => $ex->getMessage(),
'data' => array(),
'statusCode' => 404
);
} finally {
return response()->json($arrResponse);
}
}
}
```
The request is <http://mydomain/index.php/api/v1/location/add?name=@>!^
The response reason I expect is: { "result": 0, "reason": "Name must be alphanumeric", "data": [], "statusCode": 404 }
The actual response I get instead is: { "result": 0, "reason": "The given data was invalid.", "data": [], "statusCode": 404 }
Please help. This is bugging me.
|
2017/09/16
|
['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']
|
I've only just seen this but all you need to do is move the validate call **before** the try/catch
```
$p_oRequest->validate(
[
'name' => 'required|alpha_num',
'user_id' => 'required|integer',
],
[
'name.required' => 'Name is required',
'name.string' => 'Name must be alphanumeric',
'user_id.required' => 'Curator User Id is required',
'user_id.required' => 'Curator User Id must be an integer',
]
);
try {
...
} catch(\Exception $e) {
return back()->withErrors($e->getMessage())->withInput();
}
```
Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like
```
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
```
|
Put the response in a variable and use dd() to print it. You will find it on the "messages" method. Worked for me.
`dd($response);`
|
38,156,908 |
I am working on windows Universal platform(Universal app-UWP). I have issue regarding Responsiveness of the Grid Control. How to design a grid which is responsive for all view. I am designed a grid this way:
Code:
```
<ListView Margin="30,0,0,1" MaxHeight="160" Visibility="Visible" ScrollViewer.VerticalScrollMode="Enabled" Name="lstAssociatedProduct" Grid.Row="1" Grid.Column="0" BorderThickness="0" BorderBrush="#FFA79E9E" UseLayoutRounding="False" >
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected">
<Storyboard>
<ColorAnimation Duration="0" Storyboard.TargetName="myback" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="Transparent"/>
</Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused">
<Storyboard>
<ColorAnimation Duration="0" Storyboard.TargetName="myback" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="#FFF4F4F4"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="myback" Background="Transparent">
<ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Padding" Value="0,0,0,0"/>
<Setter Property="Margin" Value="0,-10,0,-10"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.HeaderTemplate>
<DataTemplate>
<Grid x:Name="grdAssociateTitle" MinWidth="700" HorizontalAlignment="Left" Margin="5,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250*"></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition x:Name="clmStatus" Width="150*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" x:Name="name_title_detail" Text="Name" HorizontalAlignment="Stretch" Foreground="#FF020202" FontWeight="Bold" Margin="0"></TextBlock>
<TextBlock Grid.Column="1" x:Name="sku_title_detail" Text="Surname" HorizontalAlignment="Left" Foreground="#FF040404" FontWeight="Bold"></TextBlock>
<TextBlock Grid.Column="2" x:Name="qty_title_detail" Text="Age" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Bold"></TextBlock>
<TextBlock x:Name="txtAcPriceTitle" Grid.Column="3" Text="City" Margin="0,0,0,0" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Bold"></TextBlock>
<TextBlock Grid.Column="4" Text="Status" x:Name="Address" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Bold"></TextBlock>
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="5,5,0,0" x:Name="grdAssociateData" MinWidth="700" HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250*"></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="150*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" x:Name="name_ans" Text="{Binding name}" Foreground="#FF020202" TextWrapping="Wrap" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="1" x:Name="sku_ans" Text="{Binding surname}" Foreground="#FF040404" HorizontalAlignment="Left" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="2" x:Name="qty_ans" Text="{Binding age}" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="3" x:Name="price_ans" Text="{Binding city}" Foreground="#FF080808" Margin="0,0,0,0" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="4" x:Name="status_ans" Text="{Binding addres}" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
I designed this way but the Grid not properly work responsiveness as per the view so, If there are any solution which make it easily responsive so provide a solution.
|
2016/07/02
|
['https://Stackoverflow.com/questions/38156908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5997390/']
|
We can provide a width of listview in code behind (c#) through the managing all visual state.
Code:
```
if (PageSizeStatesGroup.CurrentState == WideState) //Desktop Devie
{
}
else if (PageSizeStatesGroup.CurrentState == MediumState) // // //tablate state
{
lstorderdetail.Width = 650;
}
else if (PageSizeStatesGroup.CurrentState == MobileState)
{
}
else
{
lstorderdetail.Width = 1200;
new InvalidOperationException();
}
```
Use PageSizeStatesGroup to manage the visual state and then provide a width as per your scrrn requirement.
|
Please tell more about your current problem (at which view size it has problem ? What is your desired result ?).
Depend on your view port / device requirements, you can chose one or combine the following solutions:
* Use difference XAML for each device family
* Use VisualState to change the size/flow of content of the view
* Check the conditions in code behind and adjust the view accordingly
* Programmatically build your UI from code behind
|
38,156,908 |
I am working on windows Universal platform(Universal app-UWP). I have issue regarding Responsiveness of the Grid Control. How to design a grid which is responsive for all view. I am designed a grid this way:
Code:
```
<ListView Margin="30,0,0,1" MaxHeight="160" Visibility="Visible" ScrollViewer.VerticalScrollMode="Enabled" Name="lstAssociatedProduct" Grid.Row="1" Grid.Column="0" BorderThickness="0" BorderBrush="#FFA79E9E" UseLayoutRounding="False" >
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected">
<Storyboard>
<ColorAnimation Duration="0" Storyboard.TargetName="myback" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="Transparent"/>
</Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused">
<Storyboard>
<ColorAnimation Duration="0" Storyboard.TargetName="myback" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="#FFF4F4F4"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="myback" Background="Transparent">
<ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Padding" Value="0,0,0,0"/>
<Setter Property="Margin" Value="0,-10,0,-10"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.HeaderTemplate>
<DataTemplate>
<Grid x:Name="grdAssociateTitle" MinWidth="700" HorizontalAlignment="Left" Margin="5,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250*"></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition x:Name="clmStatus" Width="150*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" x:Name="name_title_detail" Text="Name" HorizontalAlignment="Stretch" Foreground="#FF020202" FontWeight="Bold" Margin="0"></TextBlock>
<TextBlock Grid.Column="1" x:Name="sku_title_detail" Text="Surname" HorizontalAlignment="Left" Foreground="#FF040404" FontWeight="Bold"></TextBlock>
<TextBlock Grid.Column="2" x:Name="qty_title_detail" Text="Age" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Bold"></TextBlock>
<TextBlock x:Name="txtAcPriceTitle" Grid.Column="3" Text="City" Margin="0,0,0,0" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Bold"></TextBlock>
<TextBlock Grid.Column="4" Text="Status" x:Name="Address" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Bold"></TextBlock>
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="5,5,0,0" x:Name="grdAssociateData" MinWidth="700" HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250*"></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="50*"></ColumnDefinition>
<ColumnDefinition Width="150*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" x:Name="name_ans" Text="{Binding name}" Foreground="#FF020202" TextWrapping="Wrap" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="1" x:Name="sku_ans" Text="{Binding surname}" Foreground="#FF040404" HorizontalAlignment="Left" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="2" x:Name="qty_ans" Text="{Binding age}" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="3" x:Name="price_ans" Text="{Binding city}" Foreground="#FF080808" Margin="0,0,0,0" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
<TextBlock Grid.Column="4" x:Name="status_ans" Text="{Binding addres}" Foreground="#FF080808" HorizontalAlignment="Left" FontWeight="Normal"></TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
I designed this way but the Grid not properly work responsiveness as per the view so, If there are any solution which make it easily responsive so provide a solution.
|
2016/07/02
|
['https://Stackoverflow.com/questions/38156908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5997390/']
|
We can provide a width of listview in code behind (c#) through the managing all visual state.
Code:
```
if (PageSizeStatesGroup.CurrentState == WideState) //Desktop Devie
{
}
else if (PageSizeStatesGroup.CurrentState == MediumState) // // //tablate state
{
lstorderdetail.Width = 650;
}
else if (PageSizeStatesGroup.CurrentState == MobileState)
{
}
else
{
lstorderdetail.Width = 1200;
new InvalidOperationException();
}
```
Use PageSizeStatesGroup to manage the visual state and then provide a width as per your scrrn requirement.
|
The best thing you could do is to use State Triggers which automatically resize based on the Screen size.
Check this [example](http://www.wintellect.com/devcenter/jprosise/using-adaptivetrigger-to-build-adaptive-uis-in-windows-10)
|
40,935,127 |
I am getting an error when executing following `.prototxt` and I have absolutely no idea why I get an error there:
```
layer {
name: "conv"
type: "Convolution"
bottom: "image"
top: "conv"
convolution_param {
num_output: 2
kernel_size: 5
pad: 2
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
value: 0
}
}
}
```
This is the error output. As I have seen in the latest `caffe-master-branch` it should be possible to use `5D-Blobs`.
```
I1202 14:54:58.617269 2393 hdf5_data_layer.cpp:93] Number of HDF5 files: 9
I1202 14:54:58.631134 2393 hdf5.cpp:35] Datatype class: H5T_INTEGER
I1202 14:54:59.159739 2393 net.cpp:150] Setting up train-data
I1202 14:54:59.159760 2393 net.cpp:157] Top shape: 1 1 1 128 128 (16384)
I1202 14:54:59.159765 2393 net.cpp:157] Top shape: 1 1 8 128 128 (131072)
I1202 14:54:59.159766 2393 net.cpp:165] Memory required for data: 589824
I1202 14:54:59.159773 2393 layer_factory.hpp:77] Creating layer down_level_0_conv
I1202 14:54:59.159790 2393 net.cpp:100] Creating Layer down_level_0_conv
I1202 14:54:59.159795 2393 net.cpp:434] down_level_0_conv <- image
I1202 14:54:59.159804 2393 net.cpp:408] down_level_0_conv -> down_level_0_conv
F1202 14:54:59.159915 2393 blob.hpp:140] Check failed: num_axes() <= 4 (5 vs. 4) Cannot use legacy accessors on Blobs with > 4 axes.
```
Do I need to go to a certain branch? I just pulled from `caffe-master-branch` again to make sure it is the newest version. I then made a make clean make all command and it still does not work.
|
2016/12/02
|
['https://Stackoverflow.com/questions/40935127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
AFAIK, this error comes from the `"Xavier"` filler: this filler computes the ratio between the input and output channels. If you replace it with a different filler you should be Okay with ND blob.
|
When I remove the check in `line 140 blob.hpp` it does work. This is one way to solve it, not the best one though.
(But this cannot be the proper solution. Is there anything else?)
|
40,935,127 |
I am getting an error when executing following `.prototxt` and I have absolutely no idea why I get an error there:
```
layer {
name: "conv"
type: "Convolution"
bottom: "image"
top: "conv"
convolution_param {
num_output: 2
kernel_size: 5
pad: 2
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
value: 0
}
}
}
```
This is the error output. As I have seen in the latest `caffe-master-branch` it should be possible to use `5D-Blobs`.
```
I1202 14:54:58.617269 2393 hdf5_data_layer.cpp:93] Number of HDF5 files: 9
I1202 14:54:58.631134 2393 hdf5.cpp:35] Datatype class: H5T_INTEGER
I1202 14:54:59.159739 2393 net.cpp:150] Setting up train-data
I1202 14:54:59.159760 2393 net.cpp:157] Top shape: 1 1 1 128 128 (16384)
I1202 14:54:59.159765 2393 net.cpp:157] Top shape: 1 1 8 128 128 (131072)
I1202 14:54:59.159766 2393 net.cpp:165] Memory required for data: 589824
I1202 14:54:59.159773 2393 layer_factory.hpp:77] Creating layer down_level_0_conv
I1202 14:54:59.159790 2393 net.cpp:100] Creating Layer down_level_0_conv
I1202 14:54:59.159795 2393 net.cpp:434] down_level_0_conv <- image
I1202 14:54:59.159804 2393 net.cpp:408] down_level_0_conv -> down_level_0_conv
F1202 14:54:59.159915 2393 blob.hpp:140] Check failed: num_axes() <= 4 (5 vs. 4) Cannot use legacy accessors on Blobs with > 4 axes.
```
Do I need to go to a certain branch? I just pulled from `caffe-master-branch` again to make sure it is the newest version. I then made a make clean make all command and it still does not work.
|
2016/12/02
|
['https://Stackoverflow.com/questions/40935127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
As a complement of [Shai's answer](https://stackoverflow.com/a/40956354/6281477), in order to be compatible with the `ND Convolution` and `InnerProduct` layer, the "`Xavier`" filler [code](https://github.com/BVLC/caffe/blob/master/include/caffe/filler.hpp#L144)
```
virtual void Fill(Blob<Dtype>* blob) {
...
int fan_in = blob->count() / blob->num();
int fan_out = blob->count() / blob->channels();
Dtype n = fan_in; // default to fan_in
...
Dtype scale = sqrt(Dtype(3) / n);
caffe_rng_uniform<Dtype>(blob->count(), -scale, scale,
blob->mutable_cpu_data());
CHECK_EQ(this->filler_param_.sparse(), -1)
<< "Sparsity not supported by this Filler.";
}
```
in caffe, should be more like this:
```
...
int fan_in = blob->count() / blob->shape(0);
int fan_out = blob->num_axis() == 2 ? blob->shape(0) : blob->count() / blob->shape(1);
...//original stuff
```
This little change should also make your prototxt work.
|
When I remove the check in `line 140 blob.hpp` it does work. This is one way to solve it, not the best one though.
(But this cannot be the proper solution. Is there anything else?)
|
40,935,127 |
I am getting an error when executing following `.prototxt` and I have absolutely no idea why I get an error there:
```
layer {
name: "conv"
type: "Convolution"
bottom: "image"
top: "conv"
convolution_param {
num_output: 2
kernel_size: 5
pad: 2
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
value: 0
}
}
}
```
This is the error output. As I have seen in the latest `caffe-master-branch` it should be possible to use `5D-Blobs`.
```
I1202 14:54:58.617269 2393 hdf5_data_layer.cpp:93] Number of HDF5 files: 9
I1202 14:54:58.631134 2393 hdf5.cpp:35] Datatype class: H5T_INTEGER
I1202 14:54:59.159739 2393 net.cpp:150] Setting up train-data
I1202 14:54:59.159760 2393 net.cpp:157] Top shape: 1 1 1 128 128 (16384)
I1202 14:54:59.159765 2393 net.cpp:157] Top shape: 1 1 8 128 128 (131072)
I1202 14:54:59.159766 2393 net.cpp:165] Memory required for data: 589824
I1202 14:54:59.159773 2393 layer_factory.hpp:77] Creating layer down_level_0_conv
I1202 14:54:59.159790 2393 net.cpp:100] Creating Layer down_level_0_conv
I1202 14:54:59.159795 2393 net.cpp:434] down_level_0_conv <- image
I1202 14:54:59.159804 2393 net.cpp:408] down_level_0_conv -> down_level_0_conv
F1202 14:54:59.159915 2393 blob.hpp:140] Check failed: num_axes() <= 4 (5 vs. 4) Cannot use legacy accessors on Blobs with > 4 axes.
```
Do I need to go to a certain branch? I just pulled from `caffe-master-branch` again to make sure it is the newest version. I then made a make clean make all command and it still does not work.
|
2016/12/02
|
['https://Stackoverflow.com/questions/40935127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
AFAIK, this error comes from the `"Xavier"` filler: this filler computes the ratio between the input and output channels. If you replace it with a different filler you should be Okay with ND blob.
|
As a complement of [Shai's answer](https://stackoverflow.com/a/40956354/6281477), in order to be compatible with the `ND Convolution` and `InnerProduct` layer, the "`Xavier`" filler [code](https://github.com/BVLC/caffe/blob/master/include/caffe/filler.hpp#L144)
```
virtual void Fill(Blob<Dtype>* blob) {
...
int fan_in = blob->count() / blob->num();
int fan_out = blob->count() / blob->channels();
Dtype n = fan_in; // default to fan_in
...
Dtype scale = sqrt(Dtype(3) / n);
caffe_rng_uniform<Dtype>(blob->count(), -scale, scale,
blob->mutable_cpu_data());
CHECK_EQ(this->filler_param_.sparse(), -1)
<< "Sparsity not supported by this Filler.";
}
```
in caffe, should be more like this:
```
...
int fan_in = blob->count() / blob->shape(0);
int fan_out = blob->num_axis() == 2 ? blob->shape(0) : blob->count() / blob->shape(1);
...//original stuff
```
This little change should also make your prototxt work.
|
9,104,620 |
I have this code to check if a span is hidden or visible depending on the value it will show or hide, the event is triggered when a user clicks a button:
```
$('form').on('click', '#agregar', function(){
// var p = $('#panel');
//var a = $('#agregar');
if($('#panel').is(':visible')){
$('#panel').hide();
$('#agregar').val('Mostrar Forma');
alert('ocultar');
}else {
//if($('#panel').is(':hidden')){
$('#panel').show();
$('#agregar').val('Ocultar Forma');
alert('mostrar');
}
});
```
the problem is that even if its visible it will never hide it and the alert('mostrar') will always show so the conditional is always false, why is this? is my code wrong? my span is like this:
```
<span id="panel>a fieldset and a form here</span>
```
The css is on a external stylesheet and it's like
```
#panel{ display: none;}
```
Any help is greatly apreciated don't mind any code that's commented I was just trying different forms to see any changes
|
2012/02/01
|
['https://Stackoverflow.com/questions/9104620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079232/']
|
try doing this
if( $("#panel").css("display") != "none" )
|
Try this extension to see if this helps you.
```
jQuery.extend(
jQuery.expr[ ":" ],
{ reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);
```
|
7,923,033 |
I am running some unit tests on my code, and for this I had to download the selenium server. Now, one of the examples selenium includes is called GoogleTest. I had this copied to my C:\ folder, and tried to run it.
At first, i had an error trying to open firefox. Seems that selenium hasn't been updated for quite some time, since it supports up till Firefox version 3.5. Found [this](http://geekswithblogs.net/thomasweller/archive/2010/02/14/making-selenium-1.0.1-work-with-firefox-3.6.aspx) helpful blog that helped me (changing 3.5.\* for 7.0.\*).
Now, I have a new problem. It seems selenium hasn't updated its docs either, and the GoogleTest hangs when executed ([this](https://stackoverflow.com/questions/3652235/selenium-rc-waitforpagetoload-hangs) post explains why). When using AJAX type operations, the operation waitForPageToLoad hangs.
Now, I need an equivalent to this operation but when dealing with AJAX operations.. anybody knows of an alternative? Thanks
|
2011/10/27
|
['https://Stackoverflow.com/questions/7923033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775205/']
|
Did you tried with [QAF formerly ISFW](https://qmetry.github.io/qaf/)? It internally waits for element as well as provides wait functionality for ajax to complete for may of the js toolkit like dojo, extjs, prototype etc
for example if the AUT uses extjs then you can use like
```
waitService.waitForAjaxToComplete(JsToolkit.EXTJS);
```
|
There is no waitforajaxtoreturn function in Selenium. The way AJAX changes are handled are by using the `WebDriverWait` class to wait for a specific condition to become true when the AJAX call returns.
So for example, for the Google test, the `WebDriverWait` could wait for the search container to appear.
In essence, you have to know what you are waiting for in order to continue the test.
|
7,923,033 |
I am running some unit tests on my code, and for this I had to download the selenium server. Now, one of the examples selenium includes is called GoogleTest. I had this copied to my C:\ folder, and tried to run it.
At first, i had an error trying to open firefox. Seems that selenium hasn't been updated for quite some time, since it supports up till Firefox version 3.5. Found [this](http://geekswithblogs.net/thomasweller/archive/2010/02/14/making-selenium-1.0.1-work-with-firefox-3.6.aspx) helpful blog that helped me (changing 3.5.\* for 7.0.\*).
Now, I have a new problem. It seems selenium hasn't updated its docs either, and the GoogleTest hangs when executed ([this](https://stackoverflow.com/questions/3652235/selenium-rc-waitforpagetoload-hangs) post explains why). When using AJAX type operations, the operation waitForPageToLoad hangs.
Now, I need an equivalent to this operation but when dealing with AJAX operations.. anybody knows of an alternative? Thanks
|
2011/10/27
|
['https://Stackoverflow.com/questions/7923033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775205/']
|
Did you tried with [QAF formerly ISFW](https://qmetry.github.io/qaf/)? It internally waits for element as well as provides wait functionality for ajax to complete for may of the js toolkit like dojo, extjs, prototype etc
for example if the AUT uses extjs then you can use like
```
waitService.waitForAjaxToComplete(JsToolkit.EXTJS);
```
|
I am testing some ajax and JS heavy pages and I have been facing exactly the same problem. I have used implicit waits to to pause for the ajax code to execute and load the new content to DOM . Here is a python sample from my code :
```
from selenium import webdriver
browserHandle = webdriver.Firefox()
browserHandle.implicitly_wait(10)
## assuming dom object loads in 10 seconds
## clear implicit wait
browserHandle.implicitly_wait(0)
```
|
12,851,933 |
when i try to run this code :
```
<?php
$str = "Patty O'Furniture";
if(get_magic_quotes_gpc())
echo stripslashes($str);
?>
```
the output is `Patty O'Furniture` but when i try to run this code(upload data into database table)
```
<?php
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
if(get_magic_quotes_gpc())
mysql_query("INSERT INTO sms_recipient (store_id, recipient_name, recipient_phone) VALUES
(
'".$login_id."',
'".stripslashes($data[0])."',
'".stripslashes($data[1])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
}
?>
```
the output only `Patty O` . (see screenshot)

i'm not sure why when i try to save data into database using function `stripslashes` it's not working.
|
2012/10/12
|
['https://Stackoverflow.com/questions/12851933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1530536/']
|
Because you're undoing what [magic\_quotes](http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc) is trying to do.
>
> When magic\_quotes are on, all ' (single-quote), " (double quote), \
> (backslash) and NUL's are escaped with a backslash automatically.
>
>
>
So you're removing the backslashes via `stripslashes` that are being added, and shorting the query when it hits the `'` in `O'Furniture`
|
use [`mysql_real_escape_string()`](http://php.net/manual/en/function.mysql-real-escape-string.php) function instead of `stripslashes()`
or
Try to avoid `mysql_*` functions, Try to use [`mysqli`](http://www.php.net/manual/en/book.mysqli.php) or `PDO`
|
12,851,933 |
when i try to run this code :
```
<?php
$str = "Patty O'Furniture";
if(get_magic_quotes_gpc())
echo stripslashes($str);
?>
```
the output is `Patty O'Furniture` but when i try to run this code(upload data into database table)
```
<?php
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
if(get_magic_quotes_gpc())
mysql_query("INSERT INTO sms_recipient (store_id, recipient_name, recipient_phone) VALUES
(
'".$login_id."',
'".stripslashes($data[0])."',
'".stripslashes($data[1])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
}
?>
```
the output only `Patty O` . (see screenshot)

i'm not sure why when i try to save data into database using function `stripslashes` it's not working.
|
2012/10/12
|
['https://Stackoverflow.com/questions/12851933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1530536/']
|
Because you're undoing what [magic\_quotes](http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc) is trying to do.
>
> When magic\_quotes are on, all ' (single-quote), " (double quote), \
> (backslash) and NUL's are escaped with a backslash automatically.
>
>
>
So you're removing the backslashes via `stripslashes` that are being added, and shorting the query when it hits the `'` in `O'Furniture`
|
What you are seeing is the basis for [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection). Your input is not escaped at all once you remove the slashes. Imagine what would happen if an attacker provided an input string that closed your query and began a new one with `'; UPDATE users SET password WHERE username="admin"`?
At the very least, you need to escape your input with `mysql_real_escape_string`, but really you need to stop using the `mysql` extension. Use prepared statements of the `mysqli` extension instead.
|
24,359,324 |
This is my php code to get user information using google plus api. I had unset the access token in case user click logout but still logout don't works. Once i got the information of any user, then after logging out and connecting again i still got the same user information and no option to sign in with different email id.
```
<?php
error_reporting(E_ERROR | E_PARSE);
include_once "templates/base.php";
session_start();
set_include_path("google-api-php-client-master/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
require_once 'Google/Service/Oauth2.php';
$client_id = '554944507188-jvl2lg6l70dfmee1qad8rguircdfesba.apps.googleusercontent.com';
$client_secret = '-kcfgfqWdhk9sDNOO8LC9N6A';
$redirect_uri = 'http://localhost:81/googleplus/redirect.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey('AIzaSyCWdr3JGvgOZ0lPX9R6hJP4Y00J-R2Ksgg');
$plus = new Google_Service_Plus($client);
$google_oauthV2 = new Google_Service_Oauth2($client);
$client->setScopes('https://www.googleapis.com/auth/plus.login');
$client->setScopes('email');
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
/************************************************
If we're signed in we can go ahead and retrieve
the ID token, which is part of the bundle of
data that is exchange in the authenticate step
- we only need to do a network call if we have
to retrieve the Google certificate to verify it,
and that can be cached.
************************************************/
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
$user = $google_oauthV2->userinfo->get();
$me = $plus->people->get('me');
}
echo pageHeader("GOOGLE+ API for Information Retrival");
if (
$client_id == ' '
|| $client_secret == ' '
|| $redirect_uri == ' ') {
echo missingClientSecretsWarning();
}
?>
<div class="box">
<div class="request">
<?php if (isset($authUrl)): ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php else: ?>
<a class='logout' href='index.php?logout'>Logout</a>
<?php endif ?>
</div>
</div>
```
|
2014/06/23
|
['https://Stackoverflow.com/questions/24359324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/734371/']
|
How about this?
```
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
header('Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
```
|
And how about this?
```
if (isset($_REQUEST['logout'])) {
$client->revokeToken($_SESSION['access_token']);
unset($_SESSION['access_token']);
}
```
|
15,535,398 |
Im trying to add a checkbox to a specific datagridview column header, I found some code online to help but it's not aligning properly and I'm not really sure how to fix it.
Below is an image of the problem and the code, any help would be greatly appreciated!
P.S. I think it might be something to do with properties but I've played around with them but not been successful.

```
Private checkboxHeader231 As CheckBox
Private Sub show_chkBox()
Dim rect As Rectangle = DataGridView1.GetCellDisplayRectangle(columnIndexOfCheckBox, -1, True)
' set checkbox header to center of header cell. +1 pixel to position
rect.Y = 3
rect.X = rect.Location.X + 8 + (rect.Width / 4)
checkboxHeader231 = New CheckBox()
With checkboxHeader231
.BackColor = Color.Transparent
End With
checkboxHeader231.Name = "checkboxHeader1"
checkboxHeader231.Size = New Size(18, 18)
checkboxHeader231.Location = rect.Location
AddHandler checkboxHeader231.CheckedChanged, AddressOf checkboxHeader231_CheckedChanged
DataGridView1.Controls.Add(checkboxHeader231)
End Sub
Private Sub checkboxHeader231_CheckedChanged(sender As System.Object, e As System.EventArgs)
Dim headerBox As CheckBox = DirectCast(DataGridView1.Controls.Find("checkboxHeader1", True)(0), CheckBox)
For Each row As DataGridViewRow In DataGridView1.Rows
row.Cells(columnIndexOfCheckBox).Value = headerBox.Checked
Next
End Sub
```
|
2013/03/20
|
['https://Stackoverflow.com/questions/15535398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2058444/']
|
This is my first entry, but I think this is what youre looking for. I tested it and it worked on my datagrid. You were using the width for the rectangle, youll need it for the column width instead. I set the column header to 4, but you would replace the 4 with your column you want to use I put it in two ways, one with a four loop, the other just as single lines. Tell me if this worked for you:
```
Dim rect As Rectangle = DataGridView1.GetCellDisplayRectangle(4, -1, True) ' replace 4
rect.Y = 3
Dim sum = DataGridView1.Columns(0).Width
'for this area write a for loop to find the width of each column except for the last line which you manually do
'
'
'For i As Integer = 1 To 4 - 1 Step 1 ' replace 4
'sum = sum + DataGridView1.Columns(i).Width
'Next
sum = sum + DataGridView1.Columns(1).Width
sum = sum + DataGridView1.Columns(2).Width
sum = sum + DataGridView1.Columns(3).Width
' stop here and add the last line by hand here
sum = sum + (DataGridView1.Columns(4).Width / 2) + 35 ' used in both cases ' replace 4
rect.X = sum
checkboxHeader231 = New CheckBox()
With checkboxHeader231
.BackColor = Color.Transparent
End With
checkboxHeader231.Name = "checkboxHeader1"
checkboxHeader231.Size = New Size(18, 18)
checkboxHeader231.Location = rect.Location
AddHandler checkboxHeader231.CheckedChanged, AddressOf checkboxHeader231_CheckedChanged
DataGridView1.Controls.Add(checkboxHeader231)
```
|
```
Private headerBox As CheckBox
Private Sub show_checkBox()
Dim checkboxHeader As CheckBox = New CheckBox()
Dim rect As Rectangle = PendingApprovalServiceListingDataGridView.GetCellDisplayRectangle(4, -1, True)
rect.X = 20
rect.Y = 12
With checkboxHeader
.BackColor = Color.Transparent
End With
checkboxHeader.Name = "checkboxHeader"
checkboxHeader.Size = New Size(14, 14)
checkboxHeader.Location = rect.Location
AddHandler checkboxHeader.CheckedChanged, AddressOf checkboxHeader_CheckedChanged
PendingApprovalServiceListingDataGridView.Controls.Add(checkboxHeader)
End Sub
Private Sub checkboxHeader_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
headerBox = DirectCast(PendingApprovalServiceListingDataGridView.Controls.Find("checkboxHeader", True)(0), CheckBox)
For Each row As DataGridViewRow In PendingApprovalServiceListingDataGridView.Rows
row.Cells(0).Value = headerBox.Checked
Next
End Sub
```
|
73,963,231 |
I know that `document.getElementById()` won't work with several ids. So I tried this:
```
document.getElementsByClassName("circle");
```
But that also doesn't work at all. But if I use just the `document.getElementById()` it works with that one id. Here is my code:
```js
let toggle = () => {
let circle = document.getElementsByClassName("circle");
let hidden = circle.getAttribute("hidden");
if (hidden) {
circle.removeAttribute("hidden");
} else {
circle.setAttribute("hidden", "hidden");
}
}
```
|
2022/10/05
|
['https://Stackoverflow.com/questions/73963231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20168544/']
|
`document.getElementsByClassName()` returns a `NodeList`, and to convert it to an array of elements, use `Array.from()`. this will return an array containing all of the elements with the class name `circle`
Here is an example, which changes each element with the `circle` class:
```js
const items = document.getElementsByClassName('circle')
const output = Array.from(items)
function change() {
output.forEach(i => {
var current = i.innerText.split(' ')
current[1] = 'hate'
current = current[0] + ' ' + current[1] + ' ' + current[2]
i.innerText = current
})
}
```
```html
<p class="circle"> I love cats! </p>
<p class="circle"> I love dogs! </p>
<p class="square">I love green!</p>
<p class="circle"> I love waffles! </p>
<p class="circle"> I love javascript! </p>
<p class="square">I love tea!</p>
<button onclick="change()">Change</button>
```
|
You can try this.
```
const selectedIds = document.querySelectorAll('#id1, #id12, #id3');
console.log(selectedIds);
//Will log [element#id1, element#id2, element#id3]
```
Then you can do something like this:
```
for(const element of selectedIds){
//Do something with element
//Example:
element.style.color = "red"
}
```
|
21,608,613 |
I was trying to solve a problem which is to verify that if there exist a sub sequence whose sum is equal to a given number. I found this thread [Distinct sub sequences summing to given number in an array](https://stackoverflow.com/questions/17125536/distinct-sub-sequences-summing-to-given-number-in-an-array).
I don't have to solve it for all the possible sub sequence I just need is to verify. What is the most optimal algorithm to verify it.
e.g. `a[]={8,1,2,5,4,7,6,3} and num=18`
```
8+2+5+3 = 18
```
|
2014/02/06
|
['https://Stackoverflow.com/questions/21608613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1763475/']
|
You're trying to solve the [subset sum problem](http://en.wikipedia.org/wiki/Subset_sum_problem) which is known to be NP-complete.
Hence there's no known optimal polynomial algorithm. However if your problem permits certain constraints then it may be possible to solve it elegantly with one of the algorithms provided in the Wikipedia article.
|
There is a pseudo polynomial Dynamic Programming solution similar to knapsack problem using following analogy :-
>
> 1. Knapsack capacity W = num
> 2. Item i's weight and cost is same as arr[i]
> 3. Maximize Profit
> 4. if MaxProfit == W then there exists subsequence else no subsequence possible.
> 5. Recontruct solution using DP values
>
>
>
**Note:** So as this can be reduced to knapsack problem hence there is no polynomial time solution yet found.
|
167,409 |
I have to evaluate:
$$\int\_{0}^{\pi/2}\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}\, \mathrm{d}x. $$
I can't get the right answer! So please help me out!
|
2012/07/06
|
['https://math.stackexchange.com/questions/167409', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27579/']
|
Let $I$ denote the integral and consider the substitution $u= \frac{\pi }{2} - x.$ Then $I = \displaystyle\int\_0^{\frac{\pi }{2}} \frac{\sqrt{\cos u}}{\sqrt{\cos u } + \sqrt{\sin u }} du$ and $2I = \displaystyle\int\_0^{\frac{\pi }{2}} \frac{\sqrt{\cos u} + \sqrt{\sin u }}{\sqrt{\cos u } + \sqrt{\sin u }} du = \frac{\pi }{2}.$ Hence $I = \frac{\pi }{4}.$
In general, $ \displaystyle\int\_0^a f(x) dx = \displaystyle\int\_0^a f(a-x) $ $dx$ whenever $f$ is integrable, and $\displaystyle\int\_0^{\frac{\pi }{2}} \frac{\cos^a x}{\cos^a x + \sin^a x } dx = \displaystyle\int\_0^{\frac{\pi }{2}} \frac{\sin^a x}{\cos^a x + \sin^a x } dx = \frac{\pi }{4}$ for $a>0$ (same trick.)
|
Note that $\sin(\pi/2-x)=\cos x$ and $\cos(\pi/2-x)=\sin x$. The answer will exploit the symmetry.
Break up the original integral into two parts, (i) from $0$ to $\pi/4$ and (ii) from $\pi/4$ to $\pi/2$.
So our first integral is
$$\int\_{x=0}^{\pi/4} \frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}\,dx.\tag{$1$} $$
For the second integral, make the change of variable $u=\pi/2-x$. Using the fact that $\sin x=\sin(\pi/2-u)=\cos u$ and $\cos x=\cos(\pi/2-u)=\sin u$, and the fact that $dx=-du$, we get after not much work
$$\int\_{u=\pi/4}^{0} -\frac{\sqrt{\cos u}}{\sqrt{\cos u}+\sqrt{\sin u}}\,du$$
Change the dummy variable of integration variable to the **name** $x$. Also, do the integration in the "right" order, $0$ to $\pi/4$. That changes the sign, so our second integral is equal to
$$\int\_{x=0}^{\pi/4} \frac{\sqrt{\cos x}}{\sqrt{\cos x}+\sqrt{\sin x}}\,dx.\tag{$2$}$$
Our original integral is the **sum** of the integrals $(1)$ and $(2)$. Add, and note the beautiful cancellation $\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}+ \frac{\sqrt{\cos x}}{\sqrt{\cos x}+\sqrt{\sin x}}=1$. Thus our original integral is equal to
$$\int\_0^{\pi/4}1\,dx.$$
This is trivial to compute: the answer is $\pi/4$.
**Remark:** Let $f(x)$ and $g(x)$ be any reasonably nice functions such that $g(x)=f(a-x)$. Exactly the same argument shows that
$$\int\_0^a\frac{f(x)}{f(x)+g(x)}\,dx=\frac{a}{2}.$$
|
40,102,726 |
I am working on building an app. Earlier I have used Xcode 7.1 at that time everything was working fine. Recently I have installed Xcode 8.0 as well and I have both the setups installed into in two different directories Xcode\_7, Xcode\_8 and I renamed the setup files as well. Everything was working fine but lately I am getting the following error while working with Xcode 8.
**"An internal error occurred. Editing functionality may be limited "**
and the storyboard view objects are all gone empty like shown in the image but I am able to click on a specific view and still can see their properties defined through attributes inspector but nothing shows up in storyboard still I am able to build the project successfully but while loading it in simulator it says
**Unable to boot the iOS simulator**
I have followed few tips like reinstalling the Xcode , trashing the derived data from preferences. Nothing helped so far. Please let me know if anyone resolved this issue.
[Storyboard file ViewObjects all gone empty](https://i.stack.imgur.com/GtOrZ.png)
**UPDATE**
I have found the fix with the help of apple forums here [Visit](https://forums.developer.apple.com/message/189283)!.
**Disabling the SIP (System Integrity Protection)** in my iMac which runs on El Capitan solved the issue however not sure disabling it will raise any further errors. :)
|
2016/10/18
|
['https://Stackoverflow.com/questions/40102726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4134597/']
|
Try This
>
> Go to Xcode -> Preferences -> Locations -> Derived Data -> click the
> arrow to open in Finder -> And delete the content of that folder.
>
>
>
[](https://i.stack.imgur.com/0j0EO.png)
Hope it helps!
|
Restart your mac, press cmd+R and open in recovery mode.
Open terminal and type command --> csrutil disable
restart mac..
open terminal--> sudo chmod 0777 / private / tmp
then run your xcode, simulator will work fine :)
|
40,102,726 |
I am working on building an app. Earlier I have used Xcode 7.1 at that time everything was working fine. Recently I have installed Xcode 8.0 as well and I have both the setups installed into in two different directories Xcode\_7, Xcode\_8 and I renamed the setup files as well. Everything was working fine but lately I am getting the following error while working with Xcode 8.
**"An internal error occurred. Editing functionality may be limited "**
and the storyboard view objects are all gone empty like shown in the image but I am able to click on a specific view and still can see their properties defined through attributes inspector but nothing shows up in storyboard still I am able to build the project successfully but while loading it in simulator it says
**Unable to boot the iOS simulator**
I have followed few tips like reinstalling the Xcode , trashing the derived data from preferences. Nothing helped so far. Please let me know if anyone resolved this issue.
[Storyboard file ViewObjects all gone empty](https://i.stack.imgur.com/GtOrZ.png)
**UPDATE**
I have found the fix with the help of apple forums here [Visit](https://forums.developer.apple.com/message/189283)!.
**Disabling the SIP (System Integrity Protection)** in my iMac which runs on El Capitan solved the issue however not sure disabling it will raise any further errors. :)
|
2016/10/18
|
['https://Stackoverflow.com/questions/40102726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4134597/']
|
Try This
>
> Go to Xcode -> Preferences -> Locations -> Derived Data -> click the
> arrow to open in Finder -> And delete the content of that folder.
>
>
>
[](https://i.stack.imgur.com/0j0EO.png)
Hope it helps!
|
To all you Xcode 8 users out there:
Make sure you are running mac os sierra! It isn't said that being on el capitan will cause this problem. But I have updated to Sierra and everything works fine now!
|
40,102,726 |
I am working on building an app. Earlier I have used Xcode 7.1 at that time everything was working fine. Recently I have installed Xcode 8.0 as well and I have both the setups installed into in two different directories Xcode\_7, Xcode\_8 and I renamed the setup files as well. Everything was working fine but lately I am getting the following error while working with Xcode 8.
**"An internal error occurred. Editing functionality may be limited "**
and the storyboard view objects are all gone empty like shown in the image but I am able to click on a specific view and still can see their properties defined through attributes inspector but nothing shows up in storyboard still I am able to build the project successfully but while loading it in simulator it says
**Unable to boot the iOS simulator**
I have followed few tips like reinstalling the Xcode , trashing the derived data from preferences. Nothing helped so far. Please let me know if anyone resolved this issue.
[Storyboard file ViewObjects all gone empty](https://i.stack.imgur.com/GtOrZ.png)
**UPDATE**
I have found the fix with the help of apple forums here [Visit](https://forums.developer.apple.com/message/189283)!.
**Disabling the SIP (System Integrity Protection)** in my iMac which runs on El Capitan solved the issue however not sure disabling it will raise any further errors. :)
|
2016/10/18
|
['https://Stackoverflow.com/questions/40102726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4134597/']
|
Restart your mac, press cmd+R and open in recovery mode.
Open terminal and type command --> csrutil disable
restart mac..
open terminal--> sudo chmod 0777 / private / tmp
then run your xcode, simulator will work fine :)
|
To all you Xcode 8 users out there:
Make sure you are running mac os sierra! It isn't said that being on el capitan will cause this problem. But I have updated to Sierra and everything works fine now!
|
101,120 |
I have a Google App Engine Java web app that I have setup with a custom domain from GoDaddy. The site can currently be reached at domain.com and www.domain.com. I am trying to have a 301 redirect occur whenever someone tries to access domain.com instead of www.domain.com. I have tried to use domain forwarding via GoDaddy, without success. How can I achieve this goal?
Here is my Google App Engine setup. I have added all of these records to the GoDaddy DNS Manger.
[](https://i.stack.imgur.com/alc3w.png)
Here is the domain forwarding information I tried:
[](https://i.stack.imgur.com/TeeiC.png)
|
2016/11/15
|
['https://webmasters.stackexchange.com/questions/101120', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/71988/']
|
Update: There are 3 ways to do this.
1. htaccess
2. php to yaml with redirect
3. Within Google itself.
>
> **Specify the domain and subdomains you want to map.**
>
>
> Note: The naked domain and www subdomain are pre populated in the
> form. A naked domain, such as example.com, maps to <http://example.com>.
> A subdomain, such as www, maps to <http://www.example.com>. Click Submit
> mappings to create the desired mapping. In the final step of the Add
> new custom domain form, note the resource records listed along with
> their type and canonical name.
>
>
>
[Full article on Google](https://cloud.google.com/appengine/docs/python/console/using-custom-domains-and-ssl?hl=en)
[Link to Custom Domains Login on Google](https://console.cloud.google.com/appengine/settings/domains?_ga=1.59431789.139328086.1479124615)
**HTACCESS**
Assuming you are on their Apache server you want to add this to your .htaccess file. This is for both, choose one. Replace example with your domain name.
```
#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
```
---
```
#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
```
|
Google does not support htaccess file. They support app.yaml file, which have different [mod rewrite rule](https://cloud.google.com/appengine/docs/php/config/appref), but as far I know It will applicable only to one CNAME, it means if you have set www.example.com then those rewrite rules will not applicable to example.com.
You can use wildcard `*` in CNAME, which redirect all of your subdomain to your perferred domain name. For example if people access example.com/directory/ then it will automatically redirect to www.example.com/directory/ . The main drawback of wildcard is, it applied to all of your subdomain, it means you can't add any of content like images and blog in your subdomain, for example blog.example.com will redirect to www.example.com and images.example.com/puppy.jpg will redirect to www.example.com/puppy.jpg(Which may trigger 404 error). But If you don't have placed any of thing in your subdomain then wildcard will solve your problem.
And, If you just want to redirect example.com to www.example.com and not other subdirectory then you can use [meta refresh tag](https://www.w3.org/TR/WCAG20-TECHS/H76.html) which is client side solution. Or you can host your naked domain somwehere else(Github Pages, Firebase are free solution) and do 301 redirection.
|
3,018 |
In my view the life begins at the time of forming zygote inside the mother's womb. My question is that what is the view of Hinduism about "the beginning of a life"?
|
2014/09/04
|
['https://hinduism.stackexchange.com/questions/3018', 'https://hinduism.stackexchange.com', 'https://hinduism.stackexchange.com/users/187/']
|
**Scientifically:** You are correct.
**By Hinduism:** Its a soul,which is going to change a body like clothes, leaving off the old one and wearing newones.[see this](http://www.eaglespace.com/spirit/gita_reincarnation.php)
>
> vaasaa.nsi jiirNaani yathaa vihaaya navaani gRRihNaati naro.aparaaNi.
>
>
> tathaa shariiraaNi vihaaya jiirNaanyanyaani sa.nyaati navaani dehii..
> B.G. II-22
>
>
> वासांसि जीर्णानि यथा विहाय नवानि गृह्णाति नरोऽपराणि।
>
>
> तथा शरीराणि विहाय जीर्णान्यन्यानि संयाति नवानि देही।।
>
>
>
**That is:** The life of your **body** begins when Zygote was formed in mother's womb, but there is no life of your **soul** (and no death either).
|
*Krishna* says in the *Bhagavad Gita* that the soul is eternal i.e. life neither begins nor ends. Ofcourse, the body if formed again and again as mentioned in *nobalG's* answer.
TEXT 2.12
>
> na tv evaham jatu nasam na tvam neme janadhipah na caiva na
> bhavisyamah sarve vayam atah param
>
>
>
SYNONYMS
>
> na—never; tu—but; eva—certainly; aham—I; jātu—become; na—never;
> āsam—existed; na—it is not so; tvam—yourself; na—not; ime—all these;
> janādhipāḥ—kings; na—never; ca—also; eva—certainly; na—not like that;
> bhaviṣyāmaḥ—shall exist; sarve—all of us; vayam—we; ataḥ
> param—hereafter.
>
>
>
TRANSLATION
>
> Never was there a time when I did not exist, nor you, nor all these
> kings; nor in the future shall any of us cease to be.
>
>
>
<http://www.asitis.com/2/12.html>
|
3,018 |
In my view the life begins at the time of forming zygote inside the mother's womb. My question is that what is the view of Hinduism about "the beginning of a life"?
|
2014/09/04
|
['https://hinduism.stackexchange.com/questions/3018', 'https://hinduism.stackexchange.com', 'https://hinduism.stackexchange.com/users/187/']
|
**Scientifically:** You are correct.
**By Hinduism:** Its a soul,which is going to change a body like clothes, leaving off the old one and wearing newones.[see this](http://www.eaglespace.com/spirit/gita_reincarnation.php)
>
> vaasaa.nsi jiirNaani yathaa vihaaya navaani gRRihNaati naro.aparaaNi.
>
>
> tathaa shariiraaNi vihaaya jiirNaanyanyaani sa.nyaati navaani dehii..
> B.G. II-22
>
>
> वासांसि जीर्णानि यथा विहाय नवानि गृह्णाति नरोऽपराणि।
>
>
> तथा शरीराणि विहाय जीर्णान्यन्यानि संयाति नवानि देही।।
>
>
>
**That is:** The life of your **body** begins when Zygote was formed in mother's womb, but there is no life of your **soul** (and no death either).
|
My SatGuru says human life (i.e., in physical form) starts when the sperm fuses with the Ova. However, it is not that simple.The incoming spirit permeates through both the Ova and the sperm even before they fuse.
Answer is taken from this video:
<https://www.youtube.com/watch?v=sWXgorb7Ia8>
|
3,018 |
In my view the life begins at the time of forming zygote inside the mother's womb. My question is that what is the view of Hinduism about "the beginning of a life"?
|
2014/09/04
|
['https://hinduism.stackexchange.com/questions/3018', 'https://hinduism.stackexchange.com', 'https://hinduism.stackexchange.com/users/187/']
|
*Krishna* says in the *Bhagavad Gita* that the soul is eternal i.e. life neither begins nor ends. Ofcourse, the body if formed again and again as mentioned in *nobalG's* answer.
TEXT 2.12
>
> na tv evaham jatu nasam na tvam neme janadhipah na caiva na
> bhavisyamah sarve vayam atah param
>
>
>
SYNONYMS
>
> na—never; tu—but; eva—certainly; aham—I; jātu—become; na—never;
> āsam—existed; na—it is not so; tvam—yourself; na—not; ime—all these;
> janādhipāḥ—kings; na—never; ca—also; eva—certainly; na—not like that;
> bhaviṣyāmaḥ—shall exist; sarve—all of us; vayam—we; ataḥ
> param—hereafter.
>
>
>
TRANSLATION
>
> Never was there a time when I did not exist, nor you, nor all these
> kings; nor in the future shall any of us cease to be.
>
>
>
<http://www.asitis.com/2/12.html>
|
My SatGuru says human life (i.e., in physical form) starts when the sperm fuses with the Ova. However, it is not that simple.The incoming spirit permeates through both the Ova and the sperm even before they fuse.
Answer is taken from this video:
<https://www.youtube.com/watch?v=sWXgorb7Ia8>
|
37,899,964 |
I am a total scrub with the node http module and having some trouble.
The ultimate goal here is to take a huge list of urls, figure out which are valid and then scrape those pages for certain data. So step one is figuring out if a URL is valid and this simple exercise is baffling me.
say we have an array allURLs:
```
["www.yahoo.com", "www.stackoverflow.com", "www.sdfhksdjfksjdhg.net"]
```
The goal is to iterate this array, make a get request to each and if a response comes in, add the link to a list of workingURLs (for now just another array), else it goes to a list brokenURLs.
```
var workingURLs = [];
var brokenURLs = [];
for (var i = 0; i < allURLs.length; i++) {
var url = allURLs[i];
var req = http.get(url, function (res) {
if (res) {
workingURLs.push(?????); // How to derive URL from response?
}
});
req.on('error', function (e) {
brokenURLs.push(e.host);
});
}
```
what I don't know is how to properly obtain the url from the request/ response object itself, or really how to structure this kind of async code - because again, I am a nodejs scrub :(
For most websites using res.headers.location works, but there are times when the headers do not have this property and that will cause problems for me later on. Also I've tried console logging the response object itself and that was a messy and fruitless endeavor
I have tried pushing the url variable to workingURLs, but by the time any response comes back that would trigger the push, the for loop is already over and url is forever pointing to the final element of the allURLs array.
Thanks to anyone who can help
|
2016/06/18
|
['https://Stackoverflow.com/questions/37899964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6062473/']
|
You need to closure url value to have access to it and protect it from changes on next loop iteration.
For example:
```
(function(url){
// use url here
})(allUrls[i]);
```
Most simple solution for this is use `forEach` instead of `for`.
```
allURLs.forEach(function(url){
//....
});
```
Promisified solution allows you to get a moment when work is done:
```
var http = require('http');
var allURLs = [
"http://www.yahoo.com/",
"http://www.stackoverflow.com/",
"http://www.sdfhksdjfksjdhg.net/"
];
var workingURLs = [];
var brokenURLs = [];
var promises = allURLs.map(url => validateUrl(url)
.then(res => (res?workingURLs:brokenURLs).push(url)));
Promise.all(promises).then(() => {
console.log(workingURLs, brokenURLs);
});
// ----
function validateUrl(url) {
return new Promise((ok, fail) => {
http.get(url, res => return ok(res.statusCode == 200))
.on('error', e => ok(false));
});
}
// Prevent nodejs from exit, don't need if any server listen.
var t = setTimeout(() => { console.log('Time is over'); }, 1000).ref();
```
|
You can use something like this (Not tested):
```
const arr = ["", "/a", "", ""];
Promise.all(arr.map(fetch)
.then(responses=>responses.filter(res=> res.ok).map(res=>res.url))
.then(workingUrls=>{
console.log(workingUrls);
console.log(arr.filter(url=> workingUrls.indexOf(url) == -1 ))
});
```
**EDITED**
[Working fiddle](https://jsfiddle.net/joherro3/x9mg92xf/2/) (Note that you can't do request to another site in the browser because of Cross domain).
**UPDATED with @vp\_arth suggestions**
```
const arr = ["/", "/a", "/", "/"];
let working=[], notWorking=[],
find = url=> fetch(url)
.then(res=> res.ok ?
working.push(res.url) && res : notWorking.push(res.url) && res);
Promise.all(arr.map(find))
.then(responses=>{
console.log('woking', working, 'notWorking', notWorking);
/* Do whatever with the responses if needed */
});
```
[Fiddle](https://jsfiddle.net/joherro3/x9mg92xf/3/)
|
47,712,861 |
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
```
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
```
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
```
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
```
This is Error:
[enter image description here](https://i.stack.imgur.com/fHsXV.png)
|
2017/12/08
|
['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']
|
You could do it with just a little CSS but it does leave a gap:
```
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
```
Hope this helps a little.
|
You can also do it by setting a custom css class and use it in `beforeShowDay` like below
```
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
```
But it only hides the sundays beginning from current day.
Here is a working fiddle
<https://jsfiddle.net/dnbd01do/16/>
|
47,712,861 |
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
```
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
```
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
```
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
```
This is Error:
[enter image description here](https://i.stack.imgur.com/fHsXV.png)
|
2017/12/08
|
['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']
|
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
* [Moment.js - Get all mondays between a date range](https://stackoverflow.com/questions/44909662/moment-js-get-all-mondays-between-a-date-range)
* [Moment.js: Date between dates](https://stackoverflow.com/questions/14897571/moment-js-date-between-dates)
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as `dayNumber` parameter) in the date range you selected:
```
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
```
Then I call this function in my code like that:
```
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
```
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with `sundays.length`), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
[](https://i.stack.imgur.com/PYa56.png)
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and `X`for `X` sundays in the period):
[](https://i.stack.imgur.com/L6yR8.png)
**Finally, here's the working fiddle: <https://jsfiddle.net/maximelafarie/dnbd01do/21/>**
I want to thank any person that helped me. The question was hard to explain and to understand.
|
You could do it with just a little CSS but it does leave a gap:
```
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
```
Hope this helps a little.
|
47,712,861 |
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
```
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
```
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
```
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
```
This is Error:
[enter image description here](https://i.stack.imgur.com/fHsXV.png)
|
2017/12/08
|
['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']
|
You need do changes in two functions in your daterangepicker.js file:
1. createMonthHTML()
```
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
```
In this function i have added class `hideSunday` while pushing the element.
The 2nd function is getWeekHead():
```
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
```
In this file, I have added class to week-7 header.
CSS:
```
.hideSunday{display:none;}
```
Please note, I have not checked all the scenario but it will do trick for you.
|
You can also do it by setting a custom css class and use it in `beforeShowDay` like below
```
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
```
But it only hides the sundays beginning from current day.
Here is a working fiddle
<https://jsfiddle.net/dnbd01do/16/>
|
47,712,861 |
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
```
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
```
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
```
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
```
This is Error:
[enter image description here](https://i.stack.imgur.com/fHsXV.png)
|
2017/12/08
|
['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']
|
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
* [Moment.js - Get all mondays between a date range](https://stackoverflow.com/questions/44909662/moment-js-get-all-mondays-between-a-date-range)
* [Moment.js: Date between dates](https://stackoverflow.com/questions/14897571/moment-js-date-between-dates)
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as `dayNumber` parameter) in the date range you selected:
```
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
```
Then I call this function in my code like that:
```
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
```
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with `sundays.length`), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
[](https://i.stack.imgur.com/PYa56.png)
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and `X`for `X` sundays in the period):
[](https://i.stack.imgur.com/L6yR8.png)
**Finally, here's the working fiddle: <https://jsfiddle.net/maximelafarie/dnbd01do/21/>**
I want to thank any person that helped me. The question was hard to explain and to understand.
|
You can also do it by setting a custom css class and use it in `beforeShowDay` like below
```
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
```
But it only hides the sundays beginning from current day.
Here is a working fiddle
<https://jsfiddle.net/dnbd01do/16/>
|
47,712,861 |
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
```
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
```
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
```
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
```
This is Error:
[enter image description here](https://i.stack.imgur.com/fHsXV.png)
|
2017/12/08
|
['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']
|
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
* [Moment.js - Get all mondays between a date range](https://stackoverflow.com/questions/44909662/moment-js-get-all-mondays-between-a-date-range)
* [Moment.js: Date between dates](https://stackoverflow.com/questions/14897571/moment-js-date-between-dates)
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as `dayNumber` parameter) in the date range you selected:
```
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
```
Then I call this function in my code like that:
```
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
```
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with `sundays.length`), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
[](https://i.stack.imgur.com/PYa56.png)
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and `X`for `X` sundays in the period):
[](https://i.stack.imgur.com/L6yR8.png)
**Finally, here's the working fiddle: <https://jsfiddle.net/maximelafarie/dnbd01do/21/>**
I want to thank any person that helped me. The question was hard to explain and to understand.
|
You need do changes in two functions in your daterangepicker.js file:
1. createMonthHTML()
```
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
```
In this function i have added class `hideSunday` while pushing the element.
The 2nd function is getWeekHead():
```
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
```
In this file, I have added class to week-7 header.
CSS:
```
.hideSunday{display:none;}
```
Please note, I have not checked all the scenario but it will do trick for you.
|
46,977,956 |
Any ideas how to create like this animation on iOS using Swift ? Thanks
[](https://i.stack.imgur.com/h49Hi.gif)
|
2017/10/27
|
['https://Stackoverflow.com/questions/46977956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5718563/']
|
There are three ways to achieve this (probably more than three):
1. Create a custom header and listen to your table view Scroll, then update the header based on the offset.
2. Use a third party library like this one:
* <https://material.io/components/ios/catalog/flexible-headers/>
3. Follow a tutorial (there are many of them): <https://www.youtube.com/watch?v=lML5XMLrZEk>
Sometimes it is better to do that by yourself, but in this case, I think a framework could help you.
|
I think it's not the UINavigationBar. You could change nav bar alpha then add custom view to table view or collection view and create animation that you need when scrolling.
|
46,977,956 |
Any ideas how to create like this animation on iOS using Swift ? Thanks
[](https://i.stack.imgur.com/h49Hi.gif)
|
2017/10/27
|
['https://Stackoverflow.com/questions/46977956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5718563/']
|
There are three ways to achieve this (probably more than three):
1. Create a custom header and listen to your table view Scroll, then update the header based on the offset.
2. Use a third party library like this one:
* <https://material.io/components/ios/catalog/flexible-headers/>
3. Follow a tutorial (there are many of them): <https://www.youtube.com/watch?v=lML5XMLrZEk>
Sometimes it is better to do that by yourself, but in this case, I think a framework could help you.
|
Custom Collection view flow layout or ScrollView with UIScrollViewDelegate adjusting the header height when content offset is changing.
|
9,347 |
In the rules it is recommended for the first games to use side A of the wonders only. After these first games (if I understand the rules correctly) players play the side that is *at the top* of the wonder card they draw. So some would play side A and some side B (probably). This question discusses [if the two sides are balanced](https://boardgames.stackexchange.com/questions/5310/are-the-a-sides-and-b-sides-of-the-wonder-boards-really-balanced).
I wonder if this is really the best way?
I see several possibilities how to handle which side to play:
1. randomly drawn wonder cards, but all players use side A (recommended for the first games)
2. randomly drawn wonder cards, but all players use side B
3. randomly drawn wonder cards, all players use the side that is at the top when the card is revealed (the normal rule)
4. randomly drawn wonder cards, all players use the side they like more
I feel like variant 4 would be the best (each player may select the side) for a casual playing group, as otherwise some side A players might feel that the side B players have an "unfair" advantage (as the special abilites on B *seem* to be better). Would it be problematic/unbalanced to use variant 4?
How does the side get selected in tournaments?
---
EDIT: The rules also allow that players (if all agree) can choose which *wonder* to play. In this case, variant 4 is probably used (variants 1 and 2 would be possible, too), while variant 3 would be rather pointless (you'd select a wonder yourself but randomize which side to play). Anyhow, this question is about randomly chosen wonders.
|
2012/11/23
|
['https://boardgames.stackexchange.com/questions/9347', 'https://boardgames.stackexchange.com', 'https://boardgames.stackexchange.com/users/3532/']
|
This is a tricky one. The rulebook makes seems to specify option #3 pretty specifically:
>
> Shuffle the 7 Wonder cards, face down, and hand one to each player. The card **and its facing** determine the Wonders board given to each player, as well as the side to be used during the game.
>
>
>
However, when I demoed the Leaders expansion from Asmodee at a convention, option #4 was used; the cards were dealt randomly but players were allowed to choose their own sides. This was the first I had seen this rule, but it seemed to work well and I immediately started using it in casual games as well. Not only do players get to choose the board they like better, but there's no worry about making sure to maintain the orientation on the Wonder card when revealing it. I encountered the same rule at GenCon 2012, when I played (with little success, sadly) in a tournament.
|
The sides are pretty imbalanced - with about one exception (I forget which, and depends on Leaders expansion) B is far stronger. In general it's a poorly balanced game but forcing some players to side A and some to side B only exacerbates this.
|
7,324,767 |
Look at the Twitter sign up page at <https://twitter.com/signup>
Even when you click on first input field "Full name" placeholder stays there until I start typing something. That is awesome.
Does anyone know of a good jQuery plugin that comes close to that?
|
2011/09/06
|
['https://Stackoverflow.com/questions/7324767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/796723/']
|
One possible problem could be that the web server is running out of memory and forcing the app pool to recycle. This would flush the InProc Session memory. You could try using Sql Session State instead and see if that resolves the problem. Try monitoring the web server processes and see if they're recycling quickly.
|
You can place a
```
if(Session.IsNew)
```
check in your code and redirect/stop code execution appropriately.
|
7,324,767 |
Look at the Twitter sign up page at <https://twitter.com/signup>
Even when you click on first input field "Full name" placeholder stays there until I start typing something. That is awesome.
Does anyone know of a good jQuery plugin that comes close to that?
|
2011/09/06
|
['https://Stackoverflow.com/questions/7324767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/796723/']
|
One possible problem could be that the web server is running out of memory and forcing the app pool to recycle. This would flush the InProc Session memory. You could try using Sql Session State instead and see if that resolves the problem. Try monitoring the web server processes and see if they're recycling quickly.
|
I would check the Performance tab in IIS to see whether a bandwidth threshold is set.
1. Right click on website in IIS
2. Performance tab
3. Check "Bandwidth throttling" limit
If a treshold is set you might be hitting the maximum bandwidth (KB per second) limit. Either disable bandwidth throttling, or increase the limit.
|
79,016 |
Given the case that a user is presented a modal dialog that displays an installation process (or something similar).
If the process would normally take a few seconds but can potentially take longer, should I offer a "Cancel" button to give the user full control?
I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ...
* trap the user in the dialog until the process is completed or a timeout is reached
* offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation
|
2015/05/20
|
['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']
|
It very much depends on the type of your application the operation it is doing. Ideally user should always be in control, but there are situations when you will want to keep control when you are making critical changes.
Firstly, you must inform user that a following operation might take X amount of time and that she may not be able to use the system.

When you tell such a thing, this puts a certain amount of stress on the user. You should try your best to alleviate that stress. Best way is to show the time left, and what exactly is the action you are performing. While doing so, your messages should avoid jargon and meet the target audience's vocabulary.
A windows update may not be an precise example for this situation but it does tell you how Microsoft handled it in Windows 7.

Although here Windows can not estimate the time required, it tries to break up the operation in steps so that user has some tangible progress to hold on to. This is very essential for many reasons. I have seen vague progress bars which just run to oblivion without offering any solace to users. You must avoid that.
*Considering your use case, after user feedback, you might want to push the message of delay when the operation does not complete in threshold time. I agree that users would already have started the process, but if most of the times the operation is going to take few seconds, there is no reason to always show a message that they can't use the system. After a few seconds you can pop up and mention this seems to be taking longer than usual. You might need a users opinion on this.*
|
If there is no safe way for the user to leave the process then you really should make them wait until it is complete. Leaving them with a faulty system is potentially more damaging to the software's reputation than making them wait for an extra 20 minutes for a correct and perfect instal.
However, I assume that they've gone through some sort of process to get to that point (agree to EULA, select instal location, etc), that would be that time to clearly tell them how much time it is expected to take in the worst cases (this will also add a little expectation management giving users who don't experience worst case a pleasant surprise when the process completes more quickly than expected).
If you must offer a "cancel at any cost" option then you will need to clearly message the user about the cost to their system (bad data, disk errors, failing software, etc) with an "Are you sure?" dialogue so that they can make an informed choice. You might also need to include a legal disclaimer depending on the amount of damage you could potentially do to their system.
|
79,016 |
Given the case that a user is presented a modal dialog that displays an installation process (or something similar).
If the process would normally take a few seconds but can potentially take longer, should I offer a "Cancel" button to give the user full control?
I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ...
* trap the user in the dialog until the process is completed or a timeout is reached
* offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation
|
2015/05/20
|
['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']
|
If there is no safe way for the user to leave the process then you really should make them wait until it is complete. Leaving them with a faulty system is potentially more damaging to the software's reputation than making them wait for an extra 20 minutes for a correct and perfect instal.
However, I assume that they've gone through some sort of process to get to that point (agree to EULA, select instal location, etc), that would be that time to clearly tell them how much time it is expected to take in the worst cases (this will also add a little expectation management giving users who don't experience worst case a pleasant surprise when the process completes more quickly than expected).
If you must offer a "cancel at any cost" option then you will need to clearly message the user about the cost to their system (bad data, disk errors, failing software, etc) with an "Are you sure?" dialogue so that they can make an informed choice. You might also need to include a legal disclaimer depending on the amount of damage you could potentially do to their system.
|
If possible, present the user with a "Finish Later" option on the dialog, instead of "Cancel". If the install takes longer than they want right now, or they have something important they need to do right now that the install process is interfering with, they can choose that option and then you let them continue the next time the install process is initiated.
|
79,016 |
Given the case that a user is presented a modal dialog that displays an installation process (or something similar).
If the process would normally take a few seconds but can potentially take longer, should I offer a "Cancel" button to give the user full control?
I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ...
* trap the user in the dialog until the process is completed or a timeout is reached
* offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation
|
2015/05/20
|
['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']
|
It very much depends on the type of your application the operation it is doing. Ideally user should always be in control, but there are situations when you will want to keep control when you are making critical changes.
Firstly, you must inform user that a following operation might take X amount of time and that she may not be able to use the system.

When you tell such a thing, this puts a certain amount of stress on the user. You should try your best to alleviate that stress. Best way is to show the time left, and what exactly is the action you are performing. While doing so, your messages should avoid jargon and meet the target audience's vocabulary.
A windows update may not be an precise example for this situation but it does tell you how Microsoft handled it in Windows 7.

Although here Windows can not estimate the time required, it tries to break up the operation in steps so that user has some tangible progress to hold on to. This is very essential for many reasons. I have seen vague progress bars which just run to oblivion without offering any solace to users. You must avoid that.
*Considering your use case, after user feedback, you might want to push the message of delay when the operation does not complete in threshold time. I agree that users would already have started the process, but if most of the times the operation is going to take few seconds, there is no reason to always show a message that they can't use the system. After a few seconds you can pop up and mention this seems to be taking longer than usual. You might need a users opinion on this.*
|
I believe the correct action would be to explain to the user before going through with the irreversible action, that the action is irreversible.
`"Doing this is permanent / This action is un-doable / You can not roll back this change" -> OK /cancel` Or something like that depending on what kind of users you have and what jargon they do or don't know.
Don't trap a user on a load screen if avoidable. If the load time really is so high that you have to expect the user to want to cancel out of it; then we can now acknowledge that the load time is very high. So let's make the user prepared for this long, irreversible load time and at least give them the option to start it in their own time.
Presenting junk data would only be okay if CRUD'ing / manipulating data was normal/easy/expected/not a hassel. But it usually is considering we as UX designers should value every single click we cost on the user.
|
79,016 |
Given the case that a user is presented a modal dialog that displays an installation process (or something similar).
If the process would normally take a few seconds but can potentially take longer, should I offer a "Cancel" button to give the user full control?
I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ...
* trap the user in the dialog until the process is completed or a timeout is reached
* offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation
|
2015/05/20
|
['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']
|
I believe the correct action would be to explain to the user before going through with the irreversible action, that the action is irreversible.
`"Doing this is permanent / This action is un-doable / You can not roll back this change" -> OK /cancel` Or something like that depending on what kind of users you have and what jargon they do or don't know.
Don't trap a user on a load screen if avoidable. If the load time really is so high that you have to expect the user to want to cancel out of it; then we can now acknowledge that the load time is very high. So let's make the user prepared for this long, irreversible load time and at least give them the option to start it in their own time.
Presenting junk data would only be okay if CRUD'ing / manipulating data was normal/easy/expected/not a hassel. But it usually is considering we as UX designers should value every single click we cost on the user.
|
If possible, present the user with a "Finish Later" option on the dialog, instead of "Cancel". If the install takes longer than they want right now, or they have something important they need to do right now that the install process is interfering with, they can choose that option and then you let them continue the next time the install process is initiated.
|
79,016 |
Given the case that a user is presented a modal dialog that displays an installation process (or something similar).
If the process would normally take a few seconds but can potentially take longer, should I offer a "Cancel" button to give the user full control?
I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ...
* trap the user in the dialog until the process is completed or a timeout is reached
* offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation
|
2015/05/20
|
['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']
|
It very much depends on the type of your application the operation it is doing. Ideally user should always be in control, but there are situations when you will want to keep control when you are making critical changes.
Firstly, you must inform user that a following operation might take X amount of time and that she may not be able to use the system.

When you tell such a thing, this puts a certain amount of stress on the user. You should try your best to alleviate that stress. Best way is to show the time left, and what exactly is the action you are performing. While doing so, your messages should avoid jargon and meet the target audience's vocabulary.
A windows update may not be an precise example for this situation but it does tell you how Microsoft handled it in Windows 7.

Although here Windows can not estimate the time required, it tries to break up the operation in steps so that user has some tangible progress to hold on to. This is very essential for many reasons. I have seen vague progress bars which just run to oblivion without offering any solace to users. You must avoid that.
*Considering your use case, after user feedback, you might want to push the message of delay when the operation does not complete in threshold time. I agree that users would already have started the process, but if most of the times the operation is going to take few seconds, there is no reason to always show a message that they can't use the system. After a few seconds you can pop up and mention this seems to be taking longer than usual. You might need a users opinion on this.*
|
If possible, present the user with a "Finish Later" option on the dialog, instead of "Cancel". If the install takes longer than they want right now, or they have something important they need to do right now that the install process is interfering with, they can choose that option and then you let them continue the next time the install process is initiated.
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core`
In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours.
```
PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1
```
### 3rd party
If Nuget is not installed this command should do it
```
dotnet add package Microsoft.EntityFrameworkCore
```
|
Change your project to `.NETFramework,Version=v4.6.1` or choose an Entity Framework nuget that supports `.NETCoreApp,Version=v2.0`
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
Alternatively you can change your target framework to net461 as below.
```
<TargetFramework>net461</TargetFramework>
```
By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.
|
Change your project to `.NETFramework,Version=v4.6.1` or choose an Entity Framework nuget that supports `.NETCoreApp,Version=v2.0`
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)
|
Change your project to `.NETFramework,Version=v4.6.1` or choose an Entity Framework nuget that supports `.NETCoreApp,Version=v2.0`
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core`
In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours.
```
PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1
```
### 3rd party
If Nuget is not installed this command should do it
```
dotnet add package Microsoft.EntityFrameworkCore
```
|
Alternatively you can change your target framework to net461 as below.
```
<TargetFramework>net461</TargetFramework>
```
By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core`
In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours.
```
PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1
```
### 3rd party
If Nuget is not installed this command should do it
```
dotnet add package Microsoft.EntityFrameworkCore
```
|
I had the same problem, and was introduced by altering my solution to use a new TargetFramework.
```
<TargetFramework>netcoreapp2.2</TargetFramework>
```
After the Update I tried to add the Identity Framework but failed with a warning as described.
By Adding the packages in this sequence solved it for me:
```
Microsoft.EntityFrameworkCore
Microsoft.AspNetCore.Identity
```
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core`
In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours.
```
PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1
```
### 3rd party
If Nuget is not installed this command should do it
```
dotnet add package Microsoft.EntityFrameworkCore
```
|
In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
Alternatively you can change your target framework to net461 as below.
```
<TargetFramework>net461</TargetFramework>
```
By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.
|
I had the same problem, and was introduced by altering my solution to use a new TargetFramework.
```
<TargetFramework>netcoreapp2.2</TargetFramework>
```
After the Update I tried to add the Identity Framework but failed with a warning as described.
By Adding the packages in this sequence solved it for me:
```
Microsoft.EntityFrameworkCore
Microsoft.AspNetCore.Identity
```
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
Alternatively you can change your target framework to net461 as below.
```
<TargetFramework>net461</TargetFramework>
```
By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.
|
In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)
|
48,201,091 |
I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error
>
> Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
>
>
>
How do I fix this?
|
2018/01/11
|
['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']
|
In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)
|
I had the same problem, and was introduced by altering my solution to use a new TargetFramework.
```
<TargetFramework>netcoreapp2.2</TargetFramework>
```
After the Update I tried to add the Identity Framework but failed with a warning as described.
By Adding the packages in this sequence solved it for me:
```
Microsoft.EntityFrameworkCore
Microsoft.AspNetCore.Identity
```
|
54,096,270 |
I do not understand why one IEnumerable.Contains() is faster than the other in the following snippet, even though they are identical.
```
public class Group
{
public static Dictionary<int, Group> groups = new Dictionary<int, Group>();
// Members, user and groups
public List<string> Users = new List<string>();
public List<int> GroupIds = new List<int>();
public IEnumerable<string> AggregateUsers()
{
IEnumerable<string> aggregatedUsers = Users.AsEnumerable();
foreach (int id in GroupIds)
aggregatedUsers = aggregatedUsers.Concat(groups[id].AggregateUsers());
return aggregatedUsers;
}
}
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
Group.groups.TryAdd(i, new Group());
for (int i = 0; i < 999; i++)
Group.groups[i + 1].GroupIds.Add(i);
for (int i = 0; i < 10000; i++)
Group.groups[i/10].Users.Add($"user{i}");
IEnumerable<string> users = Group.groups[999].AggregateUsers();
Stopwatch stopwatch = Stopwatch.StartNew();
bool contains1 = users.Contains("user0");
Console.WriteLine($"Search through IEnumerable from recursive function was {contains1} and took {stopwatch.ElapsedMilliseconds} ms");
users = Enumerable.Empty<string>();
foreach (Group group in Group.groups.Values.Reverse())
users = users.Concat(group.Users);
stopwatch = Stopwatch.StartNew();
bool contains2 = users.Contains("user0");
Console.WriteLine($"Search through IEnumerable from foreach was {contains2} and took {stopwatch.ElapsedMilliseconds} ms");
Console.Read();
}
```
Here is the output obtained by executing this snippet:
```
Search through IEnumerable from recursive function was True and took 40 ms
Search through IEnumerable from foreach was True and took 3 ms
```
The snippet simulates 10,000 users distributed in 1,000 groups of 10 users each.
Each group can have 2 types of members, users (a string), or other groups (an int representing the ID of that group).
Each group has the previous group as a member. So group 0 has 10 users, group1 has 10 users and users from group 0, group 2 has 10 users and users of group 1 .. and here begins the recursion.
The purpose of the search is to determine if user "user0" (which is close to the end of the List) is a member of the group 999 (which through group relation contains all 10,000 users).
The question is, why is the search taking only 3 ms for the search through the IEnumerable constructed with foreach, and 10 times more, for the same IEnumerable constructed with the recursive method ?
|
2019/01/08
|
['https://Stackoverflow.com/questions/54096270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5550961/']
|
An interesting question. When I compiled it in .NET Framework, the execution times were about the same (I had to change the TryAdd Dictionary method to Add).
In .NET Core I've got the same result as you observed.
I believe the answer is deferred execution. You can see in the debugger, that the
```
IEnumerable<string> users = Group.groups[999].AggregateUsers();
```
assignment to users variable will result in Concat2Iterator instance and the second one
```
users = Enumerable.Empty<string>();
foreach (Group group in Group.groups.Values.Reverse())
users = users.Concat(group.Users);
```
will result in ConcatNIterator.
From the documentation of concat:
>
> This method is implemented by using deferred execution. The immediate
> return value is an object that stores all the information that is
> required to perform the action. The query represented by this method
> is not executed until the object is enumerated either by calling its
> GetEnumerator method directly or by using foreach in Visual C# or For
> Each in Visual Basic.
>
>
>
You can check out the code of concat [here](https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Concat.cs). The implementations of GetEnumerable for ConcatNIterator and Concat2Iterator are different.
So my guess is that the first query takes longer to evaluate because of the way you build the query using concat. If you try using ToList() on one of the enumerables like this:
```
IEnumerable<string> users = Group.groups[999].AggregateUsers().ToList();
```
you will see that the time elapsed will come down almost to 0 ms.
|
I figured out how to overcome the problem after reading Mikołaj's answer and Servy's comment. Thanks!
```
public class Group
{
public static Dictionary<int, Group> groups = new Dictionary<int, Group>();
// Members, user and groups
public List<string> Users = new List<string>();
public List<int> GroupIds = new List<int>();
public IEnumerable<string> AggregateUsers()
{
IEnumerable<string> aggregatedUsers = Users.AsEnumerable();
foreach (int id in GroupIds)
aggregatedUsers = aggregatedUsers.Concat(groups[id].AggregateUsers());
return aggregatedUsers;
}
public IEnumerable<string> AggregateUsers(List<IEnumerable<string>> aggregatedUsers = null)
{
bool topStack = false;
if (aggregatedUsers == null)
{
topStack = true;
aggregatedUsers = new List<IEnumerable<string>>();
}
aggregatedUsers.Add(Users.AsEnumerable());
foreach (int id in GroupIds)
groups[id].AggregateUsers(aggregatedUsers);
if (topStack)
return aggregatedUsers.SelectMany(i => i);
else
return null;
}
}
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
Group.groups.TryAdd(i, new Group());
for (int i = 0; i < 999; i++)
Group.groups[i + 1].GroupIds.Add(i);
for (int i = 0; i < 10000; i++)
Group.groups[i / 10].Users.Add($"user{i}");
Stopwatch stopwatch = Stopwatch.StartNew();
IEnumerable<string> users = Group.groups[999].AggregateUsers();
Console.WriteLine($"Aggregation via nested concatenation took {stopwatch.ElapsedMilliseconds} ms");
stopwatch = Stopwatch.StartNew();
bool contains = users.Contains("user0");
Console.WriteLine($"Search through IEnumerable from nested concatenation was {contains} and took {stopwatch.ElapsedMilliseconds} ms");
stopwatch = Stopwatch.StartNew();
users = Group.groups[999].AggregateUsers(null);
Console.WriteLine($"Aggregation via SelectMany took {stopwatch.ElapsedMilliseconds} ms");
stopwatch = Stopwatch.StartNew();
contains = users.Contains("user0");
Console.WriteLine($"Search through IEnumerable from SelectMany was {contains} and took {stopwatch.ElapsedMilliseconds} ms");
stopwatch = Stopwatch.StartNew();
users = Enumerable.Empty<string>();
foreach (Group group in Group.groups.Values.Reverse())
users = users.Concat(group.Users);
Console.WriteLine($"Aggregation via flat concatenation took {stopwatch.ElapsedMilliseconds} ms");
stopwatch = Stopwatch.StartNew();
contains = users.Contains("user0");
Console.WriteLine($"Search through IEnumerable from flat concatenation was {contains} and took {stopwatch.ElapsedMilliseconds} ms");
Console.Read();
}
```
Here are the results:
```
Aggregation via nested concatenation took 0 ms
Search through IEnumerable from nested concatenation was True and took 43 ms
Aggregation via SelectMany took 1 ms
Search through IEnumerable from SelectMany was True and took 0 ms
Aggregation via foreach concatenation took 0 ms
Search through IEnumerable from foreach concatenation was True and took 2 ms
```
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
on the assumption that your needs are more like your colored example code then:
```
.box:nth-child(odd){
clear:both;
}
```
if it's going to be 3 rows then `nth-child(3n+1)`
|
This may not be the exact solution for everybody but I find that (quite literally) thinking outside the box works for many cases: in stead of displaying the the boxes from left to right, in many cases you can fill the left column first, than go to the middle, fill that with boxes and finally fill the right column with boxes.
Your image would then be:
[](https://i.stack.imgur.com/WTxhS.jpg):
If you are using a scripting language like php you can also fill the columns from left to right by adding a new box to it and outputting when all columns are filled. eg (untested php code):
```
$col1 = '<div class="col1"> <div>box1</div>';
$col2 = '<div class="col2"> <div>box2</div>';
$col3 = '<div class="col3"> <div>box3</div>';
$col1 .= '<div>box4</div> </div>'; //last </div> closes the col1 div
$col2 .= '<div>box5</div> </div>';
$col3 .= '<div>box6</div> </div>';
echo $col1.$col2.$col3;
```
$col1, $col2 and $col3 can have float:left and width: 33%, set the boxes inside the div to full width and no float.
Obviously if you are using javascript / jquery to load the boxes dynamically you are better of styling them this way as well, as explained in other answers to this thread.
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
To my knowledge, there's no way to fix this problem with pure CSS (that works in all common browsers):
* Floats [don't work](http://jsfiddle.net/bCgea/).
* `display: inline-block` [doesn't work](http://jsfiddle.net/bCgea/1/).
* `position: relative` with `position: absolute` requires [manual pixel tuning](http://jsfiddle.net/bCgea/2/). If you're using a server-side language, and you're working with images (or something with predictable height), you can handle the pixel tuning "automatically" with server-side code.
Instead, use [***jQuery Masonry***](http://masonry.desandro.com/).
|
With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer.
On every "row" that I make, I add a class name `left`.
On every other "row" that I make, I add a class name `right`.
Then I float left and float right for each of these class names!
The only complication is that my content order is reversed on the "right" rows, but that can be resolved using PHP.
Thanks for your help folks!
```css
#holder{
width:200px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
float:right;
}
.four{
background-color:#FF0;
float:right;
}
.left{float:left;}
.right{float:right;}
```
```html
<div id="holder">
<div class="box one left">1</div>
<div class="box two left">2</div>
<div class="box four right">4</div>
<div class="box three right">3</div>
</div>
</body>
```
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
As has been rightly pointed out, this is impossible with CSS alone... thankfully, I've now found a solution in <http://isotope.metafizzy.co/>
It seems to solve the problem fully.
|
Thanks to thirtydot, I have realised my previous answer did not properly resolve the problem. Here is my second attempt, which utilizes JQuery as a CSS only solution appears impossible:
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var numberOfColumns = 3;
var numberOfColumnsPlusOne = numberOfColumns+1;
var marginBottom = 10; //Top and bottom margins added
var kids = $('#holder:first-child').children();
var add;
$.each(kids, function(key, value) {
add = numberOfColumnsPlusOne+key;
if (add <= kids.length){
$('#holder:first-child :nth-child('+(numberOfColumnsPlusOne+key)+')').offset({ top: $('#holder:first-child :nth-child('+(key+1)+')').offset().top+$('#holder:first-child :nth-child('+(key+1)+')').height()+marginBottom });
}
});
});
</script>
<style>
#holder{
width:270px;
border:1px dotted blue;
display:inline-block; /* Enables the holder to hold floated elements (look at dotted blue line with and without */
}
.box{
width:80px;
height:150px;
background-color:#CCC;
margin:5px;
text-align:center;
font-size:45px;
}
.one{
height:86px;
}
.two{
height:130px;
}
.three{
height:60px;
}
.four{
clear:both;
height:107px;
}
.five{
height:89px;
}
.six{
height:89px;
}
.left{float:left;}
.right{float:right;}
</style>
</head>
<body>
<div id="holder">
<div class="box one left">1</div>
<div class="box two left">2</div>
<div class="box three left">3</div>
<div class="box four left">4</div>
<div class="box five left">5</div>
<div class="box six left">6</div>
</div>
</body>
</body>
```
The only problem that remains for my solution is, what happens when a box is two-box-widths instead of just one. I'm still working on this solution. I'll post when complete.
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
I'm providing this answer because even when there are good ones which do provide a solution([using Masonry](http://masonry.desandro.com/)) still isn't crystal clear why it isn't possible to achieve this by using floats.
(this is important - **#1**).
>
> A floated element will move as far to the left or right as it can **in
> the position where it was originally**
>
>
>
So put it in this way:
We have 2 div
```
<div class="div5">div5</div>
<div class="div6">div6</div>
.div-blue{
width:100px;
height:100px;
background: blue;
}
.div-red{
width:50px;
height:50px;
background: red;
}
```
without `float` they'll be one below the other

If we `float: right` the `div5`, the `div6` is positioned on the line where the `div5` was ,
`/*the lines are just for illustrate*/`

So if now we `float: left` the `div6` it will move as far to the left as it can, "**in this line**" (see #1 above), so if `div5` changes its line, `div6` will follow it.
Now let's add other div into the equation
```
<div class="div4">div4</div>
<div class="div5">div5</div>
<div class="div6">div6</div>
.div-gree{
width:150px;
height:150px;
background: green;
float:right;
}
```
We have this

If we set `clear: right` to the `div5`, we are forcing it to take the line bellow `div4`

and `div6` will float in this new line wether to the right or to the left.
Now lets use as example the question that brought me here due to a duplicate [Forcing div stack from left to right](https://stackoverflow.com/questions/32102623/forcing-div-stack-from-left-to-right#32102623)
Here the snippet to test it:
```css
div{
width:24%;
margin-right: 1%;
float: left;
margin-top:5px;
color: #fff;
font-size: 24px;
text-align: center;
}
.one{
background-color:red;
height: 50px;
}
.two{
background-color:green;
height:40px;
}
.three{
background-color:orange;
height:55px;
}
.four{
background-color:magenta;
height:25px;
}
.five{
background-color:black;
height:55px;
}
```
```html
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="one">1*</div>
<div class="three">2*</div>
<div class="four">3*</div>
<div class="two">4*</div>
<div class="five">5*</div>
```
[](https://i.stack.imgur.com/MQfyh.jpg)
In the above image you can see how `div.5` is stocked just next to `div.3` that is because in its line (defined by the line box of `div.4`) that is as far it can go, `div.1*`, `div.2*`, etc, also float left of `div.5` but as they don't fit in that line they go to the line bellow (defined by the line box of `div.5`)
Now notice that when we reduce the height of `div.2*` enough to be less than `div.4*` how it let pass to `div.5*`:
[](https://i.stack.imgur.com/UZSkC.jpg)
I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title "*CSS Floating Divs At Variable Heights*" and because right now the answer is quite long.
|
As has been rightly pointed out, this is impossible with CSS alone... thankfully, I've now found a solution in <http://isotope.metafizzy.co/>
It seems to solve the problem fully.
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
on the assumption that your needs are more like your colored example code then:
```
.box:nth-child(odd){
clear:both;
}
```
if it's going to be 3 rows then `nth-child(3n+1)`
|
On modern browsers you can simply do:
```
display: inline-block;
vertical-align: top;
```
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer.
On every "row" that I make, I add a class name `left`.
On every other "row" that I make, I add a class name `right`.
Then I float left and float right for each of these class names!
The only complication is that my content order is reversed on the "right" rows, but that can be resolved using PHP.
Thanks for your help folks!
```css
#holder{
width:200px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
float:right;
}
.four{
background-color:#FF0;
float:right;
}
.left{float:left;}
.right{float:right;}
```
```html
<div id="holder">
<div class="box one left">1</div>
<div class="box two left">2</div>
<div class="box four right">4</div>
<div class="box three right">3</div>
</div>
</body>
```
|
This may not be the exact solution for everybody but I find that (quite literally) thinking outside the box works for many cases: in stead of displaying the the boxes from left to right, in many cases you can fill the left column first, than go to the middle, fill that with boxes and finally fill the right column with boxes.
Your image would then be:
[](https://i.stack.imgur.com/WTxhS.jpg):
If you are using a scripting language like php you can also fill the columns from left to right by adding a new box to it and outputting when all columns are filled. eg (untested php code):
```
$col1 = '<div class="col1"> <div>box1</div>';
$col2 = '<div class="col2"> <div>box2</div>';
$col3 = '<div class="col3"> <div>box3</div>';
$col1 .= '<div>box4</div> </div>'; //last </div> closes the col1 div
$col2 .= '<div>box5</div> </div>';
$col3 .= '<div>box6</div> </div>';
echo $col1.$col2.$col3;
```
$col1, $col2 and $col3 can have float:left and width: 33%, set the boxes inside the div to full width and no float.
Obviously if you are using javascript / jquery to load the boxes dynamically you are better of styling them this way as well, as explained in other answers to this thread.
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
I'm providing this answer because even when there are good ones which do provide a solution([using Masonry](http://masonry.desandro.com/)) still isn't crystal clear why it isn't possible to achieve this by using floats.
(this is important - **#1**).
>
> A floated element will move as far to the left or right as it can **in
> the position where it was originally**
>
>
>
So put it in this way:
We have 2 div
```
<div class="div5">div5</div>
<div class="div6">div6</div>
.div-blue{
width:100px;
height:100px;
background: blue;
}
.div-red{
width:50px;
height:50px;
background: red;
}
```
without `float` they'll be one below the other

If we `float: right` the `div5`, the `div6` is positioned on the line where the `div5` was ,
`/*the lines are just for illustrate*/`

So if now we `float: left` the `div6` it will move as far to the left as it can, "**in this line**" (see #1 above), so if `div5` changes its line, `div6` will follow it.
Now let's add other div into the equation
```
<div class="div4">div4</div>
<div class="div5">div5</div>
<div class="div6">div6</div>
.div-gree{
width:150px;
height:150px;
background: green;
float:right;
}
```
We have this

If we set `clear: right` to the `div5`, we are forcing it to take the line bellow `div4`

and `div6` will float in this new line wether to the right or to the left.
Now lets use as example the question that brought me here due to a duplicate [Forcing div stack from left to right](https://stackoverflow.com/questions/32102623/forcing-div-stack-from-left-to-right#32102623)
Here the snippet to test it:
```css
div{
width:24%;
margin-right: 1%;
float: left;
margin-top:5px;
color: #fff;
font-size: 24px;
text-align: center;
}
.one{
background-color:red;
height: 50px;
}
.two{
background-color:green;
height:40px;
}
.three{
background-color:orange;
height:55px;
}
.four{
background-color:magenta;
height:25px;
}
.five{
background-color:black;
height:55px;
}
```
```html
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="one">1*</div>
<div class="three">2*</div>
<div class="four">3*</div>
<div class="two">4*</div>
<div class="five">5*</div>
```
[](https://i.stack.imgur.com/MQfyh.jpg)
In the above image you can see how `div.5` is stocked just next to `div.3` that is because in its line (defined by the line box of `div.4`) that is as far it can go, `div.1*`, `div.2*`, etc, also float left of `div.5` but as they don't fit in that line they go to the line bellow (defined by the line box of `div.5`)
Now notice that when we reduce the height of `div.2*` enough to be less than `div.4*` how it let pass to `div.5*`:
[](https://i.stack.imgur.com/UZSkC.jpg)
I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title "*CSS Floating Divs At Variable Heights*" and because right now the answer is quite long.
|
Thanks to thirtydot, I have realised my previous answer did not properly resolve the problem. Here is my second attempt, which utilizes JQuery as a CSS only solution appears impossible:
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var numberOfColumns = 3;
var numberOfColumnsPlusOne = numberOfColumns+1;
var marginBottom = 10; //Top and bottom margins added
var kids = $('#holder:first-child').children();
var add;
$.each(kids, function(key, value) {
add = numberOfColumnsPlusOne+key;
if (add <= kids.length){
$('#holder:first-child :nth-child('+(numberOfColumnsPlusOne+key)+')').offset({ top: $('#holder:first-child :nth-child('+(key+1)+')').offset().top+$('#holder:first-child :nth-child('+(key+1)+')').height()+marginBottom });
}
});
});
</script>
<style>
#holder{
width:270px;
border:1px dotted blue;
display:inline-block; /* Enables the holder to hold floated elements (look at dotted blue line with and without */
}
.box{
width:80px;
height:150px;
background-color:#CCC;
margin:5px;
text-align:center;
font-size:45px;
}
.one{
height:86px;
}
.two{
height:130px;
}
.three{
height:60px;
}
.four{
clear:both;
height:107px;
}
.five{
height:89px;
}
.six{
height:89px;
}
.left{float:left;}
.right{float:right;}
</style>
</head>
<body>
<div id="holder">
<div class="box one left">1</div>
<div class="box two left">2</div>
<div class="box three left">3</div>
<div class="box four left">4</div>
<div class="box five left">5</div>
<div class="box six left">6</div>
</div>
</body>
</body>
```
The only problem that remains for my solution is, what happens when a box is two-box-widths instead of just one. I'm still working on this solution. I'll post when complete.
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
on the assumption that your needs are more like your colored example code then:
```
.box:nth-child(odd){
clear:both;
}
```
if it's going to be 3 rows then `nth-child(3n+1)`
|
With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer.
On every "row" that I make, I add a class name `left`.
On every other "row" that I make, I add a class name `right`.
Then I float left and float right for each of these class names!
The only complication is that my content order is reversed on the "right" rows, but that can be resolved using PHP.
Thanks for your help folks!
```css
#holder{
width:200px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
float:right;
}
.four{
background-color:#FF0;
float:right;
}
.left{float:left;}
.right{float:right;}
```
```html
<div id="holder">
<div class="box one left">1</div>
<div class="box two left">2</div>
<div class="box four right">4</div>
<div class="box three right">3</div>
</div>
</body>
```
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
I'm providing this answer because even when there are good ones which do provide a solution([using Masonry](http://masonry.desandro.com/)) still isn't crystal clear why it isn't possible to achieve this by using floats.
(this is important - **#1**).
>
> A floated element will move as far to the left or right as it can **in
> the position where it was originally**
>
>
>
So put it in this way:
We have 2 div
```
<div class="div5">div5</div>
<div class="div6">div6</div>
.div-blue{
width:100px;
height:100px;
background: blue;
}
.div-red{
width:50px;
height:50px;
background: red;
}
```
without `float` they'll be one below the other

If we `float: right` the `div5`, the `div6` is positioned on the line where the `div5` was ,
`/*the lines are just for illustrate*/`

So if now we `float: left` the `div6` it will move as far to the left as it can, "**in this line**" (see #1 above), so if `div5` changes its line, `div6` will follow it.
Now let's add other div into the equation
```
<div class="div4">div4</div>
<div class="div5">div5</div>
<div class="div6">div6</div>
.div-gree{
width:150px;
height:150px;
background: green;
float:right;
}
```
We have this

If we set `clear: right` to the `div5`, we are forcing it to take the line bellow `div4`

and `div6` will float in this new line wether to the right or to the left.
Now lets use as example the question that brought me here due to a duplicate [Forcing div stack from left to right](https://stackoverflow.com/questions/32102623/forcing-div-stack-from-left-to-right#32102623)
Here the snippet to test it:
```css
div{
width:24%;
margin-right: 1%;
float: left;
margin-top:5px;
color: #fff;
font-size: 24px;
text-align: center;
}
.one{
background-color:red;
height: 50px;
}
.two{
background-color:green;
height:40px;
}
.three{
background-color:orange;
height:55px;
}
.four{
background-color:magenta;
height:25px;
}
.five{
background-color:black;
height:55px;
}
```
```html
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="one">1*</div>
<div class="three">2*</div>
<div class="four">3*</div>
<div class="two">4*</div>
<div class="five">5*</div>
```
[](https://i.stack.imgur.com/MQfyh.jpg)
In the above image you can see how `div.5` is stocked just next to `div.3` that is because in its line (defined by the line box of `div.4`) that is as far it can go, `div.1*`, `div.2*`, etc, also float left of `div.5` but as they don't fit in that line they go to the line bellow (defined by the line box of `div.5`)
Now notice that when we reduce the height of `div.2*` enough to be less than `div.4*` how it let pass to `div.5*`:
[](https://i.stack.imgur.com/UZSkC.jpg)
I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title "*CSS Floating Divs At Variable Heights*" and because right now the answer is quite long.
|
With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer.
On every "row" that I make, I add a class name `left`.
On every other "row" that I make, I add a class name `right`.
Then I float left and float right for each of these class names!
The only complication is that my content order is reversed on the "right" rows, but that can be resolved using PHP.
Thanks for your help folks!
```css
#holder{
width:200px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
float:right;
}
.four{
background-color:#FF0;
float:right;
}
.left{float:left;}
.right{float:right;}
```
```html
<div id="holder">
<div class="box one left">1</div>
<div class="box two left">2</div>
<div class="box four right">4</div>
<div class="box three right">3</div>
</div>
</body>
```
|
5,234,749 |
I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

I'd really appreciate your help. Thanks :)
```
<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}
.two{
background-color:#0FF;
}
.three{
background-color:#00F;
}
.four{
background-color:#FF0;
}
</style>
<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>
```
Here is the [jsfiddle](http://jsfiddle.net/XFX55/)
Here is what I did and achieved using javascript
<https://jsfiddle.net/8o0nwft9/>
|
2011/03/08
|
['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']
|
To my knowledge, there's no way to fix this problem with pure CSS (that works in all common browsers):
* Floats [don't work](http://jsfiddle.net/bCgea/).
* `display: inline-block` [doesn't work](http://jsfiddle.net/bCgea/1/).
* `position: relative` with `position: absolute` requires [manual pixel tuning](http://jsfiddle.net/bCgea/2/). If you're using a server-side language, and you're working with images (or something with predictable height), you can handle the pixel tuning "automatically" with server-side code.
Instead, use [***jQuery Masonry***](http://masonry.desandro.com/).
|
On modern browsers you can simply do:
```
display: inline-block;
vertical-align: top;
```
|
15,722,072 |
I have created a singup button as follows:
```
signupButton = [[UIButton alloc] initWithFrame:CGRectMake(10,(facebookLoginButton.bounds.size.height + 40),300,50)];
signupButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
UIImage *signupButtonImage = [[UIImage imageNamed:@"Signup"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)];
[signupButton setBackgroundImage:signupButtonImage forState:UIControlStateNormal];
```
The frame for the button is 300x50 per the above. I have created an image (for Retina devices) as 22(w)x100(h)px.
The image is 22 pixels which includes 10px rounded corners and 2px which are for the repeatable middle section.
I have tried to implement the stretch per the above code with insets as 0,10,0,10 but this does not stretch as expected.


Can someone explain what the insets should be? Also how to work these out, I cannot find any useful information on how to actually calculate what the insets should be? I have read the Apple documentation on this, but I do not understand how to work these out.
|
2013/03/30
|
['https://Stackoverflow.com/questions/15722072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523603/']
|
You don't need the starting and trailing `.*`, but you do need to escape the `$` as it has the special meaning of the zero-width end of the string.
```
\\$_POST\\['[a-zA-Z0-9]*'\\]
```
|
Use this:
```
"\\$_POST\\['([a-zA-Z0-9]*)'\\]"
```
Symbols like `$`have particular meanings in regex. Therefore, you need to prefix them with `\`
|
15,722,072 |
I have created a singup button as follows:
```
signupButton = [[UIButton alloc] initWithFrame:CGRectMake(10,(facebookLoginButton.bounds.size.height + 40),300,50)];
signupButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
UIImage *signupButtonImage = [[UIImage imageNamed:@"Signup"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)];
[signupButton setBackgroundImage:signupButtonImage forState:UIControlStateNormal];
```
The frame for the button is 300x50 per the above. I have created an image (for Retina devices) as 22(w)x100(h)px.
The image is 22 pixels which includes 10px rounded corners and 2px which are for the repeatable middle section.
I have tried to implement the stretch per the above code with insets as 0,10,0,10 but this does not stretch as expected.


Can someone explain what the insets should be? Also how to work these out, I cannot find any useful information on how to actually calculate what the insets should be? I have read the Apple documentation on this, but I do not understand how to work these out.
|
2013/03/30
|
['https://Stackoverflow.com/questions/15722072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523603/']
|
You don't need the starting and trailing `.*`, but you do need to escape the `$` as it has the special meaning of the zero-width end of the string.
```
\\$_POST\\['[a-zA-Z0-9]*'\\]
```
|
You can use the regex pattern given as a String with the [matches(...) method](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches%28java.lang.String%29) of the [String class](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches%28java.lang.String%29). It returns a `boolean`.
```
String a = "Hello, world! $_POST['something'] Test!";
String b = "Hello, world! $_POST['special!!!char'] Test!";
String c = "Hey there $_GET['something'] foo bar";
String pattern = ".*\\$_POST\\['[A-Za-z0-9]+'\\].*";
System.out.println ("a matches? " + Boolean.toString(a.matches(pattern)));
System.out.println ("b matches? " + Boolean.toString(b.matches(pattern)));
System.out.println ("c matches? " + Boolean.toString(c.matches(pattern)));
```
You can also use a [Pattern](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) and a Matcher object to reuse the pattern for multiple uses:
```
String[] array = {
"Hello, world! $_POST['something'] Test!",
"Hello, world! $_POST['special!!!char'] Test!",
"Hey there $_GET['something'] foo bar"
};
String strPattern = ".*\\$_POST\\['[A-Za-z0-9]+'\\].*";
Pattern p = Pattern.compile(strPattern);
for (int i=0; i<array.length; i++) {
Matcher m = p.matcher(array[i]);
System.out.println("Expression: " + array[i]);
System.out.println("-> Matches? " + Boolean.toString(m.matches()));
System.out.println("");
}
```
outputs:
```
Expression: Hello, world! $_POST['something'] Test!
-> Matches? true
Expression: Hello, world! $_POST['special!!!char'] Test!
-> Matches? false
Expression: Hey there $_GET['something'] foo bar
-> Matches? false
```
|
72,120,789 |
I'm trying to figure out a way to detect where the cursor is in a certain range. This would be the sort of thing I'm looking for:
```
if ('bla bla bla' && Input.mousePosition == (in between x1 and x2, in between y1. and y2))
```
Is this possible in unity, because I can't figure it out :(
Thanks for any help!
|
2022/05/05
|
['https://Stackoverflow.com/questions/72120789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16430718/']
|
also you can use `Rect.Contains` for Prevent dublication:
```
var InRect = new Rect(0, 0, Screen.width/2, Screen.height).Contains(Input.mousePosition);
UnityEngine.Debug.Log(InRect);
```
|
```
Vector2 mousePos = Input.mousePosition;
```
This returns a `Vector2` with the coordinates `x` and `y` of the mouse position. To check if this point with the coordinates `mousePos.x` and `mousePos.y` lies in the range `x1` and `x2`; `y1` and `y2`, we can write
```
if((mousePos.x >= x1 && mousePos.x <= x2) &&
(mousePos.y >= y1 && mousePos.y <= y2))
{
// do something
}
```
Alternatively,
```
if(mousePos >= new Vector2(x1, y1) &&
mousePos <= new Vector2(x2, y2))
{
// do something
}
```
|
10,650,165 |
I'm working on a scripting language and would like to write a compiler / interpreter for my language.
I've desited to do the compiler in standart ML
My question now is, is there a "pattern" for doing this sorta design process?
I've written a java-compiler from scratch as a part of a computerscience course, but that was sorta cheating, since the language was given, meaning that there was reference implementations and syntax, grammars and other specs given.
If starting from scratch, only having a problem domain how does one get started?
I'm looking for a book or a tutorial on the subject.
|
2012/05/18
|
['https://Stackoverflow.com/questions/10650165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/750186/']
|
The classic books on modern compiler construction in functional languages are:
* [Modern Compiler Implementation in ML](http://www.cs.princeton.edu/~appel/modern/ml/)
* [Types and Programming Languages](http://www.cis.upenn.edu/~bcpierce/tapl/)
* [Implementing Functional Languages](http://research.microsoft.com/en-us/um/people/simonpj/papers/pj-lester-book/)
* [Practical Foundations of Programming Languages](http://www.cs.cmu.edu/~rwh/plbook/book.pdf)
|
[Concepts, Techniques and Models of Computer Programming](https://rads.stackoverflow.com/amzn/click/com/0262220695). This book is not directly about how to design a language, but it is an in-depth exploration of the features of one interesting language (Oz), how they interact, and how they enable various usage patterns and features. It is excellent for giving a sense of what the implications of various design decisions and capabilities are. Reading a few such books, observing the resulting languages, and synthesizing from them is a decent way to go about learning how to design a language.
Similarly, but a lot more pragmatically, [Programming Scala](https://rads.stackoverflow.com/amzn/click/com/0981531644) does a great job of explaining how language features enable style.
A lot of language design is ultimately taste and good sense. Reading in-depth explorations of existing languages is a good way to develop and hone such taste.
|
24,808,853 |
I have several lists and I need to do something with each possible combination of these list items. In the case of two lists, I can do:
```
for a in alist:
for b in blist:
# do something with a and b
```
However, if there are more lists, say 6 or 7 lists, this method seems reluctant. Is there any way to elegantly implement this iteration?
|
2014/07/17
|
['https://Stackoverflow.com/questions/24808853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150462/']
|
You could use `itertools.product` to make all possible combinations from your lists. The result will be one long list of `tuple` with an element from each list in the order you passed the list in.
```
>>> a = [1,2,3]
>>> b = ['a', 'b', 'c']
>>> c = [4,5,6]
>>> import itertools
>>> list(itertools.product(a,b,c))
[(1, 'a', 4), (1, 'a', 5), (1, 'a', 6), (1, 'b', 4), (1, 'b', 5), (1, 'b', 6), (1, 'c', 4), (1, 'c', 5), (1, 'c', 6),
(2, 'a', 4), (2, 'a', 5), (2, 'a', 6), (2, 'b', 4), (2, 'b', 5), (2, 'b', 6), (2, 'c', 4), (2, 'c', 5), (2, 'c', 6),
(3, 'a', 4), (3, 'a', 5), (3, 'a', 6), (3, 'b', 4), (3, 'b', 5), (3, 'b', 6), (3, 'c', 4), (3, 'c', 5), (3, 'c', 6)]
```
For example
```
for ai, bi, ci in itertools.product(a,b,c):
print ai, bi, ci
```
Output
```
1 a 4
1 a 5
1 a 6
... etc
```
|
If there are in fact 6 or 7 lists, it's probably worth going to `itertools.product` for readability. But for simple cases it's straightforward to use a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions), and it requires no imports. For example:
```
alist = [1, 2, 3]
blist = ['A', 'B', 'C']
clist = ['.', ',', '?']
abc = [(a,b,c) for a in alist for b in blist for c in clist]
for e in abc:
print("{}{}{} ".format(e[0],e[1],e[2])),
# 1A. 1A, 1A? 1B. 1B, 1B? 1C. 1C, 1C? 2A. 2A, 2A? 2B. 2B, 2B? 2C. 2C, 2C? 3A. 3A, 3A? 3B. 3B, 3B? 3C. 3C, 3C?
```
|
556,808 |
I have a table like this (the `C` column is blank):
```
A B C
1 19:30 23:00 (3.50)
2 14:15 18:30 (4.25)
```
I need to calculate the time difference in each row between column `A` and column `B` (always `B` - `A`), and put it in column `C` as a decimal number (as shown inside the parentheses).
Which formula should I use? Is it possible to generate a general formula, so I won't have to change the row number every time (maybe `INDIRECT`)?
|
2013/02/24
|
['https://superuser.com/questions/556808', 'https://superuser.com', 'https://superuser.com/users/165729/']
|
If you use MOD that will also work when the times cross midnight, e.g. in C2
`=MOD(B2-A2,1)*24`
copy formula down column and the row numbers will change automaticaly for each row
|
This will do the job:
```
=(B1-A1)*24
```
You might need to format the cell as number, not time!
|
67,169,129 |
I want to exclude only If ColumnA = 'SA' exclude ColumnB not like '%Prev%' and ColumnB not like '%old%'. If columnA = 'BA' I want to keep them. exp:
>
>
> ```
> select columnA
> from Table
> where columnA ='SA' and ColumnB not like '%Prev%' and ColumnB not like '%old%'
>
> ```
>
>
|
2021/04/19
|
['https://Stackoverflow.com/questions/67169129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5661085/']
|
You are trying to perform Integer operation on a list. 'lengths' is an ArrayList and operation % is non applicable to it. Also, I think you shouldn't use cloning here and just iterate over `list` and check if each element is odd - print it or add to another list if it is.
|
modify lengths methods
```
public static void main(String []args){
ArrayList<String>
list = new ArrayList<String>();
list.add("yoy");
list.add("lmao");
list.add("lol");
list.add("kk");
list.add("bbb");
ArrayList<String> lengths = lengths(list);
System.out.println(lengths.toString());
}
public static ArrayList<String> lengths(ArrayList<String> list) {
ArrayList<String> lengthList = new ArrayList<String>();
for (String s : list)
if(s.length() % 2 != 0)
lengthList.add(s);
return lengthList;
}
```
|
67,169,129 |
I want to exclude only If ColumnA = 'SA' exclude ColumnB not like '%Prev%' and ColumnB not like '%old%'. If columnA = 'BA' I want to keep them. exp:
>
>
> ```
> select columnA
> from Table
> where columnA ='SA' and ColumnB not like '%Prev%' and ColumnB not like '%old%'
>
> ```
>
>
|
2021/04/19
|
['https://Stackoverflow.com/questions/67169129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5661085/']
|
It's better to implement a separate method that copies the strings with odd length:
```java
public static List<String> oddLengths(List<String> list) {
List<String> result = new ArrayList<>();
for (String s : list) {
if (s.length() % 2 != 0) {
result.add(s);
}
}
return result;
}
```
Then just call this method in `main` method:
```java
List<String> list = new ArrayList<>();
list.add("yoy");
list.add("lmao");
list.add("lol");
list.add("kk");
list.add("bbb");
List<String> oddList = oddLengths(list);
System.out.println("Strings with odd length are: " + oddList);
```
Less efficient approach would be to copy the initial list and then remove all strings with *even* length using `removeIf` operation:
```java
List<String> oddList2 = new ArrayList<>(list); // no need to use clone
oddList2.removeIf(s -> s.length() % 2 == 0); // removing all strings with even length
System.out.println("Strings with odd length are: " + oddList2);
```
---
It is convenient to use Stream API with filter operation to achieve the same result:
```java
public static List<String> oddLengths(List<String> list) {
return list.stream()
.filter(s -> s.length() % 2 != 0)
.collect(Collectors.toList());
}
```
|
modify lengths methods
```
public static void main(String []args){
ArrayList<String>
list = new ArrayList<String>();
list.add("yoy");
list.add("lmao");
list.add("lol");
list.add("kk");
list.add("bbb");
ArrayList<String> lengths = lengths(list);
System.out.println(lengths.toString());
}
public static ArrayList<String> lengths(ArrayList<String> list) {
ArrayList<String> lengthList = new ArrayList<String>();
for (String s : list)
if(s.length() % 2 != 0)
lengthList.add(s);
return lengthList;
}
```
|
865,774 |
I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ?
---
I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.
|
2009/05/14
|
['https://Stackoverflow.com/questions/865774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']
|
You need to use the [Modifiers](http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.modifiers.aspx) property of the KeyEventArgs class.
Something like:
```
//asumming e is of type KeyEventArgs (such as it is
// on a KeyDown event handler
// ..
bool ctrlShiftM; //will be true if the combination Ctrl + Shift + M is pressed, false otherwise
ctrlShiftM = ((e.KeyCode == Keys.M) && // test for M pressed
((e.Modifiers & Keys.Shift) != 0) && // test for Shift modifier
((e.Modifiers & Keys.Control) != 0)); // test for Ctrl modifier
if (ctrlShiftM == true)
{
Console.WriteLine("[Ctrl] + [Shift] + M was pressed");
}
```
|
You can check using a technique similar to the following:
```
if(Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Shift)
```
This in combination with the normal key checks will give you the answer you seek.
|
865,774 |
I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ?
---
I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.
|
2009/05/14
|
['https://Stackoverflow.com/questions/865774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']
|
You need to use the [Modifiers](http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.modifiers.aspx) property of the KeyEventArgs class.
Something like:
```
//asumming e is of type KeyEventArgs (such as it is
// on a KeyDown event handler
// ..
bool ctrlShiftM; //will be true if the combination Ctrl + Shift + M is pressed, false otherwise
ctrlShiftM = ((e.KeyCode == Keys.M) && // test for M pressed
((e.Modifiers & Keys.Shift) != 0) && // test for Shift modifier
((e.Modifiers & Keys.Control) != 0)); // test for Ctrl modifier
if (ctrlShiftM == true)
{
Console.WriteLine("[Ctrl] + [Shift] + M was pressed");
}
```
|
I think its easiest to use this:
`if(e.KeyData == (Keys.Control | Keys.G))`
|
865,774 |
I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ?
---
I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.
|
2009/05/14
|
['https://Stackoverflow.com/questions/865774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']
|
I think its easiest to use this:
`if(e.KeyData == (Keys.Control | Keys.G))`
|
You can check using a technique similar to the following:
```
if(Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Shift)
```
This in combination with the normal key checks will give you the answer you seek.
|
17,608,853 |
I would like a for loop in jquery using `.html()`
like this:
```
.html('<select property="doctype" name="doctype"><%for (String number : list)
{%>'<option value="'<%=number%>'>'<%out.println(number); %>'</option>'<% } %>'</select>');
```
In Java's for each loop list it uses an object of `java.util.ArrayList<String>`.
Here the `.html();` function will call when we click on add button.
Here my question is it possible to write jsp scriplet code in .html() of jquery.
|
2013/07/12
|
['https://Stackoverflow.com/questions/17608853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2147478/']
|
```
<nav id="nav-single">
<?php
$prev_post = get_previous_post();
$id = $prev_post->ID ;
$permalink = get_permalink( $id );
?>
<?php
$next_post = get_next_post();
$nid = $next_post->ID ;
$permalink = get_permalink($nid);
?>
<span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">←</span> Previous', 'twentyeleven' ) ); ?>
<h2><a href="<?php echo $permalink; ?>"><?php echo $prev_post->post_title; ?></a></h2>
</span>
<span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
<h2><a href="<?php echo $permalink; ?>"><?php echo $next_post->post_title; ?></a></h2>
</span>
</nav>
```

|
I hope you are using this code in single.php from where the whole of the post is displayed. For displaying the links (Next/Prev), you need to check the function.
```
get_template_part()
in the same file (Single.php of your theme). In my case function in single.php has been passes parameters like
<?php get_template_part( 'content-single', get_post_format() ); ?>
So, you will open the "content-single.php" according to the parameters specified in the function and paste the same code
<div class="alignleftfp">
<?php next_post('%', '<img class="imgalign" src="' . get_bloginfo('template_directory') . '/images/1.png" alt="Next" /> ', 'no');
?>
</div>
```
```
<?php previous_post('%', '<img class="imgalign" src="' . get_bloginfo('template_directory') . '/images/2.png" alt="Next" /> ', 'no');
?>
</div>
below <h1 class="entry-title"><?php the_title(); ?></h1>
```
I hope this will solve your problem.
|
64,634,372 |
I develop an Angular app based on ASP.NET Core and there is some settings in `launchSettings.json` in order to run the app with the given ports as shown below:
```
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
},
"EmployeeProject.WebUI": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:6000;https://localhost:6001",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
```
However, I heard that these settings is **ignored** when using **VS Code** and when running the frontend and backend at the same time using `dotnet watch run` the app starts by using random ports in every run. So, how can I make the app starts using the same ports (6000 or 6001) via `dotnet run` or `dotnet watch run` in VS Code?
|
2020/11/01
|
['https://Stackoverflow.com/questions/64634372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/836018/']
|
If you want to do this the VS Code way, as long as you use F5 (or the Run > "Start Debugging" command), it's as simple as changing the `launch.json` file from this:
```json
...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
...
```
to this:
```json
...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "http://localhost:5001"
},
...
```
Otherwise, if you use the IIS Express profile, edit your `launchSettings.json` file to specify the port:
```json
"iisSettings": {
"iisExpress": {
"applicationUrl": "http://localhost:6000",
}
},
"profiles" : { ... }
```
|
Running from command line execute `Kastrel` server not `IIS`.
In that case probably configuration `appsettings.json` is use. You can put in this configuration section to control port:
```
"Kestrel": {
"Endpoints": {
"HTTP": {
"Url": "http://localhost:6000"
}
}
},
```
|
26,085,466 |
How can I shorten this function, so I don't need any of these `if`?
```
function showhide(element) {
$('body').on('click', '#'+element, function() {
if(element == 'export') {
$('.chat-export').toggle();
$('.chat-settings').hide();
$('.chat-users').hide();
} else if(element == 'settings') {
$('.chat-export').hide();
$('.chat-settings').toggle();
$('.chat-users').hide();
} else if(element == 'users') {
$('.chat-export').hide();
$('.chat-settings').hide();
$('.chat-users').toggle();
}
});
}
```
|
2014/09/28
|
['https://Stackoverflow.com/questions/26085466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/718990/']
|
Just do this:
```
$('[class^=chat]').each(function(){
if($(this).attr("class").indexOf(element) > -1){ $(this).toggle(); }
else { $(this).hide(); }
});
```
PS. The problem with my early code and antyrat's code is that when we hide everything, the toggle works unexpectedly.
[**DEMO**](http://jsfiddle.net/f3avLu2o/1/)
|
You can avoid this using this [`regex`](http://james.padolsey.com/javascript/regex-selector-for-jquery/) selector snippet for example:
```
$( 'div:regex(class, .chat-*)' ).hide();
$( '.chat-' + element ).toggle();
```
|
35,957,207 |
I got an error "android.database.CursorIndexOutOfBoundsException: Index 20 requested, with a size of 20" and I can't understand what exactly caused it and how to fix it? Probably something wrong with c.moveToFirst() and c.moveToNext().
```
public class MainActivity extends AppCompatActivity {
Map<Integer, String> articleURLs = new HashMap<Integer, String>();
Map<Integer, String> articleTitles =new HashMap<Integer, String>();
ArrayList<Integer> articleIds =new ArrayList<Integer>();
SQLiteDatabase articlesDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articlesDB=this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleId INTEGER, url VARCHAR, title VARCHAR, content VARCHAR)");
DownloadTask task = new DownloadTask();
try {
String result = task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();
JSONArray jsonArray =new JSONArray(result);
articlesDB.execSQL("DELETE FROM articles");
for (int i=5; i<25;i++){
String articleId = jsonArray.getString(i);
DownloadTask getArticle = new DownloadTask();
String articleInfo = getArticle.execute("https://hacker-news.firebaseio.com/v0/item/"+ articleId+".json?print=pretty").get();
JSONObject jsonObject= new JSONObject(articleInfo);
Log.i("jsonObject", jsonObject.toString());
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
String sql = "INSERT INTO articles (articleId, url, title) VALUES (?, ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.execute();
}
Cursor c = articlesDB.rawQuery("SELECT * FROM articles",null);
int articleIdIndex = c.getColumnIndex("articleId");
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
c.moveToFirst();
while (c!= null){
Log.i("articleIdIndex", Integer.toString(c.getInt(articleIdIndex)));
Log.i("articleUrl",c.getString(urlIndex) );
Log.i("titleTitle",c.getString(titleIndex));
c.moveToNext();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask< String, Void, String> {
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
}
catch(Exception e){
e.printStackTrace();
}
return result;
}
}
}
```
|
2016/03/12
|
['https://Stackoverflow.com/questions/35957207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5427240/']
|
Change the below lines to
```
c.moveToFirst();
while (c!= null){
Log.i("articleIdIndex", Integer.toString(c.getInt(articleIdIndex)));
Log.i("articleUrl",c.getString(urlIndex) );
Log.i("titleTitle",c.getString(titleIndex));
c.moveToNext();
}
```
to
```
while (c.moveToNext()) {
Log.i("articleIdIndex", Integer.toString(c.getInt(articleIdIndex)));
Log.i("articleUrl",c.getString(urlIndex) );
Log.i("titleTitle",c.getString(titleIndex));
}
```
>
> The condition `(c!= null)` will always be `true`, so while loop will be executed every time even when there are no more records in database. So change the condition in while loop to `c.moveToNext()` so that it'll get record only when there are more records in database.
>
>
>
And it'll work fine.
|
Change the below code
```
Cursor c = articlesDB.rawQuery("SELECT * FROM articles",null);
int articleIdIndex = c.getColumnIndex("articleId");
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
c.moveToFirst();
while (c!= null){
Log.i("articleIdIndex", Integer.toString(c.getInt(articleIdIndex)));
Log.i("articleUrl",c.getString(urlIndex) );
Log.i("titleTitle",c.getString(titleIndex));
c.moveToNext();
}
```
to the following
```
Cursor c = articlesDB.rawQuery("SELECT * FROM articles",null);
int articleIdIndex = c.getColumnIndex("articleId");
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
if(c.moveToFirst())
do{
Log.i("articleIdIndex", Integer.toString(c.getInt(articleIdIndex)));
Log.i("articleUrl",c.getString(urlIndex) );
Log.i("titleTitle",c.getString(titleIndex));
}while(c.moveToNext());
```
|
13,362,921 |
According to AngularJS's tutorial, a controller function just sits within the global scope.
<http://docs.angularjs.org/tutorial/step_04>
Do the controller functions themselves automatically get parsed into an encapsulated scope, or do they dwell within the global scope? I know that they are passed a reference to their own $scope, but it appears that the function themselves are just sitting in the global scope. Obviously this can cause problems down the road, and I have learned through experience and education to encapsulate Further more, if they do dwell within the global scope, would it not be considered a best practice to encapsulate them within an object to be referenced like this:
```
Object.functionName();
```
Rather than this:
```
functionName();
```
So as to prevent issues that occur with the pollution of the global scope (ie overriding functions, etc..)
|
2012/11/13
|
['https://Stackoverflow.com/questions/13362921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1707160/']
|
AngularJS supports 2 methods of registering controller functions - either as globally accessible functions (you can see this form in the mentioned tutorial) or as a part of a modules (that forms a kind of namespace). More info on modules can be found here: <http://docs.angularjs.org/guide/module> but in short one would register a controller in a module like so:
```
angular.module('[module name]', []).controller('PhoneListCtrl', function($scope) {
$scope.phones = [..];
$scope.orderProp = 'age';
});
```
AngularJS uses a short, global-function form of declaring controllers in many examples but while **this form is good for quick samples it rather shouldn't be used in real-life applications**.
In short: AngularJS makes it possible to properly encapsulate controller functions but also exposes a simpler, quick & dirty way of declaring them as global functions.
|
You can register a controller as part of a module, as answered by [pkozlowski-opensource](https://stackoverflow.com/a/13363482/1957398).
If you need minification you can simply extend this by providing the variable names before the actual function in a list:
```
angular.module('[module name]', []).
controller('PhoneListCtrl', ['$scope', function($scope) {
$scope.phones = [..];
$scope.orderProp = 'age';
}]);
```
This will work the same after "minification":
```
angular.module('[module name]', []).
controller('PhoneListCtrl', ['$scope', function(s) {
s.phones = [..];
s.orderProp = 'age';
}]);
```
This notation can be found under "Inline Annotation" at [Dependency Injection](http://docs.angularjs.org/guide/di).
To test a controller, that has been registered as part of a module, you have to ask angular to create your controller. For example:
```
describe('PhoneListCtrl test', function() {
var scope;
var ctrl;
beforeEach(function() {
module('[module name]');
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('[module name]', {$scope: scope});
});
});
it('should be ordered by age', function() {
expect(scope.orderProp).toBe('age');
});
});
```
This method of testing the controller can be found under "Testing Controllers" at [Understanding the Controller Component](http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.