qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
25,279,044 |
I am trying to integrate `SonarQube` to generate report on my `iOS project`,
I am using [Objective-C Sonar plugin](https://github.com/octo-technology/sonar-objective-c)
When i run `./run-sonar.sh`
`OCLint` generates a `compile_commands.json` file in my root directory.
and after that getting following error
```
11:24:39.782 INFO - Processing OCLint report /Users/.......app/./sonar-reports/oclint.xml
11:24:39.899 ERROR - Reporting 1073 violations.
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
Total time: 16.240s
Final Memory: 6M/86M
INFO: ------------------------------------------------------------------------
ERROR: Error during Sonar runner execution
org.sonar.runner.impl.RunnerException: Unable to execute Sonar
at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91)
at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
at java.security.AccessController.doPrivileged(Native Method)
at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
at org.sonar.runner.api.Runner.execute(Runner.java:100)
at org.sonar.runner.Main.executeTask(Main.java:70)
at org.sonar.runner.Main.execute(Main.java:59)
at org.sonar.runner.Main.main(Main.java:53)
Caused by: The rule 'OCLint:ivar assignment outside accessors or init' does not exist.
```
Can any one help me on this issue?
Thanks
AMR
Thnaks
|
2014/08/13
|
[
"https://Stackoverflow.com/questions/25279044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3936042/"
] |
I had a similar error. My sonar server had two objective-c code analyser plugin. The [Sonar Plugin for Objective C (free)](https://github.com/octo-technology/sonar-objective-c) and [SonarSource Objective-C plugin (commercial)](http://www.sonarsource.com/products/plugins/languages/objective-c/)
When I removed (uninstalled) one of the plugin from sonar server the error stopped to occur
|
I am not sure what version of the objective-c-sonar plugin that you were using.
I solved similar issue before.
Goto `${SONAR_INSTALLATION_FOLDER}/extensions/plugins/`, copy the `sonar-objective-c-plugin-${version}.jar` to somewhere else.
unzip the jar file, and edit below file
`org/sonar/plugins/objectivec/profile-oclint.xml`
Add the rule you are missing following the layout of the xml file,
may be look similar below
```
<rule>
<repositoryKey>OCLint</repositoryKey>
<key>ivar assignment outside accessors or init</key>
</rule>
```
And edit another file `org/sonar/plugins/objectivec/rules-oclint.xml`
```
<rule>
<key>ivar assignment outside accessors or init</key>
<name>ivar assignment outside accessors or init</name>
<priority>MAJOR</priority>
<description>ivar assignment outside accessors or init</description>
</rule>
```
And then using zip to package the files unpacked as the new jar file.
Override the original plugin jar file in `${SONAR_INSTALLATION_FOLDER}/extensions/plugins/`, restart the sonar, issue could be gone.
Repeat the step for all similar issues you encountered.
|
25,279,044 |
I am trying to integrate `SonarQube` to generate report on my `iOS project`,
I am using [Objective-C Sonar plugin](https://github.com/octo-technology/sonar-objective-c)
When i run `./run-sonar.sh`
`OCLint` generates a `compile_commands.json` file in my root directory.
and after that getting following error
```
11:24:39.782 INFO - Processing OCLint report /Users/.......app/./sonar-reports/oclint.xml
11:24:39.899 ERROR - Reporting 1073 violations.
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
Total time: 16.240s
Final Memory: 6M/86M
INFO: ------------------------------------------------------------------------
ERROR: Error during Sonar runner execution
org.sonar.runner.impl.RunnerException: Unable to execute Sonar
at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91)
at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
at java.security.AccessController.doPrivileged(Native Method)
at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
at org.sonar.runner.api.Runner.execute(Runner.java:100)
at org.sonar.runner.Main.executeTask(Main.java:70)
at org.sonar.runner.Main.execute(Main.java:59)
at org.sonar.runner.Main.main(Main.java:53)
Caused by: The rule 'OCLint:ivar assignment outside accessors or init' does not exist.
```
Can any one help me on this issue?
Thanks
AMR
Thnaks
|
2014/08/13
|
[
"https://Stackoverflow.com/questions/25279044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3936042/"
] |
I had a similar error too with the last version of this [plugin](https://github.com/Backelite/sonar-objective-c "plugin") which is a fork of the one you used.
I downgrade my OCLint version from 0.11 to 0.10.1 and everything work perfectly.
It seems that the OCLint rules defined in the plugin was different of the OCLint version installed on my server.
|
I am not sure what version of the objective-c-sonar plugin that you were using.
I solved similar issue before.
Goto `${SONAR_INSTALLATION_FOLDER}/extensions/plugins/`, copy the `sonar-objective-c-plugin-${version}.jar` to somewhere else.
unzip the jar file, and edit below file
`org/sonar/plugins/objectivec/profile-oclint.xml`
Add the rule you are missing following the layout of the xml file,
may be look similar below
```
<rule>
<repositoryKey>OCLint</repositoryKey>
<key>ivar assignment outside accessors or init</key>
</rule>
```
And edit another file `org/sonar/plugins/objectivec/rules-oclint.xml`
```
<rule>
<key>ivar assignment outside accessors or init</key>
<name>ivar assignment outside accessors or init</name>
<priority>MAJOR</priority>
<description>ivar assignment outside accessors or init</description>
</rule>
```
And then using zip to package the files unpacked as the new jar file.
Override the original plugin jar file in `${SONAR_INSTALLATION_FOLDER}/extensions/plugins/`, restart the sonar, issue could be gone.
Repeat the step for all similar issues you encountered.
|
38,811,533 |
I am using RecyclerView for showing my list. I implement Swipe to dismiss on the RecyclerView with ItemTouchHelper. The underlying layout is implemented in OnchildDraw method by using canvas.
Now I have a problem: I want to set onclick on my icon. By clicking on the icon, I want to do some functions.
Here is My class:
```
public class ItemTouchHelperCallback : ItemTouchHelper.SimpleCallback
{
private ContactSearchedResultAdapter _adapter;
private RecyclerView _mRecyclerView;
private int _swipeCount;
private Android.Content.Res.Resources _resources;
public ItemTouchHelperCallback(ContactSearchedResultAdapter adapter, RecyclerView mRecyclerView, Android.Content.Res.Resources resources)
: base(0, ItemTouchHelper.Left | ItemTouchHelper.Right)
{
this._adapter = adapter;
this._mRecyclerView = mRecyclerView;
this._resources = resources;
}
public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
{
return false;
}
public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
{
if (direction == ItemTouchHelper.Left)
{
_adapter.RemoveViewWithDialog(viewHolder.AdapterPosition, _mRecyclerView, _swipeCount);
if (_swipeCount == 0)
_swipeCount++;
}
else
{
_adapter.SaveContactToDataBase(viewHolder.AdapterPosition, _mRecyclerView);
}
}
public override void OnChildDraw(Canvas cValue, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
{
Paint paint = new Paint();
View itemView = viewHolder.ItemView;
float height = (float)itemView.Bottom - (float)itemView.Top;
float width = height / 3;
Bitmap icon;
if (dX > 0)
{
paint.Color = Color.ParseColor("#388E3C");
RectF background = new RectF((float)itemView.Left, (float)itemView.Top, dX, (float)itemView.Bottom);
cValue.DrawRect(background, paint);
icon = BitmapFactory.DecodeResource(_resources, Resource.Drawable.addoption);
RectF icon_dest = new RectF((float)itemView.Left + width, (float)itemView.Top + width, (float)itemView.Left + 2 * width, (float)itemView.Bottom - width);
cValue.DrawBitmap(icon, null, icon_dest, paint);
}
else
{
paint.Color = Color.ParseColor("#D32F2F");
RectF background = new RectF((float)itemView.Right + dX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
cValue.DrawRect(background, paint);
icon = BitmapFactory.DecodeResource(_resources, Resource.Drawable.removeoption);
RectF icon_dest = new RectF((float)itemView.Right - 2 * width, (float)itemView.Top + width, (float)itemView.Right - width, (float)itemView.Bottom - width);
cValue.DrawBitmap(icon, null, icon_dest, paint);
}
float alpha = (float)1.0- Math.Abs(dX)/(float) itemView.Width;
itemView.Alpha = alpha;
itemView.TranslationX = dX;
base.OnChildDraw(cValue, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
```
As you can see I am calling ItemRemoving or ItemSaving in OnSwiped method. What I want to do now is calling these methods on icons' click (icons that are drawn by canvas in OnchildDraw)
I searched a lot about this topic and couldn't find any solution that implemented this feature without using any library.
I don't want to use library.
|
2016/08/07
|
[
"https://Stackoverflow.com/questions/38811533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6687286/"
] |
I had the same problem as yours. I coded half a day and finally find one way.
First of all, I think this is android ItemTouchHelper problem that there are no methods to solve that.
So it can't use ItemTouchHelper and other system methods.
What I do is this:
1. Set recylerView.setOnTouchListener to get (x,y) on screen.
2. When ItemTouchHelper onSwiped(), set it a state and find the clickable region.
3. Check your touch point if it hits the icon region.
4. Do something when hitted in your onTouch() method.
You can find my solution on my Github repo.
<https://github.com/TindleWei/WindGod>
Here 3 ways to use ItemTouchHelper:
1. android normal way like yours
2. foregound and background region way
3. viewpager way
On my repo, you can look at 2nd way.
|
For those using AdamWei's solution number 2, if you're having trouble with the the recyclerview ontouchlistener in a fragment, change the following line:
```
Point point = new Point((int)motionEvent.getRawX(), (int)motionEvent.getRawY());
```
to
```
Point point = new Point((int) motionEvent.getX(), (int) motionEvent.getY());
```
|
4,788,600 |
Hi so lately I've been doing a lot of java programming and I've been using a lot of if statements. the problem is i have to copy and paste the if statements over a hundred times to check all the senarios. Here is an example:
```
while (i < AreaNumbers.size()) {
String roomnum = "j" + AreaNumbers.get(i);
if (roomnum.equals("j100")) {
if (k == 1) {
j100.setVisible(true);
j100.setToolTipText("<html>" + "<br>" + "Room Number: " + AreaNumbers.get(i) + "<br>" + "Incident ID: " + IncidentID.get(i) + "<br>" + " Teacher: " + Teachers.get(i) + "<br>" + " Description: " + Descriptions.get(i) + "</html>");
k = k + 1;
} else if (k > 0) {
j100.setToolTipText(k + " help desk calls, click here for more information");
k = k + 1;
}
```
for this example i would copy and paste the `if (roomnum.equals("j100")) {` and everything past it for every label i want to check and compare. Is there anyway i could do this where i could write a statement that goes through this same scenario once and everywhere it sees `j100` it could replace it after each time with a different label, such as j101 j107 an so on. Im sorry if this isnt very clear i just cant think of a better way to word it. Thanks in advance.
|
2011/01/24
|
[
"https://Stackoverflow.com/questions/4788600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569027/"
] |
Don't use numbered variable names (like `j100`, `j101`, etc.). Use an array instead, so you can loop over them programatically:
```
SomeType[] j = new SomeType[1000];
for (int z = 0; z < j.length; z++) {
j[z] = new SomeType();
j[z].setTooltipText("Hello world");
}
```
Depending on what you need to do, you may want to investigate the more advanced [collections classes](http://download.oracle.com/javase/tutorial/collections/intro/index.html) instead of simple arrays.
|
you could use a `Map<String, Runnable>` using the label as the key and to a `Runnable`. Depending on how you write you Runnable subclasses, this could alleviate a lot of redundancy.
```
if( myMap.containsKey( myLabel ) ) {
myMap.get(myLabel).run();
}
```
|
17,243 |
Last night I was at a wedding, and when I stood up as the bride was passing by on the way to the Chuppa, a fellow in all seriousness told me "It is not proper and a lack of Tzniyus to stand up for the bride". I told him that I am certain that there is a valid source for doing so as we see that it is a Minhag Yisroel that people stand up when the bride passes by. What is the source?
|
2012/06/22
|
[
"https://judaism.stackexchange.com/questions/17243",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/200/"
] |
See [Halachically Speaking (Volume 4, Issue 12, Page 8)](http://www.thehalacha.com/attach/Volume4/Issue12.pdf) where the author brings that many poskim [see footnote 108 for names] actually say to stand the *entire* Chuppah. (One reason given is because the Chosson is doing a Mitzvah, so we stand in his honor). Common custom however, is not like that.
He then goes on to say:
>
> It is customary to stand when the chosson and kallah walk down the aisle. Some say this is out of respect for the chosson and kallah.
>
>
>
He brings [Knesses Hagedolah E.H. 62](http://hebrewbooks.org/pdfpager.aspx?req=14596&pgnum=88)[:2] as a source for that last reason [though the Knesses Hagedolah is referring to standing for the Chuppah Berachos].
So there you have it: a source.
|
I have heard it comes from [the *mishna* (*Bikurim*)](http://he.wikisource.org/wiki/%D7%9E%D7%A9%D7%A0%D7%94_%D7%91%D7%9B%D7%95%D7%A8%D7%99%D7%9D_%D7%92_%D7%92) that says people in Jerusalem would stand and greet people bringing *bikurim*, on which [the *g'mara* (*Kidushin*)](http://www.e-daf.com/index.asp?ID=2692&size=1) says *chaviva mitzva b'sha'tah*, a *mitzva* at its right time is beloved [and we stand up for the one doing it].
However, I'll have to find the source that connects that to a bride (and groom).
See also the comments on this answer.
|
17,243 |
Last night I was at a wedding, and when I stood up as the bride was passing by on the way to the Chuppa, a fellow in all seriousness told me "It is not proper and a lack of Tzniyus to stand up for the bride". I told him that I am certain that there is a valid source for doing so as we see that it is a Minhag Yisroel that people stand up when the bride passes by. What is the source?
|
2012/06/22
|
[
"https://judaism.stackexchange.com/questions/17243",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/200/"
] |
I have heard it comes from [the *mishna* (*Bikurim*)](http://he.wikisource.org/wiki/%D7%9E%D7%A9%D7%A0%D7%94_%D7%91%D7%9B%D7%95%D7%A8%D7%99%D7%9D_%D7%92_%D7%92) that says people in Jerusalem would stand and greet people bringing *bikurim*, on which [the *g'mara* (*Kidushin*)](http://www.e-daf.com/index.asp?ID=2692&size=1) says *chaviva mitzva b'sha'tah*, a *mitzva* at its right time is beloved [and we stand up for the one doing it].
However, I'll have to find the source that connects that to a bride (and groom).
See also the comments on this answer.
|
Quotes from two of Rabbi Leib Tropper's *Shoel Umaishiv* emails:
**Dec 24, '15:**
>
> Rav Moshe [Feinstein], zt'l took the position that the choson only earns the status
> of 'Choson' after the chupah.β Therefore if after the Choson's Tish
> people would daven mincha he would also say β'Tachnun'. He would not
> stand up for the Choson or the Kalah as they walk to the Chupah since
> they do not have the status of Choson & Kalah until after the chupah.
>
>
>
**Nov 19, '12:**
>
> Maran Harav Moshe [Feinstein], zt'l did not stand up for the choson & kallah as they
> walked to the chupah. Rav Moshe's position is that they are not a
> Choson or Kallah until after the chupah.
>
>
> He also did not exempt the choson from tachnun at mincha before the
> Chupah as he is not considered a choson until after The chupah.
>
>
> There are other poskim who concur with this psak.
>
>
>
|
17,243 |
Last night I was at a wedding, and when I stood up as the bride was passing by on the way to the Chuppa, a fellow in all seriousness told me "It is not proper and a lack of Tzniyus to stand up for the bride". I told him that I am certain that there is a valid source for doing so as we see that it is a Minhag Yisroel that people stand up when the bride passes by. What is the source?
|
2012/06/22
|
[
"https://judaism.stackexchange.com/questions/17243",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/200/"
] |
See [Halachically Speaking (Volume 4, Issue 12, Page 8)](http://www.thehalacha.com/attach/Volume4/Issue12.pdf) where the author brings that many poskim [see footnote 108 for names] actually say to stand the *entire* Chuppah. (One reason given is because the Chosson is doing a Mitzvah, so we stand in his honor). Common custom however, is not like that.
He then goes on to say:
>
> It is customary to stand when the chosson and kallah walk down the aisle. Some say this is out of respect for the chosson and kallah.
>
>
>
He brings [Knesses Hagedolah E.H. 62](http://hebrewbooks.org/pdfpager.aspx?req=14596&pgnum=88)[:2] as a source for that last reason [though the Knesses Hagedolah is referring to standing for the Chuppah Berachos].
So there you have it: a source.
|
The Jewish Press of the week of January 9, 2016, brings a small piece by Rabbi Soleveitchik saying the tzibbur stands when the chassan and kallah walk down the aisle to honor the parents that are bringing their children to do the mitzvah of kiddushin. I think he also mentions the mishnah in bikkurim as a source to why we stand to honor the parents in this case
|
17,243 |
Last night I was at a wedding, and when I stood up as the bride was passing by on the way to the Chuppa, a fellow in all seriousness told me "It is not proper and a lack of Tzniyus to stand up for the bride". I told him that I am certain that there is a valid source for doing so as we see that it is a Minhag Yisroel that people stand up when the bride passes by. What is the source?
|
2012/06/22
|
[
"https://judaism.stackexchange.com/questions/17243",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/200/"
] |
See [Halachically Speaking (Volume 4, Issue 12, Page 8)](http://www.thehalacha.com/attach/Volume4/Issue12.pdf) where the author brings that many poskim [see footnote 108 for names] actually say to stand the *entire* Chuppah. (One reason given is because the Chosson is doing a Mitzvah, so we stand in his honor). Common custom however, is not like that.
He then goes on to say:
>
> It is customary to stand when the chosson and kallah walk down the aisle. Some say this is out of respect for the chosson and kallah.
>
>
>
He brings [Knesses Hagedolah E.H. 62](http://hebrewbooks.org/pdfpager.aspx?req=14596&pgnum=88)[:2] as a source for that last reason [though the Knesses Hagedolah is referring to standing for the Chuppah Berachos].
So there you have it: a source.
|
Quotes from two of Rabbi Leib Tropper's *Shoel Umaishiv* emails:
**Dec 24, '15:**
>
> Rav Moshe [Feinstein], zt'l took the position that the choson only earns the status
> of 'Choson' after the chupah.β Therefore if after the Choson's Tish
> people would daven mincha he would also say β'Tachnun'. He would not
> stand up for the Choson or the Kalah as they walk to the Chupah since
> they do not have the status of Choson & Kalah until after the chupah.
>
>
>
**Nov 19, '12:**
>
> Maran Harav Moshe [Feinstein], zt'l did not stand up for the choson & kallah as they
> walked to the chupah. Rav Moshe's position is that they are not a
> Choson or Kallah until after the chupah.
>
>
> He also did not exempt the choson from tachnun at mincha before the
> Chupah as he is not considered a choson until after The chupah.
>
>
> There are other poskim who concur with this psak.
>
>
>
|
17,243 |
Last night I was at a wedding, and when I stood up as the bride was passing by on the way to the Chuppa, a fellow in all seriousness told me "It is not proper and a lack of Tzniyus to stand up for the bride". I told him that I am certain that there is a valid source for doing so as we see that it is a Minhag Yisroel that people stand up when the bride passes by. What is the source?
|
2012/06/22
|
[
"https://judaism.stackexchange.com/questions/17243",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/200/"
] |
The Jewish Press of the week of January 9, 2016, brings a small piece by Rabbi Soleveitchik saying the tzibbur stands when the chassan and kallah walk down the aisle to honor the parents that are bringing their children to do the mitzvah of kiddushin. I think he also mentions the mishnah in bikkurim as a source to why we stand to honor the parents in this case
|
Quotes from two of Rabbi Leib Tropper's *Shoel Umaishiv* emails:
**Dec 24, '15:**
>
> Rav Moshe [Feinstein], zt'l took the position that the choson only earns the status
> of 'Choson' after the chupah.β Therefore if after the Choson's Tish
> people would daven mincha he would also say β'Tachnun'. He would not
> stand up for the Choson or the Kalah as they walk to the Chupah since
> they do not have the status of Choson & Kalah until after the chupah.
>
>
>
**Nov 19, '12:**
>
> Maran Harav Moshe [Feinstein], zt'l did not stand up for the choson & kallah as they
> walked to the chupah. Rav Moshe's position is that they are not a
> Choson or Kallah until after the chupah.
>
>
> He also did not exempt the choson from tachnun at mincha before the
> Chupah as he is not considered a choson until after The chupah.
>
>
> There are other poskim who concur with this psak.
>
>
>
|
62,184,952 |
I have written few lines of code using javascript in Vue framework. I can not display date on html from var. I used vue-bootstrap for styles. Any suggestion is app?
```
<template>
<div class="app">
<b-form-datepicker id="datepicker" class="weekpicker" placeholder="Select a week" local="en"></b-form-datepicker>
<div class="w-75 p-3 mb-1 text-light">
<b-form-select class="weekpicker" onfocus="myFunction()">
<b-form-select-option hidden value="">Select a week</b-form-select-option>
<b-form-select-option id="mydate" value="">{{ myFunction() }}</b-form-select-option>
<b-form-select-option type="date" value=""></b-form-select-option>
<b-form-select-option type="date" value=""></b-form-select-option>
</b-form-select>
</div>
<button><span>Submit</span></button>
</div>
</template>
<script>
export default {
name: 'TS_home',
data() {
return {
};
},
methods: {
myFunction() {
let x = new Date();
let current_date = x.toDateString();
x.setDate(x.getDate() + 7);
let seventh_date = x.toDateString()
document.getElementById("mydate").innerHTML = current_date + " - " + seventh_date;
}
}
};
</script>
```
|
2020/06/04
|
[
"https://Stackoverflow.com/questions/62184952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13401826/"
] |
As @Phil said since you are using Vue you should define the data property for the date like so:
```
data() {
return {
myDate: null
}
}
```
When it comes to date pickers it is usually `@change` event or `v-model`.
Try:
```
<b-form-datepicker id="datepicker" class="weekpicker" placeholder="Select a week" local="en" @change="myDate=$event"></b-form-datepicker>
```
Then display the property in your HTML template like:
```
{{myDate}}
```
**Another** possibility is to use [vue-bootstrap](https://www.npmjs.com/package/vue-bootstrap-datetimepicker) if that is not what you have installed already. You would do it like this:
```
npm install vue-bootstrap-datetimepicker --save
```
then in your component
```
// Import required dependencies
import 'bootstrap/dist/css/bootstrap.css';
// Import this component
import datePicker from 'vue-bootstrap-datetimepicker';
```
then in your data
```
data() {
return {
myDate: new Date(),
options: {
format: 'DD/MM/YYYY',
useCurrent: false,
}
}
}
```
and in your HTML template
```
<date-picker v-model="myDate" :config="options"></date-picker>
```
and to display that date you would again use:
```
{{myDate}}
```
Please refer to the [documentation](https://www.npmjs.com/package/vue-bootstrap-datetimepicker) for more detailed information.
I hope it helps. Good luck.
|
You should use the data property instead of manipulating the dom
```
data() {
return {
myDate: ''
}
}
```
Inside the function
```
myFunction() {
let x = new Date();
let current_date = x.toDateString();
x.setDate(x.getDate() + 7);
let seventh_date = x.toDateString()
this.myDate = current_date + " - " + seventh_date;
}
```
In the html, use the vue-event handler
```
<b-form-select class="weekpicker" @focus="myFunction()">
```
```
<b-form-select-option id="mydate" value="">{{ myDate }}</b-form-select-option>
```
Hope this will help :)
|
1,702,651 |
Have seen a lot of conflicting information when trying to google this -- people claiming they did it successfully and others claiming it is impossible.
I have a laptop with USB-C out, but it does not support Thunderbolt, DP-altmode, or HDMI-altmode.
Does there exist a way to output to a HDMI monitor via this port? Obviously it can't output direct video signal but I thought it might be possible for the display content to be just sent as data like any other data transfer and reassembled to HDMI by the hub. I understand this would not be a great refresh rate due to the lower bandwidth of the port.
If so, what should I look for in specifications of hubs to buy?
I got burned by buying a hub that seemed to claim this functionality but it didn't work, and contacting the manufacturer, they said it only worked on DP USB-C ports (which they didn't bother to mention in their specifications).
|
2022/02/01
|
[
"https://superuser.com/questions/1702651",
"https://superuser.com",
"https://superuser.com/users/320374/"
] |
>
> I have a laptop with USB-C out, but it does not support Thunderbolt, DP-altmode, or HDMI-altmode.
> Does there exist a way to output to a HDMI monitor via this port?
>
>
>
Yes.
>
> If so, what should I look for in specifications of hubs to buy?
>
>
>
DisplayLink.
I don't know if there are other brands of USB graphics processor units but DisplayLink is certainly popular. Make note this is Display***Link***, not Display***Port***, they are very different in spite of the similar name and function. There are USB-C docks and adapters with DisplayLink GPUs in them to allow video over the USB protocol. DisplayLink adapters/docks/whatever will not work without drivers which makes them unique from DisplayPort adapters. Because they require drivers it means only certain operating systems are supported, as opposed to working on things like a Nintendo Switch where there's no ability to install drivers.
Most adapters from USB-C to HDMI rely on the host to supply a DisplayPort video signal to their USB-C port, and the adapter then converts this DisplayPort video protocol into the HDMI protocol. DisplayLink is a different beast in that it is its own GPU, which is why it appears as a unique output in the operating system display settings. You can have it be an extension to the desktop because it is a separate GPU, a protocol adapter can't do that.
As you noted in another answer a USB-A to HDMI adapter will work, and they work because there is a DisplayLink GPU inside. This is not all that different than any USB-C adapter with DisplayLink. The USB-A adapter may be the cheaper option because of economy of scale, like many things they are cheaper by the dozen and USB-C adapters would not be as popular. There may be some more capable DisplayLink HDMI adapters specifically for USB-C that take advantage of the higher power and bandwidth that USB-C allows, I didn't look close enough at the product offerings to know. Point is that you are not likely to be missing out by taking the route of using a USB-C to USB-A adapter then plugging in a DisplayLink cable, dock, or adapter.
|
A technically correct answer (the best kind) - I have successfully managed this by getting a USB-A to HDMI adapter and plugging it into the USB-A output port of the USB-C hub whose HDMI port doesn't work.
|
11,883,479 |
I develop yii application and have CGridView with many columns. I want to scroll the CGridView horizontal but can't find how.
|
2012/08/09
|
[
"https://Stackoverflow.com/questions/11883479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610094/"
] |
You can put grid into container with fixed `width` and `overflow: auto;`.
```
<div class="CGridViewContainer">
<!-- CGridView here -->
</div>
```
And CSS:
```
.CGridViewContainer { width: 960px; overflow: auto; }
```
But I believe that spanning of the columns will be better way of presenting the table. Don't know how to make headers or is it possible w/o modifications.
|
If you set `overflow: scroll-x` on the CSS for your grid, that should setup horizontal scrolling in your browser
|
107,984 |
I am trying to find a plugin or another method to block Firefox with a master password, so that a user can only use Firefox if the correct password is entered.
Can you suggest a plugin or if Windows 7 has this kind of blocking feature built in?
|
2010/02/12
|
[
"https://superuser.com/questions/107984",
"https://superuser.com",
"https://superuser.com/users/11324/"
] |
It's likely you're going about your "trying to lock down the machine" approach in a non typical way, and will struggle to correctly secure it.
You're probably better off having additional login accounts with restricted access, that way those users will not have access to what ever it is you're trying to protect in your specific firefox install (history, saved passwords, etc).
If your concern is only for:
* Privacy, then clear your history or set it up to clear on exit / per day.
* Passwords, then use the built in master password system in firefox.
|
Well, you can use the UAC feature of Win7 to block it. But then you have to provide password for each application u run.. Anyway, its the best hand you have..
```
To change the elevation prompt behavior for standard users
1. Click Start, click Accessories, click Run, type secpol.msc in the Open box, and then click OK.
2. From the Local Security Settings console tree, click Local Policies, and then Security Options.
3. Scroll down to and double-click User Account Control: Behavior of the elevation prompt for standard users.
4. From the drop-down menu, select one of the following settings:
* Automatically deny elevation requests (standard users will not be able to run programs requiring elevation, and will not be prompted)
* Prompt for credentials (this setting requires user name and password input before an application or task will run as elevated, and is the default for standard users)
5. Click OK.
6. Close the Local Security Settings window.
```
Or, another scope is to use a firefox that'll require users other than you to enter a password when they try to access your saved password or bookmarks etc(i.e. your profile data)..
To set that,
```
Tools > Options > Security tab > Tick "Use master password" ..
```
You'll get a prompt saying what you need to do next..
|
107,984 |
I am trying to find a plugin or another method to block Firefox with a master password, so that a user can only use Firefox if the correct password is entered.
Can you suggest a plugin or if Windows 7 has this kind of blocking feature built in?
|
2010/02/12
|
[
"https://superuser.com/questions/107984",
"https://superuser.com",
"https://superuser.com/users/11324/"
] |
**[WinGuard Pro](http://www.winguardpro.com/index.html)** locks any file, folder or program on your computer.

|
It's likely you're going about your "trying to lock down the machine" approach in a non typical way, and will struggle to correctly secure it.
You're probably better off having additional login accounts with restricted access, that way those users will not have access to what ever it is you're trying to protect in your specific firefox install (history, saved passwords, etc).
If your concern is only for:
* Privacy, then clear your history or set it up to clear on exit / per day.
* Passwords, then use the built in master password system in firefox.
|
107,984 |
I am trying to find a plugin or another method to block Firefox with a master password, so that a user can only use Firefox if the correct password is entered.
Can you suggest a plugin or if Windows 7 has this kind of blocking feature built in?
|
2010/02/12
|
[
"https://superuser.com/questions/107984",
"https://superuser.com",
"https://superuser.com/users/11324/"
] |
**[WinGuard Pro](http://www.winguardpro.com/index.html)** locks any file, folder or program on your computer.

|
Well, you can use the UAC feature of Win7 to block it. But then you have to provide password for each application u run.. Anyway, its the best hand you have..
```
To change the elevation prompt behavior for standard users
1. Click Start, click Accessories, click Run, type secpol.msc in the Open box, and then click OK.
2. From the Local Security Settings console tree, click Local Policies, and then Security Options.
3. Scroll down to and double-click User Account Control: Behavior of the elevation prompt for standard users.
4. From the drop-down menu, select one of the following settings:
* Automatically deny elevation requests (standard users will not be able to run programs requiring elevation, and will not be prompted)
* Prompt for credentials (this setting requires user name and password input before an application or task will run as elevated, and is the default for standard users)
5. Click OK.
6. Close the Local Security Settings window.
```
Or, another scope is to use a firefox that'll require users other than you to enter a password when they try to access your saved password or bookmarks etc(i.e. your profile data)..
To set that,
```
Tools > Options > Security tab > Tick "Use master password" ..
```
You'll get a prompt saying what you need to do next..
|
26,901 |
If the polarity changes every time the AC switches, then why doesn't the capacitor explode?
|
2012/02/20
|
[
"https://electronics.stackexchange.com/questions/26901",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/8210/"
] |
As clabacchio said, some capacitors are unpolarized, so it's perfectly fine to put positive and negative voltages on them.
However, it is still possible to put a AC signal thru a polarized capacitor. This is done by adding a DC bias of at least half the AC peak-peak voltage. The entire signal is then still positive, but AC-wise the capacitor acts on it normally.
Nowadays, polarized capacitors are mostly used for bulk storage on power supplies to reduce ripple and to provide short term high current. A nominal 12V supply, for example, may have 1Vpp AC ripple on it. That means the voltage is from 11.5V to 12.5V, which is fine for a electrolytic or other polarized cap. However, the large value of the cap will be applied to providing current to counter the 1Vpp AC voltage swing.
Put another way, polarized caps must always have a positive *voltage* on them, but there is no such restriction on *current*.
|
Because not all the capacitors have a polarity. As far as I know, only electrolytic capacitors have a fixed polarity, while for instance ceramic capacitors don't.
If you look at the schematics, you will see that (in proper designs) electrolytic, or in general capacitors with a polarization, have the negative shield curved and a *plus* sign in the positive shield; the other capacitors are symmetric, so you cannot say which is the direction if not by the label.
|
26,901 |
If the polarity changes every time the AC switches, then why doesn't the capacitor explode?
|
2012/02/20
|
[
"https://electronics.stackexchange.com/questions/26901",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/8210/"
] |
Because not all the capacitors have a polarity. As far as I know, only electrolytic capacitors have a fixed polarity, while for instance ceramic capacitors don't.
If you look at the schematics, you will see that (in proper designs) electrolytic, or in general capacitors with a polarization, have the negative shield curved and a *plus* sign in the positive shield; the other capacitors are symmetric, so you cannot say which is the direction if not by the label.
|
You must know what capacitors are used for. That will clarify where polarized capacitors are used. They are not used in AC Circuits.
1. Capacitors are used in turning circuit in AC. These are non polarized. So as the AC switches direction, it cannot damage the capacitors because the capacitor is simply not polarized and can be plugged in either direction.
2. Electrolytic Capacitors (which are polarized) are used in Smoothing out ripples in DC. They are polarized and large. The act mainly used in [rectifiers](http://en.wikipedia.org/wiki/Rectifier). The are essentially DC circuit in which the signal does not change polarity.
So true if you put an electrolytic capacitor (polarized) in an AC circuit, it will easily get damaged provided it exceeds it rating.
|
26,901 |
If the polarity changes every time the AC switches, then why doesn't the capacitor explode?
|
2012/02/20
|
[
"https://electronics.stackexchange.com/questions/26901",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/8210/"
] |
As clabacchio said, some capacitors are unpolarized, so it's perfectly fine to put positive and negative voltages on them.
However, it is still possible to put a AC signal thru a polarized capacitor. This is done by adding a DC bias of at least half the AC peak-peak voltage. The entire signal is then still positive, but AC-wise the capacitor acts on it normally.
Nowadays, polarized capacitors are mostly used for bulk storage on power supplies to reduce ripple and to provide short term high current. A nominal 12V supply, for example, may have 1Vpp AC ripple on it. That means the voltage is from 11.5V to 12.5V, which is fine for a electrolytic or other polarized cap. However, the large value of the cap will be applied to providing current to counter the 1Vpp AC voltage swing.
Put another way, polarized caps must always have a positive *voltage* on them, but there is no such restriction on *current*.
|
You must know what capacitors are used for. That will clarify where polarized capacitors are used. They are not used in AC Circuits.
1. Capacitors are used in turning circuit in AC. These are non polarized. So as the AC switches direction, it cannot damage the capacitors because the capacitor is simply not polarized and can be plugged in either direction.
2. Electrolytic Capacitors (which are polarized) are used in Smoothing out ripples in DC. They are polarized and large. The act mainly used in [rectifiers](http://en.wikipedia.org/wiki/Rectifier). The are essentially DC circuit in which the signal does not change polarity.
So true if you put an electrolytic capacitor (polarized) in an AC circuit, it will easily get damaged provided it exceeds it rating.
|
518,898 |
This is for an assignment I'm working on, and NO I'm not looking for you to just GIVE me the answer. I just need someone to point me in the right direction, maybe with a line or two of sample code.
I need to figure out how to set the priority of a file read operation from within my program. To the point:
* server process receives a message and spawns a child to handle it
* child tries to open the filename from the message and starts loading the file contents into the message queue
* there may be several children running at the same time, and the initial message contains a priority so some messages may get more device access
The only way I can think to do this (right now, anyways) would be to increment a counter every time I create a message, and to do something like sched\_yield after the counter reaches a given value for that process' assigned priority. That's most likely a horrible, horrible approach, but it's all I can think of at the moment. The assignment is more about the message queues than anything else, but we still have to have data transfer priority.
Any help/guidance is appreciated :)
|
2009/02/06
|
[
"https://Stackoverflow.com/questions/518898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63154/"
] |
Until recently, there was no IO prioritization in Linux. Now there is `ionice`. But I doubt you are meant to use it in your assignment.
|
Are you sure your assignment is talking about files and not system V message queues?
Read the man pages for:
```
msgctl(2), msgget(2), msgrcv(2), msgsnd(2), capabilities(7),
mq_overview(7), svipc(7)
```
Although I think you can use a file as a key to create a message queue, so that multiple processes have a way to rendezvous via the message queue, a Sys V message queue itself is not a file.
Just wondering because you mention "message queues" specifically, and talk about "priorities", which might conceivably map to the msgtyp field of eg. msgsnd and msgrcv, though it's hard to tell with what information you've given what the assignment really is about.
|
518,898 |
This is for an assignment I'm working on, and NO I'm not looking for you to just GIVE me the answer. I just need someone to point me in the right direction, maybe with a line or two of sample code.
I need to figure out how to set the priority of a file read operation from within my program. To the point:
* server process receives a message and spawns a child to handle it
* child tries to open the filename from the message and starts loading the file contents into the message queue
* there may be several children running at the same time, and the initial message contains a priority so some messages may get more device access
The only way I can think to do this (right now, anyways) would be to increment a counter every time I create a message, and to do something like sched\_yield after the counter reaches a given value for that process' assigned priority. That's most likely a horrible, horrible approach, but it's all I can think of at the moment. The assignment is more about the message queues than anything else, but we still have to have data transfer priority.
Any help/guidance is appreciated :)
|
2009/02/06
|
[
"https://Stackoverflow.com/questions/518898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63154/"
] |
Have the pool of child processes share a semaphore. Once a child acquires the semaphore it can read a predefined number of bytes from the resource and return it to the client. The number of bytes read can be related to the priority of the request. Once the process has read the predefined number of bytes release the semaphore.
|
Are you sure your assignment is talking about files and not system V message queues?
Read the man pages for:
```
msgctl(2), msgget(2), msgrcv(2), msgsnd(2), capabilities(7),
mq_overview(7), svipc(7)
```
Although I think you can use a file as a key to create a message queue, so that multiple processes have a way to rendezvous via the message queue, a Sys V message queue itself is not a file.
Just wondering because you mention "message queues" specifically, and talk about "priorities", which might conceivably map to the msgtyp field of eg. msgsnd and msgrcv, though it's hard to tell with what information you've given what the assignment really is about.
|
518,898 |
This is for an assignment I'm working on, and NO I'm not looking for you to just GIVE me the answer. I just need someone to point me in the right direction, maybe with a line or two of sample code.
I need to figure out how to set the priority of a file read operation from within my program. To the point:
* server process receives a message and spawns a child to handle it
* child tries to open the filename from the message and starts loading the file contents into the message queue
* there may be several children running at the same time, and the initial message contains a priority so some messages may get more device access
The only way I can think to do this (right now, anyways) would be to increment a counter every time I create a message, and to do something like sched\_yield after the counter reaches a given value for that process' assigned priority. That's most likely a horrible, horrible approach, but it's all I can think of at the moment. The assignment is more about the message queues than anything else, but we still have to have data transfer priority.
Any help/guidance is appreciated :)
|
2009/02/06
|
[
"https://Stackoverflow.com/questions/518898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63154/"
] |
Have the pool of child processes share a semaphore. Once a child acquires the semaphore it can read a predefined number of bytes from the resource and return it to the client. The number of bytes read can be related to the priority of the request. Once the process has read the predefined number of bytes release the semaphore.
|
Until recently, there was no IO prioritization in Linux. Now there is `ionice`. But I doubt you are meant to use it in your assignment.
|
139,814 |
Sites like TD Ameritrade offer a specific lot method of recording capital gains that claims to be most efficient. Such as using the following order:
>
> Short-term lossβ descending order by cost per share (highest to
> lowest), and as a result, taking the biggest short-term losses first
>
>
> Long-term lossβ descending order by cost per share
>
>
> Long-term gainβ descending order by cost per share (highest to
> lowest), and as a result, taking the smallest long-term gain first
>
>
> Short-term gainβ descending order by cost per share
>
>
>
<https://www.tdameritrade.com/education/taxes/what-is-a-tax-lot.page>
I'd like to know if there is a proof anywhere that this is indeed the optimal algorithm. Note that I'm aware there are special tax situations that might make it non optimal by including say carryovers etc or wanting to use the $3000 annual allowance etc. but those aren't my concern here. I'm only interested in the algorithm that maximizes the amount of long term capital gains when splitting the overall capital gains into long term and short term, given only the list of buys and sells and no other information.
|
2021/04/13
|
[
"https://money.stackexchange.com/questions/139814",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/21865/"
] |
There is no proof that it's optimal, because it's not optimal.
Suppose that the current date is December 16. There's a stock whose last trade price is $100, and you have the following tax lots:
* 100 shares purchased at $50.01 on January 1
* 100 shares purchased at $50 on December 1
Then suppose you want to sell 100 shares. TD Ameritrade's algorithm will see that these are all short-term gains, and so it will sell the lot with the highest purchase price: the shares purchased at $50.01 on January 1.
However, given that you want as much as possible of your realized gains to be long-term gains, it's probably better to sell the shares that you bought on December 1. That way, your remaining short-term unrealized gains will turn into long-term unrealized gains much sooner.
|
Their engine is the same steps that you would use if you had all your trades in a spreadsheet and knew that you needed to sell 172 shares today.
Remember that is only one of the [methods they provide/allow](https://www.tdameritrade.com/education/taxes/what-is-a-tax-lot.page):
* FIFO (first-in, first-out)
* LIFO (last-in, first-out)
* Highest cost
* Lowest cost
* Specific lot
* Tax efficient loss harvester
* Average cost
The section you quoted has to do with long positions, they have a slightly different approach for short positions.
They also have an important note:
>
> The tax efficient loss harvester method can be useful when capital
> gains have already been realized in the account earlier in the year,
> and the account has unrealized loss positions that can be utilized to
> offset those prior gains. Please note: This method does not factor in
> the possibility that a lot sold via this method will cause a wash
> sale, and therefore disallow the loss on the trade.
>
>
>
It doesn't know the future. It doesn't know what you have done or will do the rest of the year. They just have some software that will do the math for you.
|
5,341,756 |
I have followed some advices I got here today and would need a bit more help now:
I have an user control with login logic.
In mainForm I am using this:
```
private void Form1_Load(object sender, EventArgs e)
{
LoginScreen login = new MainMenu();
login.Parent = this;
login.Dock = DockStyle.Fill;
login.Show();
}
```
But I guess it is not modal and thus does not stop the original Form application. Sure I would need the main Form to do not continue until the login form is closed (and login sucessfull).
Would using an event correct? Let login object to raise an event that login was successfull and let the MainForm handle it - run the app?
EDIT: This is user control, no ShowDialog method available.
|
2011/03/17
|
[
"https://Stackoverflow.com/questions/5341756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615848/"
] |
Simply use `ShowDialog()` instead of `Show()`.
Besides, `ShowDialog()` returns a DialogResult, so you can check if user doesn't press `OK` and close the form in that case:
```
if(form.ShowDialog() != DialogResult.OK)
{
this.Close();
}else
{
//if login it's ok continue with main form loading...
}
```
**EDIT:**
Given that it's a usercontrol:
* Create a new form class and add the user control in it (e.g. using designer)
* Instanciate it and call `ShowDialog()` in your `FormLoad` code (the code is similar to the one you posted, but you need to instanciate the login form instead of your usercontrol)
|
Instead of `login.Show();` you might use`login.ShowDialog(this);`, making it a modal pop-up for the form.
|
5,341,756 |
I have followed some advices I got here today and would need a bit more help now:
I have an user control with login logic.
In mainForm I am using this:
```
private void Form1_Load(object sender, EventArgs e)
{
LoginScreen login = new MainMenu();
login.Parent = this;
login.Dock = DockStyle.Fill;
login.Show();
}
```
But I guess it is not modal and thus does not stop the original Form application. Sure I would need the main Form to do not continue until the login form is closed (and login sucessfull).
Would using an event correct? Let login object to raise an event that login was successfull and let the MainForm handle it - run the app?
EDIT: This is user control, no ShowDialog method available.
|
2011/03/17
|
[
"https://Stackoverflow.com/questions/5341756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615848/"
] |
Simply use `ShowDialog()` instead of `Show()`.
Besides, `ShowDialog()` returns a DialogResult, so you can check if user doesn't press `OK` and close the form in that case:
```
if(form.ShowDialog() != DialogResult.OK)
{
this.Close();
}else
{
//if login it's ok continue with main form loading...
}
```
**EDIT:**
Given that it's a usercontrol:
* Create a new form class and add the user control in it (e.g. using designer)
* Instanciate it and call `ShowDialog()` in your `FormLoad` code (the code is similar to the one you posted, but you need to instanciate the login form instead of your usercontrol)
|
If it's not derived from the `Form` class (which is odd), just create a windows form and put your control on it, then call `ShowDialog` method of the form. You'll have to wire closing of the form to the controls on your login screen somehow, though. If it fires some events it shouldn't be a problem.
|
3,100,400 |
In the identity
$$\frac {n!}{x(x+1)(x+2)...(x+n)} = \sum ^n\_{k=0}\frac {A\_k}{x+k} $$
Prove that $$A\_k =(-1)^{k}\:\cdot\: ^{n}C\_k$$
Also from this deduce that,
$$ \;^{n}C\_0\frac 1{1.2} - \:^{n}C\_1\frac1{2.3} +\; ^{n}C\_2\frac1{3.4} \; ... \;{(-1)^n}\; ^{n}C\_n\frac1{(n+1)(n+2)}\;=\frac1{(n+2)}$$
So I have to tried to use the binomial theorem on,
$(b-a)^n$, and then multiplied both sides by $a^{x-1}$.
Now I integrated both sides with respect to $a$. This gives me the binomially expanded side as same as the right hand side of the identity that we have to prove when I substitute $a=1$. I dont know how to integrate $a^{x-1}\;(b-a)^n$ with respect to $a$. I am not able to prove the identity and solve the deduction. Can someone please help me out ? Thanks a lot.
|
2019/02/04
|
[
"https://math.stackexchange.com/questions/3100400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/641206/"
] |
There are many ways to demonstrate such an interesting identity.
*a) Induction*
I do not know at what level you are, so let's start with what should be the simpler: Induction
Given the thesis
$$
F(x,n) = {{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
$$
* for $n=0$ it is true for whichever value of $x$ different from $0$
$$
n = 0\quad \Rightarrow \quad F(x,0) = {1 \over x} = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,0}
\binom{0}{k}{1 \over {x + k}}} = {1 \over x}\;:\;TRUE
$$
* for $n+1$ the LHS is
$$
\eqalign{
& F(x,n + 1) = {{\left( {n + 1} \right)!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = {{\left( {x + n + 1 - x} \right)n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = {{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} - {{n!} \over {\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = F(x,n) - F(x + 1,n) \cr}
$$
the same as the RHS
$$
\eqalign{
& F(x,n + 1) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n+1}{k}{1 \over {x + k}}} = \cr
& = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
+ \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k-1}{1 \over {x + k}}} = \cr
& = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
- \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k - 1} \binom{n}{k-1}{1 \over {x + 1 + k - 1}}} = \cr
& = F(x,n) - F(x + 1,n) \cr}
$$
and the thesis is demonstrated.
*b) Finite Difference*
Writing the Forward Difference of the function $f(x)$ wrt to the variable $x$ as
$$
\Delta \_{\,x} \,f(x) = f(x + 1) - f(x)
$$
its iteration gives
$$
\Delta \_{\,x} ^{\,n} \,f(x) = \Delta \_{\,x} \,\left( {\Delta \_{\,x} ^{\,n - 1} f(x)} \right) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,n - k} \binom{n}{k}f(x + k)}
$$
So
$$
F(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right)
$$
We can easily see that
$$
\eqalign{
& \Delta \_{\,x} ^{\,0} \,\left( {{1 \over x}} \right)\mathop \equiv \limits^{def} {1 \over x} \cr
& \Delta \_{\,x} ^{\,1} \,\left( {{1 \over x}} \right) = {1 \over {x + 1}} - {1 \over x} = {{\left( { - 1} \right)} \over {x\left( {x + 1} \right)}} \cr
& \Delta \_{\,x} ^{\,2} \,\left( {{1 \over x}} \right) = - {1 \over {\left( {x + 1} \right)\left( {x + 2} \right)}} + {1 \over {x\left( {x + 1} \right)}} = {{\left( { - 1} \right)\left( { - 2} \right)} \over {x\left( {x + 1} \right)\left( {x + 2} \right)}} \cr
& \quad \quad \vdots \cr
& \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right) = {{\left( { - 1} \right)^{\,n} n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} \cr}
$$
and that demontrates the thesis.
*c) Falling / Rising Factorials*
For a more general approach, it's advisable to resort to
the properties of the [Rising and Falling Factorials](https://en.wikipedia.org/wiki/Falling_and_rising_factorials), in order that we can write
$$
{{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} = {{n!} \over {x^{\,\overline {\,n + 1\,} } }}
= n!\;\left( {x - 1} \right)^{\,\underline {\, - \,\left( {n + 1} \right)} }
$$
where $x^{\,\underline {\,k\,} } ,\quad x^{\,\overline {\,k\,} } $ represent respectively the Falling and Rising Factorial.
One of the basic properties of the falling factorial is that its Delta resembles the rule of differentiation of "normal" powers
$$
\Delta \_{\,x} \;x^{\,\underline {\,n\,} } = \left( {x + 1} \right)^{\,\underline {\,n\,} } - x^{\,\underline {\,n\,} } = nx^{\,\underline {\,n - 1\,} }
$$
Therefore one automatically derives that
$$ \bbox[lightyellow] {
\eqalign{
& F(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right) = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {\left( {x - 1} \right)^{\,\underline {\, - \,1} } } \right) = \left( { - 1} \right)^{\,n} \Delta \_{\,x - 1} ^{\,n} \,\left( {\left( {x - 1} \right)^{\,\underline {\, - \,1} } } \right) = \cr
& = \left( { - 1} \right)^{\,n} \left( { - 1} \right)\left( { - 2} \right) \cdots \left( { - n} \right)\left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\;} } = \cr
& = \left( { - 1} \right)^{\,n} \left( { - 1} \right)^{\,\underline {\,\,n\;} } \left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\,} } = 1^{\,\overline {\,n\,} } \left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\,} } = {{n!} \over {x^{\,\overline {\,n + 1\,} } }} \cr}
}$$
Also, the second part of your question is easily solved as
$$
\eqalign{
& G(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {\left( {k + 1} \right)\left( {k + 2} \right)}}} = \cr
& = \left. {\sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k} {1 \over {\left( {x + k} \right)\left( {x + 1 + k} \right)}}\;} } \right|\_{\,x\, = \,1} = \cr
& = \left. {G(x,n)} \right|\_{\,x\, = \,1} \cr}
$$
therefore
$$ \bbox[lightyellow] {
\eqalign{
& G(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}
{1 \over {\left( {x + k} \right)\left( {x + 1 + k} \right)}}\;} = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {{1 \over {\left( x \right)\left( {x + 1} \right)}}} \right)
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {{1 \over {x^{\,\overline {\,2\,} } }}} \right) = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {x - 1} \right)^{\,\underline {\, - 2\,} }
= \left( { - 1} \right)^{\,n} \left( { - 2} \right)^{\,\underline {\,n\,} } \left( {x - 1} \right)^{\,\underline {\, - 2 - n\,} } = \cr
& = {{2^{\,\overline {\,n\,} } } \over {x^{\,\overline {\,n + 2\,} } }}
= {{\left( {n + 1} \right)!} \over {x^{\,\overline {\,n + 2\,} } }}\quad \Rightarrow \cr
& \Rightarrow \quad G(1,n) = {{\left( {n + 1} \right)!} \over {1^{\,\overline {\,n + 2\,} } }}
= {{\left( {n + 1} \right)!} \over {\left( {n + 2} \right)!}} = {1 \over {\left( {n + 2} \right)}} \cr}
}$$
Finally, it is surely interesting to point out that the Inversion property of the Binomial Convolution
implies
$$
f(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}g(k)}
\quad \Leftrightarrow \quad
g(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}f(k)}
$$
|
Hint: Place the RHS over a common denominator. This gives in the numerator a sum of terms of the form
$$A\_ix(x+1)\cdots(x+i-1)(x+i+1)\cdots(x+n).$$
Substitute successively $x=0$, $x=1,\dotsc, x=n$. This gives the result directly once you get the signs right: for each $i$, one gets $\pm i!(n-i)!A\_i = n!$.
|
3,100,400 |
In the identity
$$\frac {n!}{x(x+1)(x+2)...(x+n)} = \sum ^n\_{k=0}\frac {A\_k}{x+k} $$
Prove that $$A\_k =(-1)^{k}\:\cdot\: ^{n}C\_k$$
Also from this deduce that,
$$ \;^{n}C\_0\frac 1{1.2} - \:^{n}C\_1\frac1{2.3} +\; ^{n}C\_2\frac1{3.4} \; ... \;{(-1)^n}\; ^{n}C\_n\frac1{(n+1)(n+2)}\;=\frac1{(n+2)}$$
So I have to tried to use the binomial theorem on,
$(b-a)^n$, and then multiplied both sides by $a^{x-1}$.
Now I integrated both sides with respect to $a$. This gives me the binomially expanded side as same as the right hand side of the identity that we have to prove when I substitute $a=1$. I dont know how to integrate $a^{x-1}\;(b-a)^n$ with respect to $a$. I am not able to prove the identity and solve the deduction. Can someone please help me out ? Thanks a lot.
|
2019/02/04
|
[
"https://math.stackexchange.com/questions/3100400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/641206/"
] |
For the second identity, start with the binomial theorem:
$$
(1-t)^n=\sum\_{k=0}^n\binom{n}k(-1)^kt^k.
$$
Integrating both sides from $0$ to $x$ with respect to $dt$,
$$
\frac{1-(1-x)^{n+1}}{n+1}=\sum\_{k=0}^n\binom{n}k(-1)^k\frac{x^{k+1}}{k+1}.
$$
Integrating both sides from $0$ to $1$ with respect to $dx$,
$$
\frac1{n+2}=\sum\_{k=0}^n\binom{n}k(-1)^k\frac1{(k+1)(k+2)}.
$$
I cannot see how the second result follows immediately from the first.
|
Hint: Place the RHS over a common denominator. This gives in the numerator a sum of terms of the form
$$A\_ix(x+1)\cdots(x+i-1)(x+i+1)\cdots(x+n).$$
Substitute successively $x=0$, $x=1,\dotsc, x=n$. This gives the result directly once you get the signs right: for each $i$, one gets $\pm i!(n-i)!A\_i = n!$.
|
3,100,400 |
In the identity
$$\frac {n!}{x(x+1)(x+2)...(x+n)} = \sum ^n\_{k=0}\frac {A\_k}{x+k} $$
Prove that $$A\_k =(-1)^{k}\:\cdot\: ^{n}C\_k$$
Also from this deduce that,
$$ \;^{n}C\_0\frac 1{1.2} - \:^{n}C\_1\frac1{2.3} +\; ^{n}C\_2\frac1{3.4} \; ... \;{(-1)^n}\; ^{n}C\_n\frac1{(n+1)(n+2)}\;=\frac1{(n+2)}$$
So I have to tried to use the binomial theorem on,
$(b-a)^n$, and then multiplied both sides by $a^{x-1}$.
Now I integrated both sides with respect to $a$. This gives me the binomially expanded side as same as the right hand side of the identity that we have to prove when I substitute $a=1$. I dont know how to integrate $a^{x-1}\;(b-a)^n$ with respect to $a$. I am not able to prove the identity and solve the deduction. Can someone please help me out ? Thanks a lot.
|
2019/02/04
|
[
"https://math.stackexchange.com/questions/3100400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/641206/"
] |
There are many ways to demonstrate such an interesting identity.
*a) Induction*
I do not know at what level you are, so let's start with what should be the simpler: Induction
Given the thesis
$$
F(x,n) = {{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
$$
* for $n=0$ it is true for whichever value of $x$ different from $0$
$$
n = 0\quad \Rightarrow \quad F(x,0) = {1 \over x} = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,0}
\binom{0}{k}{1 \over {x + k}}} = {1 \over x}\;:\;TRUE
$$
* for $n+1$ the LHS is
$$
\eqalign{
& F(x,n + 1) = {{\left( {n + 1} \right)!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = {{\left( {x + n + 1 - x} \right)n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = {{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} - {{n!} \over {\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = F(x,n) - F(x + 1,n) \cr}
$$
the same as the RHS
$$
\eqalign{
& F(x,n + 1) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n+1}{k}{1 \over {x + k}}} = \cr
& = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
+ \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k-1}{1 \over {x + k}}} = \cr
& = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
- \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k - 1} \binom{n}{k-1}{1 \over {x + 1 + k - 1}}} = \cr
& = F(x,n) - F(x + 1,n) \cr}
$$
and the thesis is demonstrated.
*b) Finite Difference*
Writing the Forward Difference of the function $f(x)$ wrt to the variable $x$ as
$$
\Delta \_{\,x} \,f(x) = f(x + 1) - f(x)
$$
its iteration gives
$$
\Delta \_{\,x} ^{\,n} \,f(x) = \Delta \_{\,x} \,\left( {\Delta \_{\,x} ^{\,n - 1} f(x)} \right) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,n - k} \binom{n}{k}f(x + k)}
$$
So
$$
F(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right)
$$
We can easily see that
$$
\eqalign{
& \Delta \_{\,x} ^{\,0} \,\left( {{1 \over x}} \right)\mathop \equiv \limits^{def} {1 \over x} \cr
& \Delta \_{\,x} ^{\,1} \,\left( {{1 \over x}} \right) = {1 \over {x + 1}} - {1 \over x} = {{\left( { - 1} \right)} \over {x\left( {x + 1} \right)}} \cr
& \Delta \_{\,x} ^{\,2} \,\left( {{1 \over x}} \right) = - {1 \over {\left( {x + 1} \right)\left( {x + 2} \right)}} + {1 \over {x\left( {x + 1} \right)}} = {{\left( { - 1} \right)\left( { - 2} \right)} \over {x\left( {x + 1} \right)\left( {x + 2} \right)}} \cr
& \quad \quad \vdots \cr
& \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right) = {{\left( { - 1} \right)^{\,n} n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} \cr}
$$
and that demontrates the thesis.
*c) Falling / Rising Factorials*
For a more general approach, it's advisable to resort to
the properties of the [Rising and Falling Factorials](https://en.wikipedia.org/wiki/Falling_and_rising_factorials), in order that we can write
$$
{{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} = {{n!} \over {x^{\,\overline {\,n + 1\,} } }}
= n!\;\left( {x - 1} \right)^{\,\underline {\, - \,\left( {n + 1} \right)} }
$$
where $x^{\,\underline {\,k\,} } ,\quad x^{\,\overline {\,k\,} } $ represent respectively the Falling and Rising Factorial.
One of the basic properties of the falling factorial is that its Delta resembles the rule of differentiation of "normal" powers
$$
\Delta \_{\,x} \;x^{\,\underline {\,n\,} } = \left( {x + 1} \right)^{\,\underline {\,n\,} } - x^{\,\underline {\,n\,} } = nx^{\,\underline {\,n - 1\,} }
$$
Therefore one automatically derives that
$$ \bbox[lightyellow] {
\eqalign{
& F(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right) = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {\left( {x - 1} \right)^{\,\underline {\, - \,1} } } \right) = \left( { - 1} \right)^{\,n} \Delta \_{\,x - 1} ^{\,n} \,\left( {\left( {x - 1} \right)^{\,\underline {\, - \,1} } } \right) = \cr
& = \left( { - 1} \right)^{\,n} \left( { - 1} \right)\left( { - 2} \right) \cdots \left( { - n} \right)\left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\;} } = \cr
& = \left( { - 1} \right)^{\,n} \left( { - 1} \right)^{\,\underline {\,\,n\;} } \left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\,} } = 1^{\,\overline {\,n\,} } \left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\,} } = {{n!} \over {x^{\,\overline {\,n + 1\,} } }} \cr}
}$$
Also, the second part of your question is easily solved as
$$
\eqalign{
& G(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {\left( {k + 1} \right)\left( {k + 2} \right)}}} = \cr
& = \left. {\sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k} {1 \over {\left( {x + k} \right)\left( {x + 1 + k} \right)}}\;} } \right|\_{\,x\, = \,1} = \cr
& = \left. {G(x,n)} \right|\_{\,x\, = \,1} \cr}
$$
therefore
$$ \bbox[lightyellow] {
\eqalign{
& G(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}
{1 \over {\left( {x + k} \right)\left( {x + 1 + k} \right)}}\;} = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {{1 \over {\left( x \right)\left( {x + 1} \right)}}} \right)
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {{1 \over {x^{\,\overline {\,2\,} } }}} \right) = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {x - 1} \right)^{\,\underline {\, - 2\,} }
= \left( { - 1} \right)^{\,n} \left( { - 2} \right)^{\,\underline {\,n\,} } \left( {x - 1} \right)^{\,\underline {\, - 2 - n\,} } = \cr
& = {{2^{\,\overline {\,n\,} } } \over {x^{\,\overline {\,n + 2\,} } }}
= {{\left( {n + 1} \right)!} \over {x^{\,\overline {\,n + 2\,} } }}\quad \Rightarrow \cr
& \Rightarrow \quad G(1,n) = {{\left( {n + 1} \right)!} \over {1^{\,\overline {\,n + 2\,} } }}
= {{\left( {n + 1} \right)!} \over {\left( {n + 2} \right)!}} = {1 \over {\left( {n + 2} \right)}} \cr}
}$$
Finally, it is surely interesting to point out that the Inversion property of the Binomial Convolution
implies
$$
f(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}g(k)}
\quad \Leftrightarrow \quad
g(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}f(k)}
$$
|
For the second identity, start with the binomial theorem:
$$
(1-t)^n=\sum\_{k=0}^n\binom{n}k(-1)^kt^k.
$$
Integrating both sides from $0$ to $x$ with respect to $dt$,
$$
\frac{1-(1-x)^{n+1}}{n+1}=\sum\_{k=0}^n\binom{n}k(-1)^k\frac{x^{k+1}}{k+1}.
$$
Integrating both sides from $0$ to $1$ with respect to $dx$,
$$
\frac1{n+2}=\sum\_{k=0}^n\binom{n}k(-1)^k\frac1{(k+1)(k+2)}.
$$
I cannot see how the second result follows immediately from the first.
|
3,100,400 |
In the identity
$$\frac {n!}{x(x+1)(x+2)...(x+n)} = \sum ^n\_{k=0}\frac {A\_k}{x+k} $$
Prove that $$A\_k =(-1)^{k}\:\cdot\: ^{n}C\_k$$
Also from this deduce that,
$$ \;^{n}C\_0\frac 1{1.2} - \:^{n}C\_1\frac1{2.3} +\; ^{n}C\_2\frac1{3.4} \; ... \;{(-1)^n}\; ^{n}C\_n\frac1{(n+1)(n+2)}\;=\frac1{(n+2)}$$
So I have to tried to use the binomial theorem on,
$(b-a)^n$, and then multiplied both sides by $a^{x-1}$.
Now I integrated both sides with respect to $a$. This gives me the binomially expanded side as same as the right hand side of the identity that we have to prove when I substitute $a=1$. I dont know how to integrate $a^{x-1}\;(b-a)^n$ with respect to $a$. I am not able to prove the identity and solve the deduction. Can someone please help me out ? Thanks a lot.
|
2019/02/04
|
[
"https://math.stackexchange.com/questions/3100400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/641206/"
] |
There are many ways to demonstrate such an interesting identity.
*a) Induction*
I do not know at what level you are, so let's start with what should be the simpler: Induction
Given the thesis
$$
F(x,n) = {{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
$$
* for $n=0$ it is true for whichever value of $x$ different from $0$
$$
n = 0\quad \Rightarrow \quad F(x,0) = {1 \over x} = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,0}
\binom{0}{k}{1 \over {x + k}}} = {1 \over x}\;:\;TRUE
$$
* for $n+1$ the LHS is
$$
\eqalign{
& F(x,n + 1) = {{\left( {n + 1} \right)!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = {{\left( {x + n + 1 - x} \right)n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = {{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} - {{n!} \over {\left( {x + 1} \right) \cdots \left( {x + n} \right)\left( {x + n + 1} \right)}} = \cr
& = F(x,n) - F(x + 1,n) \cr}
$$
the same as the RHS
$$
\eqalign{
& F(x,n + 1) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n+1}{k}{1 \over {x + k}}} = \cr
& = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
+ \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k-1}{1 \over {x + k}}} = \cr
& = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
- \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k - 1} \binom{n}{k-1}{1 \over {x + 1 + k - 1}}} = \cr
& = F(x,n) - F(x + 1,n) \cr}
$$
and the thesis is demonstrated.
*b) Finite Difference*
Writing the Forward Difference of the function $f(x)$ wrt to the variable $x$ as
$$
\Delta \_{\,x} \,f(x) = f(x + 1) - f(x)
$$
its iteration gives
$$
\Delta \_{\,x} ^{\,n} \,f(x) = \Delta \_{\,x} \,\left( {\Delta \_{\,x} ^{\,n - 1} f(x)} \right) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,n - k} \binom{n}{k}f(x + k)}
$$
So
$$
F(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right)
$$
We can easily see that
$$
\eqalign{
& \Delta \_{\,x} ^{\,0} \,\left( {{1 \over x}} \right)\mathop \equiv \limits^{def} {1 \over x} \cr
& \Delta \_{\,x} ^{\,1} \,\left( {{1 \over x}} \right) = {1 \over {x + 1}} - {1 \over x} = {{\left( { - 1} \right)} \over {x\left( {x + 1} \right)}} \cr
& \Delta \_{\,x} ^{\,2} \,\left( {{1 \over x}} \right) = - {1 \over {\left( {x + 1} \right)\left( {x + 2} \right)}} + {1 \over {x\left( {x + 1} \right)}} = {{\left( { - 1} \right)\left( { - 2} \right)} \over {x\left( {x + 1} \right)\left( {x + 2} \right)}} \cr
& \quad \quad \vdots \cr
& \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right) = {{\left( { - 1} \right)^{\,n} n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} \cr}
$$
and that demontrates the thesis.
*c) Falling / Rising Factorials*
For a more general approach, it's advisable to resort to
the properties of the [Rising and Falling Factorials](https://en.wikipedia.org/wiki/Falling_and_rising_factorials), in order that we can write
$$
{{n!} \over {x\left( {x + 1} \right) \cdots \left( {x + n} \right)}} = {{n!} \over {x^{\,\overline {\,n + 1\,} } }}
= n!\;\left( {x - 1} \right)^{\,\underline {\, - \,\left( {n + 1} \right)} }
$$
where $x^{\,\underline {\,k\,} } ,\quad x^{\,\overline {\,k\,} } $ represent respectively the Falling and Rising Factorial.
One of the basic properties of the falling factorial is that its Delta resembles the rule of differentiation of "normal" powers
$$
\Delta \_{\,x} \;x^{\,\underline {\,n\,} } = \left( {x + 1} \right)^{\,\underline {\,n\,} } - x^{\,\underline {\,n\,} } = nx^{\,\underline {\,n - 1\,} }
$$
Therefore one automatically derives that
$$ \bbox[lightyellow] {
\eqalign{
& F(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {x + k}}}
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {{1 \over x}} \right) = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \,\left( {\left( {x - 1} \right)^{\,\underline {\, - \,1} } } \right) = \left( { - 1} \right)^{\,n} \Delta \_{\,x - 1} ^{\,n} \,\left( {\left( {x - 1} \right)^{\,\underline {\, - \,1} } } \right) = \cr
& = \left( { - 1} \right)^{\,n} \left( { - 1} \right)\left( { - 2} \right) \cdots \left( { - n} \right)\left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\;} } = \cr
& = \left( { - 1} \right)^{\,n} \left( { - 1} \right)^{\,\underline {\,\,n\;} } \left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\,} } = 1^{\,\overline {\,n\,} } \left( {x - 1} \right)^{\,\underline {\, - 1 - \,n\,} } = {{n!} \over {x^{\,\overline {\,n + 1\,} } }} \cr}
}$$
Also, the second part of your question is easily solved as
$$
\eqalign{
& G(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k}{1 \over {\left( {k + 1} \right)\left( {k + 2} \right)}}} = \cr
& = \left. {\sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {
\left( { - 1} \right)^{\,k} \binom{n}{k} {1 \over {\left( {x + k} \right)\left( {x + 1 + k} \right)}}\;} } \right|\_{\,x\, = \,1} = \cr
& = \left. {G(x,n)} \right|\_{\,x\, = \,1} \cr}
$$
therefore
$$ \bbox[lightyellow] {
\eqalign{
& G(x,n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}
{1 \over {\left( {x + k} \right)\left( {x + 1 + k} \right)}}\;} = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {{1 \over {\left( x \right)\left( {x + 1} \right)}}} \right)
= \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {{1 \over {x^{\,\overline {\,2\,} } }}} \right) = \cr
& = \left( { - 1} \right)^{\,n} \Delta \_{\,x} ^{\,n} \left( {x - 1} \right)^{\,\underline {\, - 2\,} }
= \left( { - 1} \right)^{\,n} \left( { - 2} \right)^{\,\underline {\,n\,} } \left( {x - 1} \right)^{\,\underline {\, - 2 - n\,} } = \cr
& = {{2^{\,\overline {\,n\,} } } \over {x^{\,\overline {\,n + 2\,} } }}
= {{\left( {n + 1} \right)!} \over {x^{\,\overline {\,n + 2\,} } }}\quad \Rightarrow \cr
& \Rightarrow \quad G(1,n) = {{\left( {n + 1} \right)!} \over {1^{\,\overline {\,n + 2\,} } }}
= {{\left( {n + 1} \right)!} \over {\left( {n + 2} \right)!}} = {1 \over {\left( {n + 2} \right)}} \cr}
}$$
Finally, it is surely interesting to point out that the Inversion property of the Binomial Convolution
implies
$$
f(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}g(k)}
\quad \Leftrightarrow \quad
g(n) = \sum\limits\_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,k} \binom{n}{k}f(k)}
$$
|
>
> We obtain
> \begin{align\*}
> \frac{n!}{x(x+1)\cdots(x+n)}&=\sum\_{k=0}^n\frac{A\_k}{x+k}\\
> n!&=\sum\_{k=0}^nA\_k\frac{x(x+1)\cdots(x+n)}{x+k}\tag{1}
> \end{align\*}
> Substituting $x=-j,0\leq j\leq n$ in (1) we get
> \begin{align\*}
> n!&=A\_j(-j)(-j+1)\cdots (-1)\cdots1\cdot 2\cdots(n-j)\\
> &=A\_j(-1)^j j!(n-j)!\\
> \end{align\*}
> We get
> \begin{align\*}
> \color{blue}{A\_j}&=(-1)^j\frac{n!}{j!(n-j)!}\\
> &\,\,\color{blue}{=(-1)^j\binom{n}{j}\qquad\qquad 0\leq j\leq n}\tag{2}
> \end{align\*}
> and the claim follows.
>
>
>
Using (1) and (2) we want to show $\sum\_{k=0}^n(-1)^k\binom{n}{k}\frac{1}{(k+1)(k+2)}=\frac{1}{n+2}$.
>
> We obtain
> \begin{align\*}
> \color{blue}{\sum\_{k=0}^n}&\color{blue}{(-1)^k\binom{n}{k}\frac{1}{(k+1)(k+2)}}\\
> &=\sum\_{k=0}^n(-1)^k\binom{n}{k}\left(\frac{1}{k+1}-\frac{1}{k+2}\right)\\
> &=\sum\_{k=0}^n(-1)^k\binom{n}{k}\frac{1}{k+1}-\sum\_{k=0}^n(-1)^k\binom{n}{k}\frac{1}{k+2}\\
> &=\frac{n!}{1\cdot 2\cdots (n+1)}-\frac{n!}{2\cdot 3\cdots (n+2)}\tag{3}\\
> &=\frac{1}{n+1}-\frac{1}{(n+1)(n+2)}\\
> &\,\,\color{blue}{=\frac{1}{n+2}}
> \end{align\*}
>
>
> and the claim follows.
>
>
>
In (3) we apply (1) and (2) with $x=1$ and $x=2$.
|
3,100,400 |
In the identity
$$\frac {n!}{x(x+1)(x+2)...(x+n)} = \sum ^n\_{k=0}\frac {A\_k}{x+k} $$
Prove that $$A\_k =(-1)^{k}\:\cdot\: ^{n}C\_k$$
Also from this deduce that,
$$ \;^{n}C\_0\frac 1{1.2} - \:^{n}C\_1\frac1{2.3} +\; ^{n}C\_2\frac1{3.4} \; ... \;{(-1)^n}\; ^{n}C\_n\frac1{(n+1)(n+2)}\;=\frac1{(n+2)}$$
So I have to tried to use the binomial theorem on,
$(b-a)^n$, and then multiplied both sides by $a^{x-1}$.
Now I integrated both sides with respect to $a$. This gives me the binomially expanded side as same as the right hand side of the identity that we have to prove when I substitute $a=1$. I dont know how to integrate $a^{x-1}\;(b-a)^n$ with respect to $a$. I am not able to prove the identity and solve the deduction. Can someone please help me out ? Thanks a lot.
|
2019/02/04
|
[
"https://math.stackexchange.com/questions/3100400",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/641206/"
] |
For the second identity, start with the binomial theorem:
$$
(1-t)^n=\sum\_{k=0}^n\binom{n}k(-1)^kt^k.
$$
Integrating both sides from $0$ to $x$ with respect to $dt$,
$$
\frac{1-(1-x)^{n+1}}{n+1}=\sum\_{k=0}^n\binom{n}k(-1)^k\frac{x^{k+1}}{k+1}.
$$
Integrating both sides from $0$ to $1$ with respect to $dx$,
$$
\frac1{n+2}=\sum\_{k=0}^n\binom{n}k(-1)^k\frac1{(k+1)(k+2)}.
$$
I cannot see how the second result follows immediately from the first.
|
>
> We obtain
> \begin{align\*}
> \frac{n!}{x(x+1)\cdots(x+n)}&=\sum\_{k=0}^n\frac{A\_k}{x+k}\\
> n!&=\sum\_{k=0}^nA\_k\frac{x(x+1)\cdots(x+n)}{x+k}\tag{1}
> \end{align\*}
> Substituting $x=-j,0\leq j\leq n$ in (1) we get
> \begin{align\*}
> n!&=A\_j(-j)(-j+1)\cdots (-1)\cdots1\cdot 2\cdots(n-j)\\
> &=A\_j(-1)^j j!(n-j)!\\
> \end{align\*}
> We get
> \begin{align\*}
> \color{blue}{A\_j}&=(-1)^j\frac{n!}{j!(n-j)!}\\
> &\,\,\color{blue}{=(-1)^j\binom{n}{j}\qquad\qquad 0\leq j\leq n}\tag{2}
> \end{align\*}
> and the claim follows.
>
>
>
Using (1) and (2) we want to show $\sum\_{k=0}^n(-1)^k\binom{n}{k}\frac{1}{(k+1)(k+2)}=\frac{1}{n+2}$.
>
> We obtain
> \begin{align\*}
> \color{blue}{\sum\_{k=0}^n}&\color{blue}{(-1)^k\binom{n}{k}\frac{1}{(k+1)(k+2)}}\\
> &=\sum\_{k=0}^n(-1)^k\binom{n}{k}\left(\frac{1}{k+1}-\frac{1}{k+2}\right)\\
> &=\sum\_{k=0}^n(-1)^k\binom{n}{k}\frac{1}{k+1}-\sum\_{k=0}^n(-1)^k\binom{n}{k}\frac{1}{k+2}\\
> &=\frac{n!}{1\cdot 2\cdots (n+1)}-\frac{n!}{2\cdot 3\cdots (n+2)}\tag{3}\\
> &=\frac{1}{n+1}-\frac{1}{(n+1)(n+2)}\\
> &\,\,\color{blue}{=\frac{1}{n+2}}
> \end{align\*}
>
>
> and the claim follows.
>
>
>
In (3) we apply (1) and (2) with $x=1$ and $x=2$.
|
112,102 |
Is there any tools to copy text from video's or images?
|
2013/11/28
|
[
"https://apple.stackexchange.com/questions/112102",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/63598/"
] |
You can upload the image to [Google Drive](https://drive.google.com) and it will use [OCR](http://en.wikipedia.org/wiki/Optical_character_recognition) to get the text from it. Or you can use a specialized software like [Abby Fine reader](http://finereader.abbyy.com/) for more advanced work.
The quality of the text recognition will vary with image quality. I would use a screenshot to get texts from video.
In **Google Drive**, you need to set Upload settings below the cogwheel on the right top to βConvert text from uploaded PDF and images filesβ.  He will copy the recognized text in the document below the image.
|
You can use Optical Character Recognition (OCR) for the job
|
112,102 |
Is there any tools to copy text from video's or images?
|
2013/11/28
|
[
"https://apple.stackexchange.com/questions/112102",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/63598/"
] |
I often also want to quickly copy text from images and videos. However I wasn't able to find a good solution on OS X, as procedures like uploading to Google Drive are far too cumbersome.
This is why I developed [Aristocrat](http://joshparnham.com/projects/aristocrat/), a simple app that performs OCR on a selected region of your screen. It's currently [free on the App Store](https://itunes.apple.com/us/app/aristocrat/id886910172?ls=1&mt=12).
|
You can use Optical Character Recognition (OCR) for the job
|
56,818,424 |
I have this simple Post Form class
```
class PostForm(FlaskForm):
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
```
Is there a way so that when the user inputs
```
<a href="example.com">example</a>
```
on the TextAreaField the site outputs it as an HTML link?
|
2019/06/29
|
[
"https://Stackoverflow.com/questions/56818424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375835/"
] |
You can use the `OR(c1,c2,...)` function which evaluates to True when any one of its argument conditions is true. For example,
```
=IF(OR(WEEKDAY(E3,2)=1,WEEKDAY(E3,2)=2,...), "Wake up", IF(OR(...), "Sleep", "Remote"))
```
|
The `OR` function takes a list of parameters, i.e. `OR(param1, param2, param...)`.
The formula below will do one thing ("Wake Up") on every day except Thursday.
```
=IF(OR(WEEKDAY(E3,2) < 4, WEEKDAY(E3,2) > 4), "Wake Up", "Sleep")
```
Using your date format (2) where Thursday is day 4, it says if the day of the week is less than 4 OR greater than 4, say "Wake Up", otherwise say "Sleep".
**Update**
To accommodate the updated original question, the function below will:
* If the date is a holiday specified in the `Holiday` named range --> Holiday
* If the week day is Thursday --> Remote
* If the week day is Saturday or Sunday --> Sleep
* Else (Monday, Tuesday, Wednesday, Friday) -> Wake Up
```
=IF(COUNTIF(Holidays,A2)>0,"Holiday",IF(WEEKDAY(A2,2)=4,"Remote",IF(OR(WEEKDAY(A2, 2)=6,WEEKDAY(A2, 2)=7),"Sleep","Wake Up")))
```
Note that I've also specified Friday 7/5 as a holiday.
[](https://i.stack.imgur.com/7BKWp.png)
|
56,818,424 |
I have this simple Post Form class
```
class PostForm(FlaskForm):
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
```
Is there a way so that when the user inputs
```
<a href="example.com">example</a>
```
on the TextAreaField the site outputs it as an HTML link?
|
2019/06/29
|
[
"https://Stackoverflow.com/questions/56818424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375835/"
] |
You can use the `OR(c1,c2,...)` function which evaluates to True when any one of its argument conditions is true. For example,
```
=IF(OR(WEEKDAY(E3,2)=1,WEEKDAY(E3,2)=2,...), "Wake up", IF(OR(...), "Sleep", "Remote"))
```
|
**This will work:**
```
=IF(OR(WEEKDAY(E3,2)<3,WEEKDAY(E3,2)=5),"Remote",IF(WEEKDAY(E3,2)=4,"Sleep","Wake up"))
```
* Monday, Tuesday, Wednesday, Friday - Remote
* Thursday - Sleep
* Sat, Sun - Wake up
|
56,818,424 |
I have this simple Post Form class
```
class PostForm(FlaskForm):
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
```
Is there a way so that when the user inputs
```
<a href="example.com">example</a>
```
on the TextAreaField the site outputs it as an HTML link?
|
2019/06/29
|
[
"https://Stackoverflow.com/questions/56818424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375835/"
] |
You can use the `OR(c1,c2,...)` function which evaluates to True when any one of its argument conditions is true. For example,
```
=IF(OR(WEEKDAY(E3,2)=1,WEEKDAY(E3,2)=2,...), "Wake up", IF(OR(...), "Sleep", "Remote"))
```
|
I know you've asked about using `OR`, and have already accepted an answer, but I wanted to point out that you can also use `VLOOKUP` to make your logic clearer and more readable.
First, you can create a table of weekdays and lookup values, like this:
```
+---+-----+-----------+---------+
| | A | B | C |
+---+-----+-----------+---------+
| 1 | nbr | weekday | alarm |
| 2 | 1 | Sunday | Sleep |
| 3 | 2 | Monday | Wake Up |
| 4 | 3 | Tuesday | Wake Up |
| 5 | 4 | Wednesday | Wake Up |
| 6 | 5 | Thursday | Remote |
| 7 | 6 | Friday | Wake Up |
| 8 | 7 | Saturday | Sleep |
+---+-----+-----------+---------+
```
Then, assuming the date you're checking is in `E3`, you can use the following formula:
```
=VLOOKUP(WEEKDAY(E3,1),$A$2:$C$8,3,FALSE)
```
The formula becomes even clearer when converting your lookup data to a table and using a named range:
[](https://i.stack.imgur.com/UWwB1.png)
[](https://i.stack.imgur.com/3r5uX.png)
```
=VLOOKUP(WEEKDAY(date_entered,1),tWeekdays,3,FALSE)
```
|
56,818,424 |
I have this simple Post Form class
```
class PostForm(FlaskForm):
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
```
Is there a way so that when the user inputs
```
<a href="example.com">example</a>
```
on the TextAreaField the site outputs it as an HTML link?
|
2019/06/29
|
[
"https://Stackoverflow.com/questions/56818424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375835/"
] |
OR is nor necessary and without seems to me a little neater:
```
=IF(COUNTIF(Holiday,E3),"Other",IF(WEEKDAY(E3)=5,"Remote",IF(WEEKDAY(E3,2)>5,"Sleep","Wake up")))
```
`Holiday` is a named range for the dates of *something different*.
|
The `OR` function takes a list of parameters, i.e. `OR(param1, param2, param...)`.
The formula below will do one thing ("Wake Up") on every day except Thursday.
```
=IF(OR(WEEKDAY(E3,2) < 4, WEEKDAY(E3,2) > 4), "Wake Up", "Sleep")
```
Using your date format (2) where Thursday is day 4, it says if the day of the week is less than 4 OR greater than 4, say "Wake Up", otherwise say "Sleep".
**Update**
To accommodate the updated original question, the function below will:
* If the date is a holiday specified in the `Holiday` named range --> Holiday
* If the week day is Thursday --> Remote
* If the week day is Saturday or Sunday --> Sleep
* Else (Monday, Tuesday, Wednesday, Friday) -> Wake Up
```
=IF(COUNTIF(Holidays,A2)>0,"Holiday",IF(WEEKDAY(A2,2)=4,"Remote",IF(OR(WEEKDAY(A2, 2)=6,WEEKDAY(A2, 2)=7),"Sleep","Wake Up")))
```
Note that I've also specified Friday 7/5 as a holiday.
[](https://i.stack.imgur.com/7BKWp.png)
|
56,818,424 |
I have this simple Post Form class
```
class PostForm(FlaskForm):
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
```
Is there a way so that when the user inputs
```
<a href="example.com">example</a>
```
on the TextAreaField the site outputs it as an HTML link?
|
2019/06/29
|
[
"https://Stackoverflow.com/questions/56818424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375835/"
] |
OR is nor necessary and without seems to me a little neater:
```
=IF(COUNTIF(Holiday,E3),"Other",IF(WEEKDAY(E3)=5,"Remote",IF(WEEKDAY(E3,2)>5,"Sleep","Wake up")))
```
`Holiday` is a named range for the dates of *something different*.
|
**This will work:**
```
=IF(OR(WEEKDAY(E3,2)<3,WEEKDAY(E3,2)=5),"Remote",IF(WEEKDAY(E3,2)=4,"Sleep","Wake up"))
```
* Monday, Tuesday, Wednesday, Friday - Remote
* Thursday - Sleep
* Sat, Sun - Wake up
|
56,818,424 |
I have this simple Post Form class
```
class PostForm(FlaskForm):
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
```
Is there a way so that when the user inputs
```
<a href="example.com">example</a>
```
on the TextAreaField the site outputs it as an HTML link?
|
2019/06/29
|
[
"https://Stackoverflow.com/questions/56818424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11375835/"
] |
OR is nor necessary and without seems to me a little neater:
```
=IF(COUNTIF(Holiday,E3),"Other",IF(WEEKDAY(E3)=5,"Remote",IF(WEEKDAY(E3,2)>5,"Sleep","Wake up")))
```
`Holiday` is a named range for the dates of *something different*.
|
I know you've asked about using `OR`, and have already accepted an answer, but I wanted to point out that you can also use `VLOOKUP` to make your logic clearer and more readable.
First, you can create a table of weekdays and lookup values, like this:
```
+---+-----+-----------+---------+
| | A | B | C |
+---+-----+-----------+---------+
| 1 | nbr | weekday | alarm |
| 2 | 1 | Sunday | Sleep |
| 3 | 2 | Monday | Wake Up |
| 4 | 3 | Tuesday | Wake Up |
| 5 | 4 | Wednesday | Wake Up |
| 6 | 5 | Thursday | Remote |
| 7 | 6 | Friday | Wake Up |
| 8 | 7 | Saturday | Sleep |
+---+-----+-----------+---------+
```
Then, assuming the date you're checking is in `E3`, you can use the following formula:
```
=VLOOKUP(WEEKDAY(E3,1),$A$2:$C$8,3,FALSE)
```
The formula becomes even clearer when converting your lookup data to a table and using a named range:
[](https://i.stack.imgur.com/UWwB1.png)
[](https://i.stack.imgur.com/3r5uX.png)
```
=VLOOKUP(WEEKDAY(date_entered,1),tWeekdays,3,FALSE)
```
|
28,124,844 |
The following function `f` attempts to read an `Int` twice by using an `IO (Maybe Int)` function twice, but βshort-circuitsβ execution after successfully reading one `Int`:
```
readInt :: IO (Maybe Int)
f :: IO (Maybe Int)
f = do
n1 <- readInt
case n1 of
Just n' -> return (Just n')
Nothing -> do
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
Is there a good way to refactor this code? This would get very hairy if I extended it to three attemptsβ¦
(My thought process: Seeing this βstaircasingβ tells me that maybe I should be using the `Monad` instance of `Maybe`, but since this is already in the `IO` monad, I would then have to use `MaybeT`(?). However, I only need *one* of the `readInt` to succeed, so the `Maybe` monad's behaviour of erroring out on the first `Nothing` would be wrong here...)
|
2015/01/24
|
[
"https://Stackoverflow.com/questions/28124844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459877/"
] |
You can use `MaybeT` and the `MonadPlus` instance to use `msum`:
```
f :: MaybeT IO Int
f = msum [readInt, readInt, readInt]
```
|
First of all,
```
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
is really just `readInt`. You are picking apart a `Maybe` value in order to put together the same one.
For the rest, I think the most succinct way in this case is to use the `maybe` function. Then you can get just
```
f = maybe readInt (return . Just) =<< readInt
```
|
28,124,844 |
The following function `f` attempts to read an `Int` twice by using an `IO (Maybe Int)` function twice, but βshort-circuitsβ execution after successfully reading one `Int`:
```
readInt :: IO (Maybe Int)
f :: IO (Maybe Int)
f = do
n1 <- readInt
case n1 of
Just n' -> return (Just n')
Nothing -> do
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
Is there a good way to refactor this code? This would get very hairy if I extended it to three attemptsβ¦
(My thought process: Seeing this βstaircasingβ tells me that maybe I should be using the `Monad` instance of `Maybe`, but since this is already in the `IO` monad, I would then have to use `MaybeT`(?). However, I only need *one* of the `readInt` to succeed, so the `Maybe` monad's behaviour of erroring out on the first `Nothing` would be wrong here...)
|
2015/01/24
|
[
"https://Stackoverflow.com/questions/28124844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459877/"
] |
You can use `MaybeT` and the `MonadPlus` instance to use `msum`:
```
f :: MaybeT IO Int
f = msum [readInt, readInt, readInt]
```
|
You need the alternative instance for `MaybeT`:
```
instance (Functor m, Monad m) => Alternative (MaybeT m) where
empty = mzero
(<|>) = mplus
instance (Monad m) => MonadPlus (MaybeT m) where
mzero = MaybeT (return Nothing)
mplus x y = MaybeT $ do
v <- runMaybeT x
case v of
Nothing -> runMaybeT y
Just _ -> return v
```
I.e. compute the first argument and return the value if it's `Just`, otherwise compute the second argument and return the value.
The code:
```
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Maybe
import Text.Read
readInt :: MaybeT IO Int
readInt = MaybeT $ readMaybe <$> getLine
main = runMaybeT (readInt <|> readInt) >>= print
```
|
28,124,844 |
The following function `f` attempts to read an `Int` twice by using an `IO (Maybe Int)` function twice, but βshort-circuitsβ execution after successfully reading one `Int`:
```
readInt :: IO (Maybe Int)
f :: IO (Maybe Int)
f = do
n1 <- readInt
case n1 of
Just n' -> return (Just n')
Nothing -> do
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
Is there a good way to refactor this code? This would get very hairy if I extended it to three attemptsβ¦
(My thought process: Seeing this βstaircasingβ tells me that maybe I should be using the `Monad` instance of `Maybe`, but since this is already in the `IO` monad, I would then have to use `MaybeT`(?). However, I only need *one* of the `readInt` to succeed, so the `Maybe` monad's behaviour of erroring out on the first `Nothing` would be wrong here...)
|
2015/01/24
|
[
"https://Stackoverflow.com/questions/28124844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459877/"
] |
You can use `MaybeT` and the `MonadPlus` instance to use `msum`:
```
f :: MaybeT IO Int
f = msum [readInt, readInt, readInt]
```
|
Another way of doing this is with the [iterative monad transformer](http://hackage.haskell.org/package/free-4.10.0.1/docs/Control-Monad-Trans-Iter.html) from the `free` package.
```
import Control.Monad.Trans.Iter (untilJust,retract,cutoff,IterT)
readInt :: IO (Maybe Int)
readInt = undefined
f' :: IterT IO Int
f' = untilJust readInt
f :: IO (Maybe Int)
f = (retract . cutoff 2) f'
```
Where [`cutoff`](http://hackage.haskell.org/package/free-4.10.0.1/docs/Control-Monad-Trans-Iter.html#v:cutoff) specifies the maximum number of retries.
The advantage of this approach is that you can easily [interleave other repeated actions](https://gist.github.com/danidiaz/e9382127d1c4025b9845) with `f'`, thanks to the `MonadPlus` instance of `IterT`. Logging actions for example, or wait actions.
|
28,124,844 |
The following function `f` attempts to read an `Int` twice by using an `IO (Maybe Int)` function twice, but βshort-circuitsβ execution after successfully reading one `Int`:
```
readInt :: IO (Maybe Int)
f :: IO (Maybe Int)
f = do
n1 <- readInt
case n1 of
Just n' -> return (Just n')
Nothing -> do
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
Is there a good way to refactor this code? This would get very hairy if I extended it to three attemptsβ¦
(My thought process: Seeing this βstaircasingβ tells me that maybe I should be using the `Monad` instance of `Maybe`, but since this is already in the `IO` monad, I would then have to use `MaybeT`(?). However, I only need *one* of the `readInt` to succeed, so the `Maybe` monad's behaviour of erroring out on the first `Nothing` would be wrong here...)
|
2015/01/24
|
[
"https://Stackoverflow.com/questions/28124844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459877/"
] |
You need the alternative instance for `MaybeT`:
```
instance (Functor m, Monad m) => Alternative (MaybeT m) where
empty = mzero
(<|>) = mplus
instance (Monad m) => MonadPlus (MaybeT m) where
mzero = MaybeT (return Nothing)
mplus x y = MaybeT $ do
v <- runMaybeT x
case v of
Nothing -> runMaybeT y
Just _ -> return v
```
I.e. compute the first argument and return the value if it's `Just`, otherwise compute the second argument and return the value.
The code:
```
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Maybe
import Text.Read
readInt :: MaybeT IO Int
readInt = MaybeT $ readMaybe <$> getLine
main = runMaybeT (readInt <|> readInt) >>= print
```
|
First of all,
```
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
is really just `readInt`. You are picking apart a `Maybe` value in order to put together the same one.
For the rest, I think the most succinct way in this case is to use the `maybe` function. Then you can get just
```
f = maybe readInt (return . Just) =<< readInt
```
|
28,124,844 |
The following function `f` attempts to read an `Int` twice by using an `IO (Maybe Int)` function twice, but βshort-circuitsβ execution after successfully reading one `Int`:
```
readInt :: IO (Maybe Int)
f :: IO (Maybe Int)
f = do
n1 <- readInt
case n1 of
Just n' -> return (Just n')
Nothing -> do
n2 <- readInt
case n2 of
Just n' -> return (Just n')
Nothing -> return Nothing
```
Is there a good way to refactor this code? This would get very hairy if I extended it to three attemptsβ¦
(My thought process: Seeing this βstaircasingβ tells me that maybe I should be using the `Monad` instance of `Maybe`, but since this is already in the `IO` monad, I would then have to use `MaybeT`(?). However, I only need *one* of the `readInt` to succeed, so the `Maybe` monad's behaviour of erroring out on the first `Nothing` would be wrong here...)
|
2015/01/24
|
[
"https://Stackoverflow.com/questions/28124844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459877/"
] |
You need the alternative instance for `MaybeT`:
```
instance (Functor m, Monad m) => Alternative (MaybeT m) where
empty = mzero
(<|>) = mplus
instance (Monad m) => MonadPlus (MaybeT m) where
mzero = MaybeT (return Nothing)
mplus x y = MaybeT $ do
v <- runMaybeT x
case v of
Nothing -> runMaybeT y
Just _ -> return v
```
I.e. compute the first argument and return the value if it's `Just`, otherwise compute the second argument and return the value.
The code:
```
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Maybe
import Text.Read
readInt :: MaybeT IO Int
readInt = MaybeT $ readMaybe <$> getLine
main = runMaybeT (readInt <|> readInt) >>= print
```
|
Another way of doing this is with the [iterative monad transformer](http://hackage.haskell.org/package/free-4.10.0.1/docs/Control-Monad-Trans-Iter.html) from the `free` package.
```
import Control.Monad.Trans.Iter (untilJust,retract,cutoff,IterT)
readInt :: IO (Maybe Int)
readInt = undefined
f' :: IterT IO Int
f' = untilJust readInt
f :: IO (Maybe Int)
f = (retract . cutoff 2) f'
```
Where [`cutoff`](http://hackage.haskell.org/package/free-4.10.0.1/docs/Control-Monad-Trans-Iter.html#v:cutoff) specifies the maximum number of retries.
The advantage of this approach is that you can easily [interleave other repeated actions](https://gist.github.com/danidiaz/e9382127d1c4025b9845) with `f'`, thanks to the `MonadPlus` instance of `IterT`. Logging actions for example, or wait actions.
|
280,334 |
I am trying to add new fields to the user search results in setup. For an example, I need to add Profile of the user. But I cannot find a way. Adapting the search results layout doesn't help in this case.
[](https://i.stack.imgur.com/rxz16.jpg)
Any solution?
|
2019/10/04
|
[
"https://salesforce.stackexchange.com/questions/280334",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/25193/"
] |
You have missed one thing in your code syntax. i.e **'$objectInfo.defaultRecordTypeId'** will not give the default value but **'$objectInfo.data.defaultRecordTypeId'** will. You missed using data to get the defaultRecordTypeId.
A sample example to use the default record type for getting picklist value in Lightning web component.
```
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
@track objectInfo;
@wire(getObjectInfo, { objectApiName: CONTACT_OBJECT })
objectInfo;
@wire(getPicklistValues, {
recordTypeId: '$objectInfo.data.defaultRecordTypeId',
fieldApiName: GENDER_FIELD
})
genders;
```
**Update:-**
On User object, we don't have any master record type. I have confirmed it through below piece of code:-
```
Schema.DescribeSObjectResult dsr = User.SObjectType.getDescribe();
Schema.RecordTypeInfo defaultRecordType;
for(Schema.RecordTypeInfo rti : dsr.getRecordTypeInfos()) {
if(rti.isDefaultRecordTypeMapping()) {
defaultRecordType = rti;
system.debug(defaultRecordType);
}
}
```
This is the reason, you are getting the defaultRecordTypeId as undefined.
|
@Salesforce\_Noobie getPicklistValues is supported for User fields, but you need to send a dummy recordtype id to
```
import { LightningElement,wire } from 'lwc';
import { getObjectInfo, getPicklistValues } from 'lightning/uiObjectInfoApi';
import USER_OBJECT from '@salesforce/schema/User';
import TESTPICKLIST_FIELD from '@salesforce/schema/User.StateCode';
export default class GetPicklistValuesOfField extends LightningElement {
value ='';
@wire(getObjectInfo, { objectApiName: USER_OBJECT })
userMetadata;
@wire(getPicklistValues,
{
recordTypeId: '012000000000000AAA',
fieldApiName: TESTPICKLIST_FIELD
}
)
industryPicklist;
handleChange(event) {
this.value = event.detail.value;
}
}
```
|
15,657,915 |
In my android Project, I need to create an 'anim' folder. As most people know, the anim folder will be used to store animations.
1. How do I create a folder?
2. Where does the anim folder belong?
|
2013/03/27
|
[
"https://Stackoverflow.com/questions/15657915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2130674/"
] |
You need to create a new folder right click on res folder create new folder name it anim. And you can put your animation xmls in it.
|
In the Android application default folder structure there is no Anim folder. If you want Anim folder, you should be create it in to the application.
|
21,528,297 |
I'm not able to post Application with Xcode 4.6.2, while uploading it is giving me error "This bundle is invalid. Apple is not currently accepting applications built with this version of the SDK". What SDK would it work with?
|
2014/02/03
|
[
"https://Stackoverflow.com/questions/21528297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1295160/"
] |
i think that should be arrived this email:

from 1 february, the apps must be built with Xcode 5
|
Upgrade your xcode 4.6.3 to xcode 5 and make app support for iOS 7 also. then only appstore validate your app
|
50,980,177 |
I have a table like this:
```
|-------|----------|------------|-----------|------------|
| M_ID | YEAR | NEW_M_ID |STATUS_CODE|GROUP_NUMBER|
|-------|----------|------------|-----------|------------|
|111 |2010 |111-2010 | 0 | |
|111 |2011 |111-2011 | 0 | |
|111 |2013 |111-2013 | 1 | |
|111 |2014 |123-2014 | 0 | |
|123 |2009 |123-2009 | 0 | |
|123 |2010 |123-2010 | 3 | |
|123 |2014 |123-2014 | 0 | |
|-------------------------------------------|------------|
```
I want to populate the value in group\_number column on the basis of other column.
and desired output should look like this:
```
|-------|----------|------------|-----------|------------|
| M_ID | YEAR | NEW_M_ID |STATUS_CODE|GROUP_NUMBER|
|-------|----------|------------|-----------|------------|
|111 |2010 |111-2010 | 0 | 1 |
|111 |2011 |111-2011 | 0 | 1 |
|111 |2013 |111-2013 | 1 | 1 |
|111 |2014 |123-2014 | 0 | 2 |
|111 |2015 |123-2015 | 0 | 2 |
|123 |2010 |123-2010 | 3 | 1 |
|123 |2014 |123-2014 | 0 | 2 |
|-------------------------------------------|------------|
```
the code I used is like this:
```
declare
group_num number:=1;
old_acct CHAR(15):=' ' ;
short_acct_number CHAR (10):= ' ';
begin
for i in (
select ACCT_NUMBER, status from xxx.transaction
order by acct_number
)
loop
short_acct_number := SUBSTR(i.ACCT_NUMBER, 1, LENGTH(i.ACCT_NUMBER)-5);
if short_acct_number <> old_acct then
group_num := 1;
end if;
if i.status <> 0 then
update xxx.transaction set group_number = group_num
where acct_number <= i.acct_number
and group_number is null;
group_num := group_num + 1;
end if;
old_acct := short_acct_number;
end loop;
end;
```
The problem with my code is it does not populate group\_number as 1 in 6th row, which is mistake.
Can anyone help please?
|
2018/06/22
|
[
"https://Stackoverflow.com/questions/50980177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7632936/"
] |
Send below query output.
```
select ACCT_NUMBER, status from xxx.transaction
order by acct_number
```
|
Right now this is how your code calculation is working
Declaration:
group\_num = 1
old\_acct = β β
Loop
Iteration 1 and 2 status code = 0 does not enter the loop
Sets old\_acct = short\_acct\_number
For iteration 3 status code = 1 enters the loop
Sets group\_num= group\_num + 1 = 1+1 = 2
For iteration 4 and 5 status code = 0 does not enter the loop
For iteration 6 enters the status code and updates group\_number = group\_num
Which was set to value 2 in iteration 3 as explained above.
This is why you donβt get Group\_Number of 1 in your sixth column.
If 1 is exactly what the answer should be you need to fix the group\_num calculation but at this point you donβt give us the logic behind setting group\_number.
Also on the cursor
```
Select Acct_Number , status from xxx.transaction
```
If your xxx.transaction table only includes the columns you have mentioned above there is no way for us to understand the logic , please share more information on that too.
|
48,178,744 |
I have following implementation:
```
#include <cstddef>
template<typename Data, size_t Size>
class Demo
{
public:
Demo();
private:
Data data[Size];
};
void f(Demo<int, size_t>& demoObj)
{
}
int main()
{
Demo<int, 100> demoObj;
}
```
I get the following error when I compile:
```
g++ -std=c++11 temp.cpp
temp.cpp:13:24: error: type/value mismatch at argument 2 in template parameter list for βtemplate<class Data, long unsigned int Size> class Demoβ
void f(Demo<int, size_t>& demoObj)
^
temp.cpp:13:24: note: expected a constant of type βlong unsigned intβ, got βsize_t {aka long unsigned int}β
```
The error is not making sense to me. Please help me understand it. Also, how do I pass demoObj to function f? I mean how o write the definition of f.
|
2018/01/10
|
[
"https://Stackoverflow.com/questions/48178744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/530340/"
] |
`Size` is a non-type parameter, so it requires a non-type argument:
```
void f(Demo<int, 100>& demoObj);
// ^^^
```
|
If you want to be able to pass in any kind of Demo you can define `f` as a template function.
```
template<typename Data, size_t Size>
void f(Demo<Data, Size>& demoObj)
{
// ...
}
```
|
89,784 |
I have two Oracle 11gR2 databases on separate servers. I want to duplicate these databases.
For this, I do these steps :
* In auxiliary db :
+ create password file with password that is same if target password
* In target database:
+ Create a pfile and set db\_name to auxiliary db
+ in tnsname.ora set the auxiliary db
+ with sqlplus connect to auxiliary db and startup, nomount with pfile.
With rman connect to these db and when I want to duplicate these databases with command below, I have an error that's in attach of this question.
```
Duplicate database to orcl1 with active database spfile nofilenamecheck.
```
Can any one help me?
[](https://i.stack.imgur.com/6M9VP.png)
|
2015/01/21
|
[
"https://dba.stackexchange.com/questions/89784",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/29327/"
] |
If you have "lost the data" because of corruption, you may be able to retrieve some of the data from nonclustered indexes. Or if the corruption is only in nonclustered indexes you may have lost nothing and can rebuild the indexes to recover the data. Search for DBCC PAGE and you may find advice from some experts on what to do.
If you have "lost the data" because someone has deleted it and you have no backup, then that data is simply gone. It doesn't exist anywhere.
I would recommend your client make an insurance claim.
|
By default none of these two can be reverted but there are special cases when this is possible.
***Truncate***: when truncate is executed `SQL Server doesnβt` delete data but only deallocates pages. This means that if you can still read these pages (using query or third party tool) there is a possibility to recover data. However you need to act fast before these pages are overwritten.
***Delete***: If database is in full recovery mode then all transactions are logged in transaction log. If you can read transaction log you can in theory figure out what were the previous values of all affected rows and then recover data.
**Recovery methods:**
One method is using SQL queries similar to the one posted here for truncate or using functions like fn\_dblog to read transaction log.
Another one is to use third party tools such as [ApexSQL Log](http://www.apexsql.com/sql_tools_log.aspx), [SQL Log Rescue](http://www.red-gate.com/labs/free-tools/sql-log-rescue/), [ApexSQL Recover](http://www.apexsql.com/sql_tools_recover.aspx) or [Quest Toad](http://www.quest.com/), [SysTools SQL Log Analyzer](https://www.systoolsgroup.com/sql-log-analyzer.html)
|
411,689 |
After reading [Valve's new employee handbook](http://newcdn.flamehaus.com/Valve_Handbook_LowRes.pdf), I was really interested in setting up a company map like they described on page 6:
>
> "The fact that everyone is always moving around within the company makes people hard to find. Thatβs why we have `http://user` β check it out. We know where you are based on where your machine is plugged in, so use this site to see a map of where everyone is right now."
>
>
>
What I'm trying to figure out is: how I can tell which machine or domain user (either will do) is connected to a particular wall jack?
|
2012/07/27
|
[
"https://serverfault.com/questions/411689",
"https://serverfault.com",
"https://serverfault.com/users/129948/"
] |
Interesting. You'd need a custom web application to associate and present the data - I'm sure Valve doesn't have a problem with this.
I'd envision it like this, in the simplest case:
* Have a database that associates a user's name to the MAC address of their computer, that gets updated when someone's computer changes or a new user is set up.
* Configure your switches so that a description or label on the port conveys something useful about its location; `r102.d004` for Room 102, desk 4, or something like that - something easily machine parsable.
* Have an application sweep the switches every few minutes. Grab the MAC address from what's connected on the port, and the description on the port.
* Use that data along with some nice map graphics that associate `r102.d004` to a physical location, translate that MAC address into the user's name with your user database, and present it in a pretty interface.
if you use 802.1x, then you may want to adjust to use that data instead - and I can envision doing this with wireless access points to get the approximate location of someone's wireless client as well. Good luck!
|
I am facing a [similar](https://serverfault.com/questions/423972/locate-devices-within-a-building) problem. As for "sweeping" the switches, that can easily be done via snmpwalk. Here's a simple loop to do just that:
```
for airport14 in 192.168.0.205 192.168.0.206 192.168.0.207 192.168.0.208
do
snmpwalk -v 2c -c community $airport14 AIRPORT-BASESTATION-3-MIB::wirelessPhysAddress | grep -o '"[^"]*"' | tr -d '"' | awk '!x[$0]++' | tr '[A-Z]' '[a-z]' >> /tmp/14wifi.txt
done
```
|
26,566,654 |
I'm currently trying to pass an array of (values[3]) which it's first 3 values contain user input. However, I'm getting the error "expected int\* but argument is type of int". I've tried to pass to method1, without the iteration of 'i', using the first three positions in the values array, but that's as far as I managed to attempt to fix it, any help would be much appreciated!
```
int main(void)
{
int i;
int values[3];
printf("Enter three consecutive numbers (With spaces between)");
scanf("%d %d %d",&values[0],&values[1],&values[2]);
for(i=0;i<3;i++)
method1(values[i]);
}
int method1(int values[3])
{
}
```
|
2014/10/25
|
[
"https://Stackoverflow.com/questions/26566654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You cannot pass an array to a function as an array - it "decays" to a pointer. There are two issues with your code:
* There is no forward declaration of `method1` visible at the point of invocation, and
* You are passing `values[i]`, a *scalar* value in place of an array.
A forward declaration is necessary because otherwise the compiler would assume that `method1` takes an returns an `int`, which is not true. Add this line before `main`
```
int method1(int values[]);
```
You could also move `method1` above `main` to fix this without providing a forward declaration. Also, `3` inside square brackets is not necessary, because the array is passed like a pointer anyway.
If you want to pass the entire array, pass `values`. Of course, `i` becomes unnecessary:
```
int res = method1(values);
```
|
```
#include <stdio.h>
int main(void)
{
int i;
int values[3];
printf("Enter three consecutive numbers (With spaces between)");
scanf("%d %d %d",&values[0],&values[1],&values[2]);
method1(values, 3);
getchar();
getchar();
return 0;
}
int method1(int* values, int size)
{
int i;
for(i=0; i<size; i++){
printf("%d ", values[i]);
}
return 1;
}
```
In C, arrays are passed by reference, you can see method1's first argument is int\* that refers first element of array, and second argument is size of this array.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.
By the way, you can do an outer join with the first syntax too:
```
WHERE a.x = b.x(+)
```
Or
```
WHERE a.x *= b.x
```
Or
```
WHERE a.x = b.x or a.x not in (select x from b)
```
|
Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The second is preferred because it is far less likely to result in an accidental cross join by forgetting to put inthe where clause. A join with no on clause will fail the syntax check, an old style join with no where clause will not fail, it will do a cross join.
Additionally when you later have to a left join, it is helpful for maintenance that they all be in the same structure. And the old syntax has been out of date since 1992, it is well past time to stop using it.
Plus I have found that many people who exclusively use the first syntax don't really understand joins and understanding joins is critical to getting correct results when querying.
|
When you need an outer join the second syntax is **not** always required:
Oracle:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x(+)
```
MSSQLServer (although it's been [deprecated](http://msdn.microsoft.com/en-us/library/dd172122.aspx) in 2000 version)/Sybase:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x *= b.x
```
But returning to your question. I don't know the answer, but it is probably related to the fact that a **join** is more natural (syntactically, at least) than adding an expression to a **where** clause when you are doing exactly that: **joining**.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
I think there are some good reasons on this page to adopt the second method -using explicit JOINs. The clincher though is that when the JOIN criteria are removed from the WHERE clause it becomes much easier to see the remaining selection criteria in the WHERE clause.
In really complex SELECT statements it becomes much easier for a reader to understand what is going on.
|
I hear a lot of people complain the first one is too difficult to understand and that it is unclear. I don't see a problem with it, but after having that discussion, I use the second one even on INNER JOINS for clarity.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The second is preferred because it is far less likely to result in an accidental cross join by forgetting to put inthe where clause. A join with no on clause will fail the syntax check, an old style join with no where clause will not fail, it will do a cross join.
Additionally when you later have to a left join, it is helpful for maintenance that they all be in the same structure. And the old syntax has been out of date since 1992, it is well past time to stop using it.
Plus I have found that many people who exclusively use the first syntax don't really understand joins and understanding joins is critical to getting correct results when querying.
|
The `SELECT * FROM table1, table2, ...` syntax is ok for a couple of tables, but it becomes exponentially (*not necessarily a mathematically accurate statement*) harder and harder to read as the number of tables increases.
The JOIN syntax is harder to write (at the beginning), but it makes it explicit what criteria affects which tables. This makes it much harder to make a mistake.
Also, if all the joins are INNER, then both versions are equivalent. However, the moment you have an OUTER join anywhere in the statement, things get much more complicated and it's virtually guarantee that what you write won't be querying what you think you wrote.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The old syntax, with just listing the tables, and using the `WHERE` clause to specify the join criteria, is being deprecated in most modern databases.
It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.
Let me give you an example.
Let's suppose you have 3 tables in your system:
```
Company
Department
Employee
```
Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.
Ok, so now you want to do the following:
>
> List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.
>
>
>
So you do this:
```
SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
AND Department.ID = Employee.DepartmentID
```
Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.
Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.
If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.
The reason for this is that the `WHERE` clause determines which *rows* end up in the final result, not individual parts of the rows.
And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.
On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.
So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.
Enter the new syntax, with this you can choose.
For instance, if you want all companies, as the problem description stated, this is what you would write:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID
```
Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.
Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'
```
This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.
This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).
Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.
So there you have it.
LEFT and INNER JOIN is the wave of the future.
|
The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.
By the way, you can do an outer join with the first syntax too:
```
WHERE a.x = b.x(+)
```
Or
```
WHERE a.x *= b.x
```
Or
```
WHERE a.x = b.x or a.x not in (select x from b)
```
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.
By the way, you can do an outer join with the first syntax too:
```
WHERE a.x = b.x(+)
```
Or
```
WHERE a.x *= b.x
```
Or
```
WHERE a.x = b.x or a.x not in (select x from b)
```
|
When you need an outer join the second syntax is **not** always required:
Oracle:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x(+)
```
MSSQLServer (although it's been [deprecated](http://msdn.microsoft.com/en-us/library/dd172122.aspx) in 2000 version)/Sybase:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x *= b.x
```
But returning to your question. I don't know the answer, but it is probably related to the fact that a **join** is more natural (syntactically, at least) than adding an expression to a **where** clause when you are doing exactly that: **joining**.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
Basically, when your FROM clause lists tables like so:
```
SELECT * FROM
tableA, tableB, tableC
```
the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction `WHERE tableA.id = tableB.a_id` which will throw away a huge number of rows, then further ... `AND tableB.id = tableC.b_id` and you should then get only those rows you are really interested in.
DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement *more* readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like
```
tableA.id = tableB.a_id
AND tableB.id = tableC.b_id
```
which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.
|
I think there are some good reasons on this page to adopt the second method -using explicit JOINs. The clincher though is that when the JOIN criteria are removed from the WHERE clause it becomes much easier to see the remaining selection criteria in the WHERE clause.
In really complex SELECT statements it becomes much easier for a reader to understand what is going on.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The old syntax, with just listing the tables, and using the `WHERE` clause to specify the join criteria, is being deprecated in most modern databases.
It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.
Let me give you an example.
Let's suppose you have 3 tables in your system:
```
Company
Department
Employee
```
Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.
Ok, so now you want to do the following:
>
> List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.
>
>
>
So you do this:
```
SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
AND Department.ID = Employee.DepartmentID
```
Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.
Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.
If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.
The reason for this is that the `WHERE` clause determines which *rows* end up in the final result, not individual parts of the rows.
And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.
On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.
So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.
Enter the new syntax, with this you can choose.
For instance, if you want all companies, as the problem description stated, this is what you would write:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID
```
Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.
Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'
```
This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.
This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).
Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.
So there you have it.
LEFT and INNER JOIN is the wave of the future.
|
Basically, when your FROM clause lists tables like so:
```
SELECT * FROM
tableA, tableB, tableC
```
the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction `WHERE tableA.id = tableB.a_id` which will throw away a huge number of rows, then further ... `AND tableB.id = tableC.b_id` and you should then get only those rows you are really interested in.
DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement *more* readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like
```
tableA.id = tableB.a_id
AND tableB.id = tableC.b_id
```
which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The old syntax, with just listing the tables, and using the `WHERE` clause to specify the join criteria, is being deprecated in most modern databases.
It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.
Let me give you an example.
Let's suppose you have 3 tables in your system:
```
Company
Department
Employee
```
Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.
Ok, so now you want to do the following:
>
> List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.
>
>
>
So you do this:
```
SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
AND Department.ID = Employee.DepartmentID
```
Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.
Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.
If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.
The reason for this is that the `WHERE` clause determines which *rows* end up in the final result, not individual parts of the rows.
And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.
On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.
So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.
Enter the new syntax, with this you can choose.
For instance, if you want all companies, as the problem description stated, this is what you would write:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID
```
Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.
Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'
```
This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.
This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).
Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.
So there you have it.
LEFT and INNER JOIN is the wave of the future.
|
To the database, they end up being the same. For you, though, you'll have to use that second syntax in some situations. For the sake of editing queries that end up having to use it (finding out you needed a left join where you had a straight join), and for consistency, I'd pattern only on the 2nd method. It'll make reading queries easier.
|
894,490 |
Most SQL dialects accept both the following queries:
```
SELECT a.foo, b.foo
FROM a, b
WHERE a.x = b.x
SELECT a.foo, b.foo
FROM a
LEFT JOIN b ON a.x = b.x
```
Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)?
|
2009/05/21
|
[
"https://Stackoverflow.com/questions/894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44065/"
] |
The old syntax, with just listing the tables, and using the `WHERE` clause to specify the join criteria, is being deprecated in most modern databases.
It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.
Let me give you an example.
Let's suppose you have 3 tables in your system:
```
Company
Department
Employee
```
Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.
Ok, so now you want to do the following:
>
> List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.
>
>
>
So you do this:
```
SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
AND Department.ID = Employee.DepartmentID
```
Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.
Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.
If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.
The reason for this is that the `WHERE` clause determines which *rows* end up in the final result, not individual parts of the rows.
And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.
On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.
So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.
Enter the new syntax, with this you can choose.
For instance, if you want all companies, as the problem description stated, this is what you would write:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID
```
Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.
Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:
```
SELECT *
FROM Company
LEFT JOIN (
Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'
```
This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.
This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).
Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.
So there you have it.
LEFT and INNER JOIN is the wave of the future.
|
I hear a lot of people complain the first one is too difficult to understand and that it is unclear. I don't see a problem with it, but after having that discussion, I use the second one even on INNER JOINS for clarity.
|
2,304,580 |
The Java documentation for [Comparable](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html) recommends that compareTo be consistent with equals (because of the behavior in sorted sets or sorted maps).
I have a Player object which is mutable. Player will not be used in any kind of sorted set or sorted map.
I want to have an array of Players (Player[]) and assign each player a random order of play (a member variable m\_nPlayOrder), then sort them in that array based on their m\_nPlayOrder member variable.
I will implement the Comparable interface and the compareTo function to achieve this.
My question is, is it ok in this case if Player has a compareTo that is NOT consistant with equals? It will not be consistant with equals unless I also override equals (and hashCode) and have it return true if the Players m\_nPlayerOrder are equal. I do not want to do that.
UPDATE:
Thanks everyone for the replys! I'm going with implementing the Comparator instead of Comparable.
|
2010/02/21
|
[
"https://Stackoverflow.com/questions/2304580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182887/"
] |
You could implement a `java.util.Comparator` (a stand-alone object that "knows" your `Player` class and compares accordingly) and use that instead of implementing `Comparable` in the class.
`Comparator` has the advantage in that you can implement any number of them for different types of sorts, rather than the single `Comparable`.
|
It is not a good practice to implement `equals` and `compareTo` that are inconsistent.
>
> Player will not be used in any kind of sorted set or sorted map.
>
>
>
The problem is that *someone else* trying to maintain your code at some time in the future may not realize that you have implemented inconsistent methods, and may try to put a `Player` into a sorted set/map or some other data structure that expects consistent methods.
There is a good alternative available to you in the form of standalone Comparator objects.
|
2,304,580 |
The Java documentation for [Comparable](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html) recommends that compareTo be consistent with equals (because of the behavior in sorted sets or sorted maps).
I have a Player object which is mutable. Player will not be used in any kind of sorted set or sorted map.
I want to have an array of Players (Player[]) and assign each player a random order of play (a member variable m\_nPlayOrder), then sort them in that array based on their m\_nPlayOrder member variable.
I will implement the Comparable interface and the compareTo function to achieve this.
My question is, is it ok in this case if Player has a compareTo that is NOT consistant with equals? It will not be consistant with equals unless I also override equals (and hashCode) and have it return true if the Players m\_nPlayerOrder are equal. I do not want to do that.
UPDATE:
Thanks everyone for the replys! I'm going with implementing the Comparator instead of Comparable.
|
2010/02/21
|
[
"https://Stackoverflow.com/questions/2304580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182887/"
] |
You could implement a `java.util.Comparator` (a stand-alone object that "knows" your `Player` class and compares accordingly) and use that instead of implementing `Comparable` in the class.
`Comparator` has the advantage in that you can implement any number of them for different types of sorts, rather than the single `Comparable`.
|
The [`Comparable`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) API says, "It is strongly recommended (though not required) that natural orderings be consistent with equals." If you don't, be certain to document the limitations you noted. Alternatively, it may be easy to implement [`Comparable`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) fully, as suggested in this [answer](https://stackoverflow.com/questions/1924728/why-isnt-collections-binarysearch-working-with-this-comparable/1926111#1926111).
|
2,304,580 |
The Java documentation for [Comparable](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html) recommends that compareTo be consistent with equals (because of the behavior in sorted sets or sorted maps).
I have a Player object which is mutable. Player will not be used in any kind of sorted set or sorted map.
I want to have an array of Players (Player[]) and assign each player a random order of play (a member variable m\_nPlayOrder), then sort them in that array based on their m\_nPlayOrder member variable.
I will implement the Comparable interface and the compareTo function to achieve this.
My question is, is it ok in this case if Player has a compareTo that is NOT consistant with equals? It will not be consistant with equals unless I also override equals (and hashCode) and have it return true if the Players m\_nPlayerOrder are equal. I do not want to do that.
UPDATE:
Thanks everyone for the replys! I'm going with implementing the Comparator instead of Comparable.
|
2010/02/21
|
[
"https://Stackoverflow.com/questions/2304580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182887/"
] |
You could implement a `java.util.Comparator` (a stand-alone object that "knows" your `Player` class and compares accordingly) and use that instead of implementing `Comparable` in the class.
`Comparator` has the advantage in that you can implement any number of them for different types of sorts, rather than the single `Comparable`.
|
I do not think you have the problem that you think you have, but perhaps I'm missing something (wouldn't be the first time).
The requirement here is that 2 objects that are equal should also return 0 for compareTo(), meaning that they occupy the same rank for sorting purposes. There is a separate requirement that 2 equal objects should also have the same hashCode. But this isn't a concern for you, because you're overriding neither equals() nor hashCode(); the Java platform will satisfy this one for you.
Since your objects will be equal based on *reference* comparison (not custom, logical comparison), you won't have a problem unless your objects don't compare to themselves. In orther words, as long as a single object, **when asked to compareTo() itself**, would always return 0, you're fine.
|
2,304,580 |
The Java documentation for [Comparable](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html) recommends that compareTo be consistent with equals (because of the behavior in sorted sets or sorted maps).
I have a Player object which is mutable. Player will not be used in any kind of sorted set or sorted map.
I want to have an array of Players (Player[]) and assign each player a random order of play (a member variable m\_nPlayOrder), then sort them in that array based on their m\_nPlayOrder member variable.
I will implement the Comparable interface and the compareTo function to achieve this.
My question is, is it ok in this case if Player has a compareTo that is NOT consistant with equals? It will not be consistant with equals unless I also override equals (and hashCode) and have it return true if the Players m\_nPlayerOrder are equal. I do not want to do that.
UPDATE:
Thanks everyone for the replys! I'm going with implementing the Comparator instead of Comparable.
|
2010/02/21
|
[
"https://Stackoverflow.com/questions/2304580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182887/"
] |
It is not a good practice to implement `equals` and `compareTo` that are inconsistent.
>
> Player will not be used in any kind of sorted set or sorted map.
>
>
>
The problem is that *someone else* trying to maintain your code at some time in the future may not realize that you have implemented inconsistent methods, and may try to put a `Player` into a sorted set/map or some other data structure that expects consistent methods.
There is a good alternative available to you in the form of standalone Comparator objects.
|
The [`Comparable`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) API says, "It is strongly recommended (though not required) that natural orderings be consistent with equals." If you don't, be certain to document the limitations you noted. Alternatively, it may be easy to implement [`Comparable`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) fully, as suggested in this [answer](https://stackoverflow.com/questions/1924728/why-isnt-collections-binarysearch-working-with-this-comparable/1926111#1926111).
|
2,304,580 |
The Java documentation for [Comparable](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html) recommends that compareTo be consistent with equals (because of the behavior in sorted sets or sorted maps).
I have a Player object which is mutable. Player will not be used in any kind of sorted set or sorted map.
I want to have an array of Players (Player[]) and assign each player a random order of play (a member variable m\_nPlayOrder), then sort them in that array based on their m\_nPlayOrder member variable.
I will implement the Comparable interface and the compareTo function to achieve this.
My question is, is it ok in this case if Player has a compareTo that is NOT consistant with equals? It will not be consistant with equals unless I also override equals (and hashCode) and have it return true if the Players m\_nPlayerOrder are equal. I do not want to do that.
UPDATE:
Thanks everyone for the replys! I'm going with implementing the Comparator instead of Comparable.
|
2010/02/21
|
[
"https://Stackoverflow.com/questions/2304580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182887/"
] |
I do not think you have the problem that you think you have, but perhaps I'm missing something (wouldn't be the first time).
The requirement here is that 2 objects that are equal should also return 0 for compareTo(), meaning that they occupy the same rank for sorting purposes. There is a separate requirement that 2 equal objects should also have the same hashCode. But this isn't a concern for you, because you're overriding neither equals() nor hashCode(); the Java platform will satisfy this one for you.
Since your objects will be equal based on *reference* comparison (not custom, logical comparison), you won't have a problem unless your objects don't compare to themselves. In orther words, as long as a single object, **when asked to compareTo() itself**, would always return 0, you're fine.
|
The [`Comparable`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) API says, "It is strongly recommended (though not required) that natural orderings be consistent with equals." If you don't, be certain to document the limitations you noted. Alternatively, it may be easy to implement [`Comparable`](http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html) fully, as suggested in this [answer](https://stackoverflow.com/questions/1924728/why-isnt-collections-binarysearch-working-with-this-comparable/1926111#1926111).
|
46,011,277 |
First I installed the coinmarketcap from the pycharm project interpreter.
Then I run the code below:
```
>>> from coinmarketcap import Market
>>> coinmarketcap = Market()
>>> coinmarketcap.ticker(<currency>, limit=3, convert='EUR')
```
But I got this:
>
> ImportError: cannot import name Market
>
>
>
Then I thought it is not the right library, so I installed the following API from <https://github.com/mrsmn/coinmarketcap-api> thinking that pycharm might have installed some other library.
So I downloaded the library from Github and I used the python setup.py install command and installed the library from Github without any problems.
I tried to rerun the code, but the problem still persists:
>
> ImportError: cannot import name Market
>
>
>
|
2017/09/02
|
[
"https://Stackoverflow.com/questions/46011277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5226914/"
] |
I have finally solved it. Actually I needed to uninstall it within pycharm. Then I installed it using the pip install coinmarketcap and after that it works.
Thank you for your help!
|
[](https://i.stack.imgur.com/h0hB0.png)
I have installed it using pip and tried to import it and did not get any error.so, can you check whether the installation is done with out any error
|
19,895,039 |
I have created a custom login page for a legacy java web app using Spring Security and a JSP page. The legacy app does NOT use Spring MVC. I preview it in MyEclipse and it applies my CSS styles. But when I run it in debug mode and look at it with Firefox it has problems. 1) The CSS is not rendered. 2) After submitting the form, it gets redirected to the CSS file, so the browser shows the text of the CSS file!
I've been over this for a couple of days, and haven't found a solution on this site or any other. I've never had to use JSP or Spring Security before, so I'm not even sure of the culprit. Can anyone point out where I'm screwing up?
My **login.jsp** file:
```
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:url value="/user_pass_login" var="loginUrl"/>
<html>
<HEAD>
<link href="Tracker.css" type="text/css" rel="stylesheet">
<TITLE>ATP3 Login</TITLE>
</HEAD>
<body onload='document.loginForm.username.focus();'>
<DIV id="login_body"
align="center" >
<h1>Sample Tracker Login</h1>
<form id="loginForm" name="loginForm" action="${loginUrl}" method="post">
<c:if test="${param.error != null}">
<div class="alert alert-error">
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
<BR /><BR />Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">You have been logged out.</div>
</c:if>
<BR />
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username" />
<BR />
<BR />
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password" />
<BR />
<BR />
<div class="form-actions">
<input
id="submit"
class="btn"
name="submit"
type="submit"
value="Login" />
</div>
</form>
</DIV>
</body>
</html>
```
After logging in I get redirected to the url for my CSS file, **Tracker.css**:
```
/** Add css rules here for your application. */
/** Example rules used by the template application (remove for your app) */
h1 {
font-size: 2em;
font-weight: bold;
color: #000555;
margin: 40px 0px 70px;
text-align: center;
}
#login_body, #formLogin {
color: #000555;
background-color: #F6FCED;
}
.sendButton {
display: block;
font-size: 16pt;
}
/** Most GWT widgets already have a style name defined */
.gwt-DialogBox {
width: 400px;
}
...
```
After thinking about what @Santosh Joshi said, I reviewed the security settings within my Spring Security configuration XML file. And here is what was happening:
1. When the **login.jsp** first loads it doesn't have access to the **Tracker.css** file, because the security settings prevent it (see below for the corrected file), so the page isn't formatted.
2. When the user successfully logs in, the CSS file is found, but since the JSP is malformed, it just spews the CSS file.
**The Fix**
1. I modified the **login.jsp** as follows:
1. Remove line 1 with xml definition
2. Move line 4 with a url variable declaration to just above the form tag
3. Add an html document type definition just below the JSP directives
2. I added a permission line to the Spring Security XML http tag
The new **login.jsp** file
```
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<HEAD>
<link href="Tracker.css" type="text/css" rel="stylesheet">
<TITLE>ATP3 Login</TITLE>
</HEAD>
<body onload='document.loginForm.username.focus();'>
<DIV id="login_body"
align="center" >
<h1>Sample Tracker Login</h1>
<c:url value="/user_pass_login" var="loginUrl"/>
<form id="loginForm" name="loginForm" action="${loginUrl}" method="post">
<c:if test="${param.error != null}">
<div class="alert alert-error">
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
<BR /><BR />Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">You have been logged out.</div>
</c:if>
<BR />
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username" />
<BR />
<BR />
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password" />
<BR />
<BR />
<div class="form-actions">
<input
id="submit"
class="btn"
name="submit"
type="submit"
value="Login" />
</div>
</form>
</DIV>
</body>
</html>
```
Here is a snippet from the security XML file. Note the new intercept-url tag for **Tracker.css**:
```
<!-- This is where we configure Spring-Security -->
<http auto-config="true"
use-expressions="true"
disable-url-rewriting="true">
<intercept-url pattern="/"
access="permitAll"/>
<intercept-url pattern="/login*"
access="permitAll"/>
<intercept-url pattern="/login*/*"
access="permitAll"/>
<intercept-url pattern="/favicon.ico"
access="permitAll"/>
<intercept-url pattern="/Tracker.css"
access="permitAll"/>
<intercept-url pattern="/**"
access="hasAnyRole('ROLE_ADMIN','ROLE_WRITE','ROLE_READ')"/>
<form-login login-page="/login.jsp"
login-processing-url="/user_pass_login"
username-parameter="username"
password-parameter="password" />
</http>
```
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19895039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792037/"
] |
Seems a problem with the path of the CSS, where have you placed the CSS
`<link href="Tracker.css" type="text/css" rel="stylesheet"/>`
you can also debug your application in Firefox using firebug, if it's not applying then it means that CSS has not downloaded properly just check console in Firefox for 404 or other errors. Also cheek where is Firefox actually wants to get this( the URLFirefox is referring) CSS .
|
I used to have the same problem with font awesome. After login I would see css contents. I noticed font-awesome folder is outside of css folder, so I added a new security rule:
```
.antMatchers("/font-awesome/**").permitAll()
.antMatchers("/css/**").permitAll()
```
I was using Spring Boot with Thymeleaf and Spring Security.
|
19,895,039 |
I have created a custom login page for a legacy java web app using Spring Security and a JSP page. The legacy app does NOT use Spring MVC. I preview it in MyEclipse and it applies my CSS styles. But when I run it in debug mode and look at it with Firefox it has problems. 1) The CSS is not rendered. 2) After submitting the form, it gets redirected to the CSS file, so the browser shows the text of the CSS file!
I've been over this for a couple of days, and haven't found a solution on this site or any other. I've never had to use JSP or Spring Security before, so I'm not even sure of the culprit. Can anyone point out where I'm screwing up?
My **login.jsp** file:
```
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:url value="/user_pass_login" var="loginUrl"/>
<html>
<HEAD>
<link href="Tracker.css" type="text/css" rel="stylesheet">
<TITLE>ATP3 Login</TITLE>
</HEAD>
<body onload='document.loginForm.username.focus();'>
<DIV id="login_body"
align="center" >
<h1>Sample Tracker Login</h1>
<form id="loginForm" name="loginForm" action="${loginUrl}" method="post">
<c:if test="${param.error != null}">
<div class="alert alert-error">
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
<BR /><BR />Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">You have been logged out.</div>
</c:if>
<BR />
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username" />
<BR />
<BR />
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password" />
<BR />
<BR />
<div class="form-actions">
<input
id="submit"
class="btn"
name="submit"
type="submit"
value="Login" />
</div>
</form>
</DIV>
</body>
</html>
```
After logging in I get redirected to the url for my CSS file, **Tracker.css**:
```
/** Add css rules here for your application. */
/** Example rules used by the template application (remove for your app) */
h1 {
font-size: 2em;
font-weight: bold;
color: #000555;
margin: 40px 0px 70px;
text-align: center;
}
#login_body, #formLogin {
color: #000555;
background-color: #F6FCED;
}
.sendButton {
display: block;
font-size: 16pt;
}
/** Most GWT widgets already have a style name defined */
.gwt-DialogBox {
width: 400px;
}
...
```
After thinking about what @Santosh Joshi said, I reviewed the security settings within my Spring Security configuration XML file. And here is what was happening:
1. When the **login.jsp** first loads it doesn't have access to the **Tracker.css** file, because the security settings prevent it (see below for the corrected file), so the page isn't formatted.
2. When the user successfully logs in, the CSS file is found, but since the JSP is malformed, it just spews the CSS file.
**The Fix**
1. I modified the **login.jsp** as follows:
1. Remove line 1 with xml definition
2. Move line 4 with a url variable declaration to just above the form tag
3. Add an html document type definition just below the JSP directives
2. I added a permission line to the Spring Security XML http tag
The new **login.jsp** file
```
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<HEAD>
<link href="Tracker.css" type="text/css" rel="stylesheet">
<TITLE>ATP3 Login</TITLE>
</HEAD>
<body onload='document.loginForm.username.focus();'>
<DIV id="login_body"
align="center" >
<h1>Sample Tracker Login</h1>
<c:url value="/user_pass_login" var="loginUrl"/>
<form id="loginForm" name="loginForm" action="${loginUrl}" method="post">
<c:if test="${param.error != null}">
<div class="alert alert-error">
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
<BR /><BR />Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">You have been logged out.</div>
</c:if>
<BR />
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username" />
<BR />
<BR />
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password" />
<BR />
<BR />
<div class="form-actions">
<input
id="submit"
class="btn"
name="submit"
type="submit"
value="Login" />
</div>
</form>
</DIV>
</body>
</html>
```
Here is a snippet from the security XML file. Note the new intercept-url tag for **Tracker.css**:
```
<!-- This is where we configure Spring-Security -->
<http auto-config="true"
use-expressions="true"
disable-url-rewriting="true">
<intercept-url pattern="/"
access="permitAll"/>
<intercept-url pattern="/login*"
access="permitAll"/>
<intercept-url pattern="/login*/*"
access="permitAll"/>
<intercept-url pattern="/favicon.ico"
access="permitAll"/>
<intercept-url pattern="/Tracker.css"
access="permitAll"/>
<intercept-url pattern="/**"
access="hasAnyRole('ROLE_ADMIN','ROLE_WRITE','ROLE_READ')"/>
<form-login login-page="/login.jsp"
login-processing-url="/user_pass_login"
username-parameter="username"
password-parameter="password" />
</http>
```
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19895039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792037/"
] |
Seems a problem with the path of the CSS, where have you placed the CSS
`<link href="Tracker.css" type="text/css" rel="stylesheet"/>`
you can also debug your application in Firefox using firebug, if it's not applying then it means that CSS has not downloaded properly just check console in Firefox for 404 or other errors. Also cheek where is Firefox actually wants to get this( the URLFirefox is referring) CSS .
|
The CSS file location is already a clue, if you've already added permitAll() to you spring security config file, make sure that the css file (or image file in my case) is actually accessible via url, ie it might need to be in the resource folder.
In my case my image file was hidden in a WEB-INF folder, which is not exposed directly when you are just logging in or just by accessing via url, which somehow breaks spring security.
|
19,895,039 |
I have created a custom login page for a legacy java web app using Spring Security and a JSP page. The legacy app does NOT use Spring MVC. I preview it in MyEclipse and it applies my CSS styles. But when I run it in debug mode and look at it with Firefox it has problems. 1) The CSS is not rendered. 2) After submitting the form, it gets redirected to the CSS file, so the browser shows the text of the CSS file!
I've been over this for a couple of days, and haven't found a solution on this site or any other. I've never had to use JSP or Spring Security before, so I'm not even sure of the culprit. Can anyone point out where I'm screwing up?
My **login.jsp** file:
```
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:url value="/user_pass_login" var="loginUrl"/>
<html>
<HEAD>
<link href="Tracker.css" type="text/css" rel="stylesheet">
<TITLE>ATP3 Login</TITLE>
</HEAD>
<body onload='document.loginForm.username.focus();'>
<DIV id="login_body"
align="center" >
<h1>Sample Tracker Login</h1>
<form id="loginForm" name="loginForm" action="${loginUrl}" method="post">
<c:if test="${param.error != null}">
<div class="alert alert-error">
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
<BR /><BR />Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">You have been logged out.</div>
</c:if>
<BR />
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username" />
<BR />
<BR />
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password" />
<BR />
<BR />
<div class="form-actions">
<input
id="submit"
class="btn"
name="submit"
type="submit"
value="Login" />
</div>
</form>
</DIV>
</body>
</html>
```
After logging in I get redirected to the url for my CSS file, **Tracker.css**:
```
/** Add css rules here for your application. */
/** Example rules used by the template application (remove for your app) */
h1 {
font-size: 2em;
font-weight: bold;
color: #000555;
margin: 40px 0px 70px;
text-align: center;
}
#login_body, #formLogin {
color: #000555;
background-color: #F6FCED;
}
.sendButton {
display: block;
font-size: 16pt;
}
/** Most GWT widgets already have a style name defined */
.gwt-DialogBox {
width: 400px;
}
...
```
After thinking about what @Santosh Joshi said, I reviewed the security settings within my Spring Security configuration XML file. And here is what was happening:
1. When the **login.jsp** first loads it doesn't have access to the **Tracker.css** file, because the security settings prevent it (see below for the corrected file), so the page isn't formatted.
2. When the user successfully logs in, the CSS file is found, but since the JSP is malformed, it just spews the CSS file.
**The Fix**
1. I modified the **login.jsp** as follows:
1. Remove line 1 with xml definition
2. Move line 4 with a url variable declaration to just above the form tag
3. Add an html document type definition just below the JSP directives
2. I added a permission line to the Spring Security XML http tag
The new **login.jsp** file
```
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<HEAD>
<link href="Tracker.css" type="text/css" rel="stylesheet">
<TITLE>ATP3 Login</TITLE>
</HEAD>
<body onload='document.loginForm.username.focus();'>
<DIV id="login_body"
align="center" >
<h1>Sample Tracker Login</h1>
<c:url value="/user_pass_login" var="loginUrl"/>
<form id="loginForm" name="loginForm" action="${loginUrl}" method="post">
<c:if test="${param.error != null}">
<div class="alert alert-error">
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
<BR /><BR />Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">You have been logged out.</div>
</c:if>
<BR />
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username" />
<BR />
<BR />
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password" />
<BR />
<BR />
<div class="form-actions">
<input
id="submit"
class="btn"
name="submit"
type="submit"
value="Login" />
</div>
</form>
</DIV>
</body>
</html>
```
Here is a snippet from the security XML file. Note the new intercept-url tag for **Tracker.css**:
```
<!-- This is where we configure Spring-Security -->
<http auto-config="true"
use-expressions="true"
disable-url-rewriting="true">
<intercept-url pattern="/"
access="permitAll"/>
<intercept-url pattern="/login*"
access="permitAll"/>
<intercept-url pattern="/login*/*"
access="permitAll"/>
<intercept-url pattern="/favicon.ico"
access="permitAll"/>
<intercept-url pattern="/Tracker.css"
access="permitAll"/>
<intercept-url pattern="/**"
access="hasAnyRole('ROLE_ADMIN','ROLE_WRITE','ROLE_READ')"/>
<form-login login-page="/login.jsp"
login-processing-url="/user_pass_login"
username-parameter="username"
password-parameter="password" />
</http>
```
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19895039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792037/"
] |
I used to have the same problem with font awesome. After login I would see css contents. I noticed font-awesome folder is outside of css folder, so I added a new security rule:
```
.antMatchers("/font-awesome/**").permitAll()
.antMatchers("/css/**").permitAll()
```
I was using Spring Boot with Thymeleaf and Spring Security.
|
The CSS file location is already a clue, if you've already added permitAll() to you spring security config file, make sure that the css file (or image file in my case) is actually accessible via url, ie it might need to be in the resource folder.
In my case my image file was hidden in a WEB-INF folder, which is not exposed directly when you are just logging in or just by accessing via url, which somehow breaks spring security.
|
55,733,734 |
I have a question with streaming in general but for the scope of the question let us restrict ourselves with Kafka Streams. Let's narrow the scope further by restricting our problem to just word count, or perhaps counting in general. Say I have a stream of some key and a value, key could be a string (and lets say we can have many strings, except empty strings, consisting of any character in the world) and value is a integer, now we are building a word count app, if the total number of words in the vocabulary is a trillion we cannot store them in some local cache. If a word `w` is seen with a value `x` i need to update the existing count for `w` to `X+x` assuming `X` was the previous count, how will I build this application. I cannot store a trillion words in a `KTable` or any other local storage native to Kafka, how will I build this app? Is my understanding wrong about Streams or how they work.
|
2019/04/17
|
[
"https://Stackoverflow.com/questions/55733734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3701377/"
] |
Because Kafka Streams scales horizontally, you can deploy as many application instances as you want. Thus, it should actually be possible to build this application. Note that the `KTable` state will be sharded over all machines.
If you assume a trillion keys, and each key is about 100 bytes, you would need about 100 TB of storage. To give some head room, in practice you might want to provision 200 TB. Thus, 100 instances with 2 TB each should do the job.
For this, your input topic would need to have 100 partitions, what is not a problem for Kafka though.
|
(+1 to what Matthias J. Sax said in his answer.)
An alternative approach is to use probabilistic counting, which has *significantly* lower storage and memory footprint; i.e., to use a probabilistic data structure like [Count-min Sketch](https://en.wikipedia.org/wiki/Count%E2%80%93min_sketch) (CMS) instead of a linear data structure like Kafka Streams' `KTable` or a Java `HashMap`.
There is an example called `ProbabilisticCounting` available that demonstrates how to perform probabilistic counting with CMS in Kafka Streams: <https://github.com/confluentinc/kafka-streams-examples> ([direct link](https://github.com/confluentinc/kafka-streams-examples/blob/5.2.1-post/src/test/scala/io/confluent/examples/streams/ProbabilisticCountingScalaIntegrationTest.scala) for Confluent Platform version 5.2.1 / Apache Kafka 2.2.1)
I have successfully used probabilistic counting for similar use cases where the key space is very large (in your case: trillions of keys).
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
Open Command Prompt, right click on the header bar at the top, select Properties, customize it in there:


|
You can use PowerShell on windows XP and up, and it comes with the newer versions of Windows. See [Costumizing the Windows PowerShell Console](http://technet.microsoft.com/en-us/library/ee156814.aspx), [Display Output in Color Using Windows PowerShell](http://technet.microsoft.com/en-us/library/ff406264.aspx), and [Windows PowerShell Tip: Modifying Message Colors](http://technet.microsoft.com/en-us/library/ee692799.aspx) from Microsoft Technet, for information on different some ways of customization.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
Running `cmd.exe /t:12` will create a command prompt window with a blue background and green text.
You can find a list of available colors [here](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true).
|
You can use PowerShell on windows XP and up, and it comes with the newer versions of Windows. See [Costumizing the Windows PowerShell Console](http://technet.microsoft.com/en-us/library/ee156814.aspx), [Display Output in Color Using Windows PowerShell](http://technet.microsoft.com/en-us/library/ff406264.aspx), and [Windows PowerShell Tip: Modifying Message Colors](http://technet.microsoft.com/en-us/library/ee692799.aspx) from Microsoft Technet, for information on different some ways of customization.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
**One small step...**
I made a clone of [HotDIR](https://veganaize.github.io/HotDIR/) (only for Windows command-line) that colorizes directory listings:
**USAGE:**
```
c:\> hd /?
```
[](https://i.stack.imgur.com/JjrVs.png)
|
I don't think you can customise CMD the way you describe in your comment to Moab's answer.
If it's relevant, there are alternatives to Windows' CMD.
You can try [console](http://sourceforge.net/projects/console/) which is a nice small freeware that does a great job.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
You can't do that because the way the Windows console works is fundamentally different from the Linux terminal. On Linux the coloring is done using [ANSI escape sequences](http://en.wikipedia.org/wiki/ANSI_escape_code). From Wikipedia:
>
> ANSI escape sequences are characters
> embedded in the text used to control
> formatting, color, and other output
> options on video text terminals.
> Almost all terminal emulators designed
> to show text output from a remote
> computer, and (except for Windows) to
> show text output from local software,
> interpret at least some of the ANSI
> escape sequences.
>
>
>
This pretty much means that coloring (and formatting in general) can be controlled by the user, even when the original program had no provision for that, by simply using strings which contain ANSI escapes.
On Windows, the console formatting has to be done explicitly by the program. Each character cell is comprised of two 16-bit codes: a Unicode character and a style word (mainly color information). The program has to use the low-level API output functions to set the style information, otherwise all characters use the default style (gray on black).
The moral of the story I guess is that Windows and Linux are two completely different operating systems. It is therefore better to get used to their idiosyncrasies, than to fight to fit either one to the mindset of the other. That way madness lies.
|
**One small step...**
I made a clone of [HotDIR](https://veganaize.github.io/HotDIR/) (only for Windows command-line) that colorizes directory listings:
**USAGE:**
```
c:\> hd /?
```
[](https://i.stack.imgur.com/JjrVs.png)
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
Open Command Prompt, right click on the header bar at the top, select Properties, customize it in there:


|
I don't think you can customise CMD the way you describe in your comment to Moab's answer.
If it's relevant, there are alternatives to Windows' CMD.
You can try [console](http://sourceforge.net/projects/console/) which is a nice small freeware that does a great job.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
You can use PowerShell on windows XP and up, and it comes with the newer versions of Windows. See [Costumizing the Windows PowerShell Console](http://technet.microsoft.com/en-us/library/ee156814.aspx), [Display Output in Color Using Windows PowerShell](http://technet.microsoft.com/en-us/library/ff406264.aspx), and [Windows PowerShell Tip: Modifying Message Colors](http://technet.microsoft.com/en-us/library/ee692799.aspx) from Microsoft Technet, for information on different some ways of customization.
|
I don't think you can customise CMD the way you describe in your comment to Moab's answer.
If it's relevant, there are alternatives to Windows' CMD.
You can try [console](http://sourceforge.net/projects/console/) which is a nice small freeware that does a great job.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
You can't do that because the way the Windows console works is fundamentally different from the Linux terminal. On Linux the coloring is done using [ANSI escape sequences](http://en.wikipedia.org/wiki/ANSI_escape_code). From Wikipedia:
>
> ANSI escape sequences are characters
> embedded in the text used to control
> formatting, color, and other output
> options on video text terminals.
> Almost all terminal emulators designed
> to show text output from a remote
> computer, and (except for Windows) to
> show text output from local software,
> interpret at least some of the ANSI
> escape sequences.
>
>
>
This pretty much means that coloring (and formatting in general) can be controlled by the user, even when the original program had no provision for that, by simply using strings which contain ANSI escapes.
On Windows, the console formatting has to be done explicitly by the program. Each character cell is comprised of two 16-bit codes: a Unicode character and a style word (mainly color information). The program has to use the low-level API output functions to set the style information, otherwise all characters use the default style (gray on black).
The moral of the story I guess is that Windows and Linux are two completely different operating systems. It is therefore better to get used to their idiosyncrasies, than to fight to fit either one to the mindset of the other. That way madness lies.
|
You can use PowerShell on windows XP and up, and it comes with the newer versions of Windows. See [Costumizing the Windows PowerShell Console](http://technet.microsoft.com/en-us/library/ee156814.aspx), [Display Output in Color Using Windows PowerShell](http://technet.microsoft.com/en-us/library/ff406264.aspx), and [Windows PowerShell Tip: Modifying Message Colors](http://technet.microsoft.com/en-us/library/ee692799.aspx) from Microsoft Technet, for information on different some ways of customization.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
You could always install [Cygwin](http://www.cygwin.com/)
|
I don't think you can customise CMD the way you describe in your comment to Moab's answer.
If it's relevant, there are alternatives to Windows' CMD.
You can try [console](http://sourceforge.net/projects/console/) which is a nice small freeware that does a great job.
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
Running `cmd.exe /t:12` will create a command prompt window with a blue background and green text.
You can find a list of available colors [here](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true).
|
**One small step...**
I made a clone of [HotDIR](https://veganaize.github.io/HotDIR/) (only for Windows command-line) that colorizes directory listings:
**USAGE:**
```
c:\> hd /?
```
[](https://i.stack.imgur.com/JjrVs.png)
|
249,128 |
I love the Linux console, but due to many reasons have to work under Windows XP. So now I decided to make it look better but couldn't find any documentation/posts about it. Is it possible at all?
|
2011/02/22
|
[
"https://superuser.com/questions/249128",
"https://superuser.com",
"https://superuser.com/users/68730/"
] |
You could always install [Cygwin](http://www.cygwin.com/)
|
**One small step...**
I made a clone of [HotDIR](https://veganaize.github.io/HotDIR/) (only for Windows command-line) that colorizes directory listings:
**USAGE:**
```
c:\> hd /?
```
[](https://i.stack.imgur.com/JjrVs.png)
|
63,063,538 |
Wanted to ask people with more experience with React about this, since I can't seem to find a definitive answer. I know you don't want to add text to the DOM directly, which is why React makes you write `dangerouslySetInnerHtml` in order to set it.
But what about `classList.{ add || remove || toggle }`? Is using `classList.add() || .remove()` tantamount to `dangerouslySetInnerHtml`? Should I be worried about doing this, too?
Case in point - a function that renders a list from inside a component styled with bootstrap css.
Problem: Set add/remove `.active` to `li className` on mouse hover.
```
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
const RenderList = (array, position = 'text-center') => {
const handleMouseEnter = e => {
e.target.classList.add('active');
};
const handleMouseLeave = e => {
e.target.classList.remove('active');
};
return (
<ul className={`list-group ${position}`}>
{array.map(({ href, key, label, rel, target }) => (
<a key={key} href={href} rel={rel} target={target} fontSize={1.2}>
<li
className={`list-group-item '${key}'`}
data-id={key}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{label}
</li>
</a>
))}
</ul>
);
};
export default RenderList;
```
The problem is - I've tried setting this in state, but it affects all `li`s at once (I've seen this issue in other questions - albeit, not for functional components, but for classes)
Is this safe? I don't see any warnings in my browser.
If it's not safe, what's the alternative? I tried using a `data-id` attribute from the key for the `li`, but I wasn't quite able to wrap my head around `useState` for a single element...
Edit: A question was suggested as a possible answer, but it recommends making a separate instance of state for each list item, which doesn't seem like a very good solution.
|
2020/07/23
|
[
"https://Stackoverflow.com/questions/63063538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5092134/"
] |
Mutating the DOM manually is an anti-pattern in React
=====================================================
React is a data-first UI lib, meaning that the data dictates how it should render, and it (almost) never need to read the DOM. It only writes to the DOM, and with its internal diffing algorithm, it computes the minimal chunks to update in the DOM.
When mutating the DOM ourselves, React won't be aware of our changes and might wipe our efforts in the next render phase.
Toggling styling on mouse hover
===============================
Whenever possible, favor CSS selectors over JavaScript to style your components. In this case, it would be a simple selector:
```css
.list-group li:hover {
/* `.active` styles here */
}
```
How to toggle classes on each item?
===================================
To avoid managing the state of each individual items in the list component, I'd make an `Item` component which manages its own state and events, leaving the parent list to focus on its actual logic.
```js
const { useState } = React;
// Manages its own state and events, making it
// possible to toggle the class here instead.
const Item = ({ to }) => {
const [active, setActive] = useState(false);
return (
<li
className={active? 'active' : ''}
onMouseEnter={() => setActive(true)}
onMouseLeave={() => setActive(false)}
>
<a data-link={to}>{to}</a>
</li>
);
};
// No more class toggling logic needed here.
const List = ({ items }) => (
<ul>
{items.map((itemProps) => <Item {...itemProps} />)}
</ul>
);
ReactDOM.render(
<List items={[{ to: '/home' }, { to: '/foo' }]} />,
document.querySelector('[data-role-react-root]')
);
```
```css
.active {
background: red;
}
```
```html
<div data-role-react-root></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
```
|
I think I may have found a solution to this, but I'm not exactly sure if it's the correct way to do it. It still manipulates the DOM, but using the state - so presumably React can decide when to do it:
```
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
const RenderList = (array, position = 'text-center') => {
const [isActive, setIsActive] = useState(null);
const [isNotActive, setIsNotActive] = useState(null);
const handleMouseEnter = e => {
setIsActive(e.target.classList.add('active'));
};
const handleMouseLeave = e => {
setIsNotActive(e.target.classList.remove('active'));
};
return (
<ul className={`list-group ${position}`}>
{array.map(({ href, key, label, rel, target }) => (
<a key={key} href={href} rel={rel} target={target} fontSize={1.2}>
<li
className={`list-group-item '${key}'`}
data-id={key}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{label}
</li>
</a>
))}
</ul>
);
};
export default RenderList;
```
Would love feedback
|
12,175,582 |
I have a method returning `IEnumerable` object, but I found that sometimes (on error) the method returns null value of `IEnumerable`.
The method looks something like this.
```
IEnumerable<string> function(String param1, String param2)
{
IEnumerable s = null;
s = (some query over here);
return s;
}
```
When I call this method with `param2`, the function internally fails and returns s which is null at this time.
So, to detect this I used,
```
IEnumerable<string> a = function(1,0);
if (a.count<string> > 0) //not working
if (a == 0) //not working.
```
What is the correct method to use `IEnumerable` and check whether it is null before any other operation?
|
2012/08/29
|
[
"https://Stackoverflow.com/questions/12175582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360251/"
] |
Yours `s = (some query over here);` is returning null. That is why you are getting the exception.
Later your check should be:
```
if(a != null)
```
and
```
if(a.Count() > 0)
```
You can combine both as:
```
if(a!=null && a.Count() >0)
{
// do your work
}
```
|
`null` is not the same as an enumeration without any elements. Therefore, your check for `if(a.count<string> > 0)` fails. (In fact, `a` isn't pointing to any instance whose number of elements you could retrieve with `Count`.)
Also, `null` is not the same as the integer value `0`. Therefore, your check for `if(a == 0)` fails, too.
However, `null` is a keyword in C# and you can compare to that:
```
if (a == null)
```
|
12,175,582 |
I have a method returning `IEnumerable` object, but I found that sometimes (on error) the method returns null value of `IEnumerable`.
The method looks something like this.
```
IEnumerable<string> function(String param1, String param2)
{
IEnumerable s = null;
s = (some query over here);
return s;
}
```
When I call this method with `param2`, the function internally fails and returns s which is null at this time.
So, to detect this I used,
```
IEnumerable<string> a = function(1,0);
if (a.count<string> > 0) //not working
if (a == 0) //not working.
```
What is the correct method to use `IEnumerable` and check whether it is null before any other operation?
|
2012/08/29
|
[
"https://Stackoverflow.com/questions/12175582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360251/"
] |
you could return an empty enumerable if the search result was null:
```
IEnumerable<string> function(String param1, String param2)
{
IEnumerable s = null;
s = (some query over here);
return s ?? Enumerable.Empty<string>();
}
```
|
`null` is not the same as an enumeration without any elements. Therefore, your check for `if(a.count<string> > 0)` fails. (In fact, `a` isn't pointing to any instance whose number of elements you could retrieve with `Count`.)
Also, `null` is not the same as the integer value `0`. Therefore, your check for `if(a == 0)` fails, too.
However, `null` is a keyword in C# and you can compare to that:
```
if (a == null)
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
One way to do it is by defining a custom `select` function and by not using an `<a>` for the links
HTML:
```
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
```
JS:
```
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").autocomplete({
source: availableTags,
select: function (event, ui) {
var elem = $(event.originalEvent.toElement);
if (elem.hasClass('ac-item-a')) {
var url = elem.attr('data-url');
event.preventDefault();
window.open(url, '_blank ');
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a>' + item.label + '<span class="ac-item-a" data-url="http://www.nba.com"> View Details</span></a>')
.appendTo(ul);
};
```
[JSFIDDLE](http://jsfiddle.net/sqsinger/jkukvpgo/3/).
|
Amir, regarding to your answer, I think that opening window inside javascript function from **select** event can be blocked by PopupBlocker
pinghsien422 , your server side should return Json and not complete html , if you must return complete html, make the following changes:
1.Remove the clientSelect function
2.No 'a' tag is needed in renderData function
```
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append( item.label )
.appendTo(ul);
};
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
One way to do it is by defining a custom `select` function and by not using an `<a>` for the links
HTML:
```
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
```
JS:
```
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").autocomplete({
source: availableTags,
select: function (event, ui) {
var elem = $(event.originalEvent.toElement);
if (elem.hasClass('ac-item-a')) {
var url = elem.attr('data-url');
event.preventDefault();
window.open(url, '_blank ');
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a>' + item.label + '<span class="ac-item-a" data-url="http://www.nba.com"> View Details</span></a>')
.appendTo(ul);
};
```
[JSFIDDLE](http://jsfiddle.net/sqsinger/jkukvpgo/3/).
|
Try to do `even.stopImmediatePropagation` in `onclick` binding to link. Page is opening and select handler not executed.
```
var li = $("<li></li>")
.data("item.autocomplete", item)
.append('<a class="ac-item-a" href="http://www.nba.com">' + item.label + '</a>')
.appendTo(ul);
li.find('a').bind('click', function(event){ event.stopImmediatePropagation() });
return li;
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
One way to do it is by defining a custom `select` function and by not using an `<a>` for the links
HTML:
```
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
```
JS:
```
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").autocomplete({
source: availableTags,
select: function (event, ui) {
var elem = $(event.originalEvent.toElement);
if (elem.hasClass('ac-item-a')) {
var url = elem.attr('data-url');
event.preventDefault();
window.open(url, '_blank ');
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a>' + item.label + '<span class="ac-item-a" data-url="http://www.nba.com"> View Details</span></a>')
.appendTo(ul);
};
```
[JSFIDDLE](http://jsfiddle.net/sqsinger/jkukvpgo/3/).
|
Okay, jquery's event takes precedence over your select event - no matter what you do, you can't stop anything there. But you can proxify menuselect event and then decide if it should be invoked ([jsfiddle](http://jsfiddle.net/ev8dnxrh/2/)).
```
var ac = $("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: document.body,
source: availableTags,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete");
ac._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<div>"+item.label+"<a class='link' href='http://test'>(http://test)</a></div>")
.appendTo(ul);
};
var ms = $._data(ac.menu.element.get(0), 'events').menuselect[0].handler;
ac.menu.element.off("menuselect");
ac.menu.element.on("menuselect", function (ev) {
if($(ev.originalEvent.target).hasClass("link"))
return;
ms.apply(this,arguments);
});
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
One way to do it is by defining a custom `select` function and by not using an `<a>` for the links
HTML:
```
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
```
JS:
```
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").autocomplete({
source: availableTags,
select: function (event, ui) {
var elem = $(event.originalEvent.toElement);
if (elem.hasClass('ac-item-a')) {
var url = elem.attr('data-url');
event.preventDefault();
window.open(url, '_blank ');
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a>' + item.label + '<span class="ac-item-a" data-url="http://www.nba.com"> View Details</span></a>')
.appendTo(ul);
};
```
[JSFIDDLE](http://jsfiddle.net/sqsinger/jkukvpgo/3/).
|
Have you thought about putting a conditional in your click handler to **not** `preventDefault` when it is that link? If you test if the element should function as normal then you can `return` early before the `preventDefault` and then the link should function as normal.
Here is an example ([JSBin](http://output.jsbin.com/qulucu/)):
```js
function clickHandler(e) {
// If the target element has the class `test-clickable` then the
// function will return early, before `preventDefault`.
if (this.className.indexOf('test-clickable') !== -1) {
return;
}
alert('That link is not clickable because of `preventDefault`');
e.preventDefault();
}
$('a').click(clickHandler);
```
```css
a {
display: block;
}
a:after {
content: ' [class=' attr(class)']';
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class='test-clickable' href='http://www.google.com' target='_blank'>Link</a>
<a class='test-not-clickable' href='http://www.google.com' target='_blank'>Link</a>
</body>
</html>
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
Amir, regarding to your answer, I think that opening window inside javascript function from **select** event can be blocked by PopupBlocker
pinghsien422 , your server side should return Json and not complete html , if you must return complete html, make the following changes:
1.Remove the clientSelect function
2.No 'a' tag is needed in renderData function
```
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append( item.label )
.appendTo(ul);
};
```
|
Try to do `even.stopImmediatePropagation` in `onclick` binding to link. Page is opening and select handler not executed.
```
var li = $("<li></li>")
.data("item.autocomplete", item)
.append('<a class="ac-item-a" href="http://www.nba.com">' + item.label + '</a>')
.appendTo(ul);
li.find('a').bind('click', function(event){ event.stopImmediatePropagation() });
return li;
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
Have you thought about putting a conditional in your click handler to **not** `preventDefault` when it is that link? If you test if the element should function as normal then you can `return` early before the `preventDefault` and then the link should function as normal.
Here is an example ([JSBin](http://output.jsbin.com/qulucu/)):
```js
function clickHandler(e) {
// If the target element has the class `test-clickable` then the
// function will return early, before `preventDefault`.
if (this.className.indexOf('test-clickable') !== -1) {
return;
}
alert('That link is not clickable because of `preventDefault`');
e.preventDefault();
}
$('a').click(clickHandler);
```
```css
a {
display: block;
}
a:after {
content: ' [class=' attr(class)']';
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class='test-clickable' href='http://www.google.com' target='_blank'>Link</a>
<a class='test-not-clickable' href='http://www.google.com' target='_blank'>Link</a>
</body>
</html>
```
|
Amir, regarding to your answer, I think that opening window inside javascript function from **select** event can be blocked by PopupBlocker
pinghsien422 , your server side should return Json and not complete html , if you must return complete html, make the following changes:
1.Remove the clientSelect function
2.No 'a' tag is needed in renderData function
```
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append( item.label )
.appendTo(ul);
};
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
Okay, jquery's event takes precedence over your select event - no matter what you do, you can't stop anything there. But you can proxify menuselect event and then decide if it should be invoked ([jsfiddle](http://jsfiddle.net/ev8dnxrh/2/)).
```
var ac = $("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: document.body,
source: availableTags,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete");
ac._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<div>"+item.label+"<a class='link' href='http://test'>(http://test)</a></div>")
.appendTo(ul);
};
var ms = $._data(ac.menu.element.get(0), 'events').menuselect[0].handler;
ac.menu.element.off("menuselect");
ac.menu.element.on("menuselect", function (ev) {
if($(ev.originalEvent.target).hasClass("link"))
return;
ms.apply(this,arguments);
});
```
|
Try to do `even.stopImmediatePropagation` in `onclick` binding to link. Page is opening and select handler not executed.
```
var li = $("<li></li>")
.data("item.autocomplete", item)
.append('<a class="ac-item-a" href="http://www.nba.com">' + item.label + '</a>')
.appendTo(ul);
li.find('a').bind('click', function(event){ event.stopImmediatePropagation() });
return li;
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
Have you thought about putting a conditional in your click handler to **not** `preventDefault` when it is that link? If you test if the element should function as normal then you can `return` early before the `preventDefault` and then the link should function as normal.
Here is an example ([JSBin](http://output.jsbin.com/qulucu/)):
```js
function clickHandler(e) {
// If the target element has the class `test-clickable` then the
// function will return early, before `preventDefault`.
if (this.className.indexOf('test-clickable') !== -1) {
return;
}
alert('That link is not clickable because of `preventDefault`');
e.preventDefault();
}
$('a').click(clickHandler);
```
```css
a {
display: block;
}
a:after {
content: ' [class=' attr(class)']';
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class='test-clickable' href='http://www.google.com' target='_blank'>Link</a>
<a class='test-not-clickable' href='http://www.google.com' target='_blank'>Link</a>
</body>
</html>
```
|
Try to do `even.stopImmediatePropagation` in `onclick` binding to link. Page is opening and select handler not executed.
```
var li = $("<li></li>")
.data("item.autocomplete", item)
.append('<a class="ac-item-a" href="http://www.nba.com">' + item.label + '</a>')
.appendTo(ul);
li.find('a').bind('click', function(event){ event.stopImmediatePropagation() });
return li;
```
|
30,727,084 |
I managed to add a link to the right of the jQuery autocomplete items, using the following code:
```
function onClientSelect(event, ui) {
// My handling code goes here
event.preventDefault();
}
$("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: $(this).parent(),
source: '/filter_client/',
select: onClientSelect,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
```
My server returns element label in this format:
```
<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>
```
What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. However, currently left-clicking on the link also executes `onClientSelect`. The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'.
I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. Does anyone have any idea how to fix this?
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30727084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041510/"
] |
Have you thought about putting a conditional in your click handler to **not** `preventDefault` when it is that link? If you test if the element should function as normal then you can `return` early before the `preventDefault` and then the link should function as normal.
Here is an example ([JSBin](http://output.jsbin.com/qulucu/)):
```js
function clickHandler(e) {
// If the target element has the class `test-clickable` then the
// function will return early, before `preventDefault`.
if (this.className.indexOf('test-clickable') !== -1) {
return;
}
alert('That link is not clickable because of `preventDefault`');
e.preventDefault();
}
$('a').click(clickHandler);
```
```css
a {
display: block;
}
a:after {
content: ' [class=' attr(class)']';
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class='test-clickable' href='http://www.google.com' target='_blank'>Link</a>
<a class='test-not-clickable' href='http://www.google.com' target='_blank'>Link</a>
</body>
</html>
```
|
Okay, jquery's event takes precedence over your select event - no matter what you do, you can't stop anything there. But you can proxify menuselect event and then decide if it should be invoked ([jsfiddle](http://jsfiddle.net/ev8dnxrh/2/)).
```
var ac = $("#mypage input[name='client']").autocomplete({
minLength: 1,
appendTo: document.body,
source: availableTags,
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete");
ac._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<div>"+item.label+"<a class='link' href='http://test'>(http://test)</a></div>")
.appendTo(ul);
};
var ms = $._data(ac.menu.element.get(0), 'events').menuselect[0].handler;
ac.menu.element.off("menuselect");
ac.menu.element.on("menuselect", function (ev) {
if($(ev.originalEvent.target).hasClass("link"))
return;
ms.apply(this,arguments);
});
```
|
27,628,390 |
I am working on an Android application in which I have two concentric circles with the text at center. I have used drawable for both circles. I want to rotate both circle in counter clockwise to each other, i.e. one in clockwise and other in anti clockwise direction.
My code is given below for anim folders along activity code and snap for explanation.

progress\_left.xml
```
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="360" />
```
progress\_right.xml
```
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="0" />
```
My Activity Layout
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/red_theme"
android:orientation="vertical" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="28dp"
android:text="Start" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="67dp"
android:text="Stop" />
<RelativeLayout
android:id="@+id/main_imageLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/halfcircle"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="@+id/main_imageRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="MUry"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
</RelativeLayout>
<TextView
android:id="@+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Beige"
android:layout_above="@+id/btnStop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:textSize="100sp" />
</RelativeLayout>
```
My code at activity
```
Animation animRight = AnimationUtils.loadAnimation(this,
R.anim.progress_right);
animRight.setDuration(1000);
mImageRight.startAnimation(animRight);
Animation animLeft = AnimationUtils.loadAnimation(this,
R.anim.progress_left);
animLeft.setDuration(1000);
mLLLeft.startAnimation(animLeft);
```
|
2014/12/23
|
[
"https://Stackoverflow.com/questions/27628390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185295/"
] |
I'm not sure if it will work, but just try to set `android:toDegrees="-360"` in progress\_right.xml.
|
Just add one ImageView to your xml and remove Relative layout movement. Your text is moving because you have put your relative layout to the animation and your text is inside the layout.Updated xml code is given below:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/red_theme"
android:orientation="vertical" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="28dp"
android:text="Start" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="67dp"
android:text="Stop" />
<RelativeLayout
android:id="@+id/main_imageLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/halfcircle"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="@+id/main_imageLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<ImageView
android:id="@+id/main_imageRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="MUry"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
</RelativeLayout>
<TextView
android:id="@+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Beige"
android:layout_above="@+id/btnStop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:textSize="100sp" />
</RelativeLayout>
```
|
27,628,390 |
I am working on an Android application in which I have two concentric circles with the text at center. I have used drawable for both circles. I want to rotate both circle in counter clockwise to each other, i.e. one in clockwise and other in anti clockwise direction.
My code is given below for anim folders along activity code and snap for explanation.

progress\_left.xml
```
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="360" />
```
progress\_right.xml
```
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="0" />
```
My Activity Layout
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/red_theme"
android:orientation="vertical" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="28dp"
android:text="Start" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="67dp"
android:text="Stop" />
<RelativeLayout
android:id="@+id/main_imageLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/halfcircle"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="@+id/main_imageRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="MUry"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
</RelativeLayout>
<TextView
android:id="@+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Beige"
android:layout_above="@+id/btnStop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:textSize="100sp" />
</RelativeLayout>
```
My code at activity
```
Animation animRight = AnimationUtils.loadAnimation(this,
R.anim.progress_right);
animRight.setDuration(1000);
mImageRight.startAnimation(animRight);
Animation animLeft = AnimationUtils.loadAnimation(this,
R.anim.progress_left);
animLeft.setDuration(1000);
mLLLeft.startAnimation(animLeft);
```
|
2014/12/23
|
[
"https://Stackoverflow.com/questions/27628390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185295/"
] |
Just change your relative layout with Image view and check the following updated code:
```
private ImageView mImageLeft, mImageRight, mImageProfile;
private ImageView mLLLeft;
mLLLeft = (ImageView) findViewById(R.id.main_imageLeft1);
mImageRight = (ImageView) findViewById(R.id.main_imageRight);
Animation animRight = AnimationUtils.loadAnimation(this,
R.anim.progress_right);
animRight.setDuration(1000);
mImageRight.startAnimation(animRight);
Animation animLeft = AnimationUtils.loadAnimation(this,R.anim.progress_left);
animLeft.setDuration(1000);
mLLLeft.startAnimation(animLeft);
```
|
I'm not sure if it will work, but just try to set `android:toDegrees="-360"` in progress\_right.xml.
|
27,628,390 |
I am working on an Android application in which I have two concentric circles with the text at center. I have used drawable for both circles. I want to rotate both circle in counter clockwise to each other, i.e. one in clockwise and other in anti clockwise direction.
My code is given below for anim folders along activity code and snap for explanation.

progress\_left.xml
```
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="360" />
```
progress\_right.xml
```
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="0" />
```
My Activity Layout
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/red_theme"
android:orientation="vertical" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="28dp"
android:text="Start" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="67dp"
android:text="Stop" />
<RelativeLayout
android:id="@+id/main_imageLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/halfcircle"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="@+id/main_imageRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="MUry"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
</RelativeLayout>
<TextView
android:id="@+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Beige"
android:layout_above="@+id/btnStop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:textSize="100sp" />
</RelativeLayout>
```
My code at activity
```
Animation animRight = AnimationUtils.loadAnimation(this,
R.anim.progress_right);
animRight.setDuration(1000);
mImageRight.startAnimation(animRight);
Animation animLeft = AnimationUtils.loadAnimation(this,
R.anim.progress_left);
animLeft.setDuration(1000);
mLLLeft.startAnimation(animLeft);
```
|
2014/12/23
|
[
"https://Stackoverflow.com/questions/27628390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185295/"
] |
Just change your relative layout with Image view and check the following updated code:
```
private ImageView mImageLeft, mImageRight, mImageProfile;
private ImageView mLLLeft;
mLLLeft = (ImageView) findViewById(R.id.main_imageLeft1);
mImageRight = (ImageView) findViewById(R.id.main_imageRight);
Animation animRight = AnimationUtils.loadAnimation(this,
R.anim.progress_right);
animRight.setDuration(1000);
mImageRight.startAnimation(animRight);
Animation animLeft = AnimationUtils.loadAnimation(this,R.anim.progress_left);
animLeft.setDuration(1000);
mLLLeft.startAnimation(animLeft);
```
|
Just add one ImageView to your xml and remove Relative layout movement. Your text is moving because you have put your relative layout to the animation and your text is inside the layout.Updated xml code is given below:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/red_theme"
android:orientation="vertical" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="28dp"
android:text="Start" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="67dp"
android:text="Stop" />
<RelativeLayout
android:id="@+id/main_imageLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/halfcircle"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="@+id/main_imageLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<ImageView
android:id="@+id/main_imageRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/halfcircle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="MUry"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
</RelativeLayout>
<TextView
android:id="@+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Beige"
android:layout_above="@+id/btnStop"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:textSize="100sp" />
</RelativeLayout>
```
|
60,595,620 |
try to use crossfold resampling and fit a random forest from the ranger package. The fit without resampling works but once I try a resample fit it fails with error below.
Consider following `df`
```
df<-structure(list(a = c(1379405931, 732812609, 18614430, 1961678341,
2362202769, 55687714, 72044715, 236503454, 61988734, 2524712675,
98081131, 1366513385, 48203585, 697397991, 28132854), b = structure(c(1L,
6L, 2L, 5L, 7L, 8L, 8L, 1L, 3L, 4L, 3L, 5L, 7L, 2L, 2L), .Label = c("CA",
"IA", "IL", "LA", "MA", "MN", "TX", "WI"), class = "factor"),
c = structure(c(2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
2L, 2L, 2L, 1L), .Label = c("R", "U"), class = "factor"),
d = structure(c(3L, 3L, 1L, 3L, 3L, 1L, 1L, 3L, 1L, 3L, 1L,
3L, 2L, 3L, 1L), .Label = c("CAH", "LTCH", "STH"), class = "factor"),
e = structure(c(3L, 2L, 3L, 3L, 1L, 3L, 3L, 3L, 2L, 4L, 2L,
2L, 3L, 3L, 3L), .Label = c("cancer", "general long term",
"psychiatric", "rehabilitation"), class = "factor")), row.names = c(NA,
-15L), class = c("tbl_df", "tbl", "data.frame"))
```
Following simple fit works without issues
```
library(tidymodels)
library(ranger)
rf_spec <- rand_forest(mode = 'regression') %>%
set_engine('ranger')
rf_spec %>%
fit(a ~. , data = df)
```
But as soon as I want to run the cross validation via
```
rf_folds <- vfold_cv(df, strata = c)
fit_resamples(a ~ . ,
rf_spec,
rf_folds)
```
Following error
>
> model: Error in parse.formula(formula, data, env = parent.frame()): Error: Illegal column names in formula interface. Fix column names or use alternative interface in ranger.
>
>
>
|
2020/03/09
|
[
"https://Stackoverflow.com/questions/60595620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6617454/"
] |
The commenter above is correct that the source of the issue here is the spaces in the factor column. The functions for resampling and the functions for just plain old fitting currently handle that differently, and we are actively looking into how to solve this problem for users. Thank you for your patience!
In the meantime, I would recommend setting up a simple [`workflow()`](https://tidymodels.github.io/workflows/) plus a [`recipe()`](https://tidymodels.github.io/recipes/), which together will handle all the necessary dummy variable munging for you.
```r
library(tidymodels)
rf_spec <- rand_forest(mode = "regression") %>%
set_engine("ranger")
rf_wf <- workflow() %>%
add_model(rf_spec) %>%
add_recipe(recipe(a ~ ., data = df))
fit(rf_wf, data = df)
#> ββ Workflow [trained] βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#> Preprocessor: Recipe
#> Model: rand_forest()
#>
#> ββ Preprocessor βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#> 0 Recipe Steps
#>
#> ββ Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#> Ranger result
#>
#> Call:
#> ranger::ranger(formula = formula, data = data, num.threads = 1, verbose = FALSE, seed = sample.int(10^5, 1))
#>
#> Type: Regression
#> Number of trees: 500
#> Sample size: 15
#> Number of independent variables: 4
#> Mtry: 2
#> Target node size: 5
#> Variable importance mode: none
#> Splitrule: variance
#> OOB prediction error (MSE): 4.7042e+17
#> R squared (OOB): 0.4341146
rf_folds <- vfold_cv(df, strata = c)
fit_resamples(rf_wf,
rf_folds)
#> # 10-fold cross-validation using stratification
#> # A tibble: 9 x 4
#> splits id .metrics .notes
#> <list> <chr> <list> <list>
#> 1 <split [13/2]> Fold1 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 2 <split [13/2]> Fold2 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 3 <split [13/2]> Fold3 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 4 <split [13/2]> Fold4 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 5 <split [13/2]> Fold5 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 6 <split [13/2]> Fold6 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 7 <split [14/1]> Fold7 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 8 <split [14/1]> Fold8 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 9 <split [14/1]> Fold9 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
```
Created on 2020-03-20 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
|
Julia bet me to it so she gets the karma. I had the same answer (I do what she does but slower):
This is *kind of* a bug and we've been working to the best way to make it not error. It's complicated. Let me explain.
`ranger` is one of a few R packages whose formula method does not create dummy variables (sensibly since it does not need them).
The infrastructure in `tune` uses the `workflows` package to process the formula then hand the resulting data over to `ranger`. *By default*, workflows does create dummy variables and, since some of your factor levels are not valid R column names (e.g. `"general long term"`), `ranger()` kicks an error.
(I know that you didn't use a workflow, but that is what happens under the hood).
We are working on the best thing to do here since most users don't know that many tree-based model packages do not produce dummy variables. To make it more complex, `parsnip` doesn't use workflows (yet) and did not have given you an error.
**Solution for now**
Use a simple recipe instead of a formula:
```r
library(tidymodels)
#> ββ Attaching packages βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ tidymodels 0.1.0 ββ
#> β broom 0.5.4 β recipes 0.1.10
#> β dials 0.0.4 β rsample 0.0.5
#> β dplyr 0.8.5 β tibble 2.1.3
#> β ggplot2 3.3.0 β tune 0.0.1
#> β infer 0.5.1 β workflows 0.1.0
#> β parsnip 0.0.5 β yardstick 0.0.5
#> β purrr 0.3.3
#> ββ Conflicts ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ tidymodels_conflicts() ββ
#> x purrr::discard() masks scales::discard()
#> x dplyr::filter() masks stats::filter()
#> x dplyr::lag() masks stats::lag()
#> x ggplot2::margin() masks dials::margin()
#> x recipes::step() masks stats::step()
df<-structure(list(a = c(1379405931, 732812609, 18614430, 1961678341,
2362202769, 55687714, 72044715, 236503454, 61988734, 2524712675,
98081131, 1366513385, 48203585, 697397991, 28132854), b = structure(c(1L,
6L, 2L, 5L, 7L, 8L, 8L, 1L, 3L, 4L, 3L, 5L, 7L, 2L, 2L), .Label = c("CA",
"IA", "IL", "LA", "MA", "MN", "TX", "WI"), class = "factor"),
c = structure(c(2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
2L, 2L, 2L, 1L), .Label = c("R", "U"), class = "factor"),
d = structure(c(3L, 3L, 1L, 3L, 3L, 1L, 1L, 3L, 1L, 3L, 1L,
3L, 2L, 3L, 1L), .Label = c("CAH", "LTCH", "STH"), class = "factor"),
e = structure(c(3L, 2L, 3L, 3L, 1L, 3L, 3L, 3L, 2L, 4L, 2L,
2L, 3L, 3L, 3L), .Label = c("cancer", "general long term",
"psychiatric", "rehabilitation"), class = "factor")), row.names = c(NA,
-15L), class = c("tbl_df", "tbl", "data.frame"))
library(tidymodels)
library(ranger)
rf_spec <- rand_forest(mode = 'regression') %>%
set_engine('ranger')
rf_folds <- vfold_cv(df, strata = c)
fit_resamples(recipe(a ~ ., data = df), rf_spec, rf_folds)
#> # 10-fold cross-validation using stratification
#> # A tibble: 9 x 4
#> splits id .metrics .notes
#> * <list> <chr> <list> <list>
#> 1 <split [13/2]> Fold1 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 2 <split [13/2]> Fold2 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 3 <split [13/2]> Fold3 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 4 <split [13/2]> Fold4 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 5 <split [13/2]> Fold5 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 6 <split [13/2]> Fold6 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 7 <split [14/1]> Fold7 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 8 <split [14/1]> Fold8 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
#> 9 <split [14/1]> Fold9 <tibble [2 Γ 3]> <tibble [0 Γ 1]>
# FYI `tune` 0.0.2 will require a different argument order:
# rf_spec %>% fit_resamples(recipe(a ~ ., data = df), rf_folds)
```
Created on 2020-03-20 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
|
7,779,994 |
I am having trouble calling a specific method from another class in my app. I have a class, Rest, that determines various settings, etc. about a particular request received by the server and creates a Rest object with the properties of the request. The Rest class may then call any given method in a separate class to fulfill the request. The problem is that the other class needs to call methods in the Rest class to send a response, etc.
How can this be possible? Here's a blueprint of my current setup:
```
class Rest {
public $controller = null;
public $method = null;
public $accept = null;
public function __construct() {
// Determine the type of request, etc. and set properties
$this->controller = "Users";
$this->method = "index";
$this->accept = "json";
// Load the requested controller
$obj = new $this->controller;
call_user_func(array($obj, $this->method));
}
public function send_response($response) {
if ( $this->accept == "json" ) {
echo json_encode($response);
}
}
}
```
The controller class:
```
class Users {
public static function index() {
// Do stuff
Rest::send_response($response_data);
}
}
```
This results in receiving a fatal error in the send\_response method: Using $this when not in object context
What's the better way to do this without sacrificing the current workflow.
|
2011/10/15
|
[
"https://Stackoverflow.com/questions/7779994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/604664/"
] |
You need to create an instance first.
```
class Users {
public static function index() {
// Do stuff
$rest = new Rest();
$rest->send_response($response_data);
}
}
```
|
You don't call send\_response() in an object context, as the error message says.
Either you create an instance and call everything on that instance (IMHO the right way), or you do everything statically, including the constructor (you may want to have a intialization method instead) and the properties.
|
7,779,994 |
I am having trouble calling a specific method from another class in my app. I have a class, Rest, that determines various settings, etc. about a particular request received by the server and creates a Rest object with the properties of the request. The Rest class may then call any given method in a separate class to fulfill the request. The problem is that the other class needs to call methods in the Rest class to send a response, etc.
How can this be possible? Here's a blueprint of my current setup:
```
class Rest {
public $controller = null;
public $method = null;
public $accept = null;
public function __construct() {
// Determine the type of request, etc. and set properties
$this->controller = "Users";
$this->method = "index";
$this->accept = "json";
// Load the requested controller
$obj = new $this->controller;
call_user_func(array($obj, $this->method));
}
public function send_response($response) {
if ( $this->accept == "json" ) {
echo json_encode($response);
}
}
}
```
The controller class:
```
class Users {
public static function index() {
// Do stuff
Rest::send_response($response_data);
}
}
```
This results in receiving a fatal error in the send\_response method: Using $this when not in object context
What's the better way to do this without sacrificing the current workflow.
|
2011/10/15
|
[
"https://Stackoverflow.com/questions/7779994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/604664/"
] |
You can create a `Rest` instance in `User`:
```
public static function index() {
// Do stuff
$rest = new Rest;
$rest::send_response($response_data);
}
```
You could also change `Rest` to be a singleton and call an instance of it, but beware of this antipattern.
|
You don't call send\_response() in an object context, as the error message says.
Either you create an instance and call everything on that instance (IMHO the right way), or you do everything statically, including the constructor (you may want to have a intialization method instead) and the properties.
|
7,779,994 |
I am having trouble calling a specific method from another class in my app. I have a class, Rest, that determines various settings, etc. about a particular request received by the server and creates a Rest object with the properties of the request. The Rest class may then call any given method in a separate class to fulfill the request. The problem is that the other class needs to call methods in the Rest class to send a response, etc.
How can this be possible? Here's a blueprint of my current setup:
```
class Rest {
public $controller = null;
public $method = null;
public $accept = null;
public function __construct() {
// Determine the type of request, etc. and set properties
$this->controller = "Users";
$this->method = "index";
$this->accept = "json";
// Load the requested controller
$obj = new $this->controller;
call_user_func(array($obj, $this->method));
}
public function send_response($response) {
if ( $this->accept == "json" ) {
echo json_encode($response);
}
}
}
```
The controller class:
```
class Users {
public static function index() {
// Do stuff
Rest::send_response($response_data);
}
}
```
This results in receiving a fatal error in the send\_response method: Using $this when not in object context
What's the better way to do this without sacrificing the current workflow.
|
2011/10/15
|
[
"https://Stackoverflow.com/questions/7779994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/604664/"
] |
You can create a `Rest` instance in `User`:
```
public static function index() {
// Do stuff
$rest = new Rest;
$rest::send_response($response_data);
}
```
You could also change `Rest` to be a singleton and call an instance of it, but beware of this antipattern.
|
You need to create an instance first.
```
class Users {
public static function index() {
// Do stuff
$rest = new Rest();
$rest->send_response($response_data);
}
}
```
|
32,918,178 |
I am trying to print the contents of an array. For example I have defined an int array of size 10. But the user entered only 8 numbers. So the last two positions in an array have an value of zero. When I am printing the array I get all ten positions. Is it possible to print only up till the user entered.Also the user decides how many to enter so I cannot hard code the position for printing the array. Thanks.
|
2015/10/03
|
[
"https://Stackoverflow.com/questions/32918178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5390306/"
] |
I don't understand your question very well, but I would start with this function first, so you can split your string:
>
> The C library function char \*strtok(char \*str, const char \*delim)
> breaks string str into a series of tokens using the delimiter delim.
>
>
>
```
char *strtok(char *str, const char *delim)
```
>
> Parameters str -- The contents of this string are modified and broken
> into smaller strings (tokens).
>
>
> delim -- This is the C string containing the delimiters. These may
> vary from one call to another.
>
>
>
[source](http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm)
|
I would use `strtok` at the beginning. I know this is a lot of code, but I wrote it showing you how to correctly manage dynamic allocated memory and how to correctly use functions like `strtok` and `realloc`, because you see a lot of wrong usage of these functions.
Of course you can make it better with more performance, but like I said, I wanted to show you more how to use dynamic allocated memory.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *copy_str(const char *str)
{
if(str == NULL)
return NULL;
char *ptr = malloc(strlen(str) + 1);
if(ptr)
{
strcpy(ptr, str);
return ptr;
}
return NULL;
}
char **add_new_word(char **words, char *newword)
{
int len;
for(len=0; words && words[len]; ++len);
char **tmp = realloc(words, (sizeof *words)*(len + 2));
if(tmp == NULL)
return NULL;
tmp[len] = newword;
tmp[len+1] = NULL;
return tmp;
}
char **get_words(const char *sentence)
{
char **strings = NULL, **tmp_strings;
char *tmp_sentence = copy_str(sentence);
char *tmp_sentence_orig = tmp_sentence;
if(tmp_sentence == NULL)
return NULL;
char *tmp_word = copy_str(strtok(tmp_sentence, " "));
if(tmp_word == NULL)
{
free(tmp_sentence_orig);
return NULL;
}
tmp_strings = add_new_word(strings, tmp_word);
if(tmp_strings == NULL)
{
free(tmp_sentence_orig);
return NULL;
}
strings = tmp_strings;
while(tmp_word = copy_str(strtok(NULL, " ")))
{
tmp_strings = add_new_word(strings, tmp_word);
if(tmp_strings == NULL)
{
free(tmp_word);
free(tmp_sentence_orig);
return strings; // got all words we could
}
strings = tmp_strings;
}
free(tmp_sentence_orig);
return strings;
}
void free_words(char **words)
{
if(words == NULL)
return;
int i;
for(i=0; words[i]; ++i)
free(words[i]);
free(words);
}
int main(void)
{
char **words = get_words("When in the course");
if(words == NULL)
return 1;
int i;
for(i = 0; words[i]; ++i)
printf("word #%d: '%s'\n", i+1, words[i]);
free_words(words);
return 0;
}
```
as you can see from `valgrind`:
```
==31202== Memcheck, a memory error detector
==31202== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==31202== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==31202== Command: ./a
==31202==
word #1: 'When'
word #2: 'in'
word #3: 'the'
word #4: 'course'
==31202==
==31202== HEAP SUMMARY:
==31202== in use at exit: 0 bytes in 0 blocks
==31202== total heap usage: 9 allocs, 9 frees, 150 bytes allocated
==31202==
==31202== All heap blocks were freed -- no leaks are possible
==31202==
==31202== For counts of detected and suppressed errors, rerun with: -v
==31202== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.