qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
148,103 | [](https://i.stack.imgur.com/VlYZM.png)
I have a fictional world, consisting of a federation of 17 provinces (in blue on the map extract). Currently, it is in the late 1920's. The Dzevogurski and Quidthovitse provinces are on the brink of war. Historically, the province of Ladies Beach was part of Dzevogurski but split away peacefully several years ago for admisitrative reasons. The mountain range running NW-SE formed a natural boundry.
In the region concerned, there are two major railway lines involved in trans-continental transport. The Fyonas River - Kandice Beach line runs through two districts of Dzevogurski. To Quidthovice, this is a major point of 'pain': Their tracks run through their 'rivals' territory.
Also, in the 1890's Quidthovice managed to convince the Kimberley-district government to deny the builders of the Vaenesston-Tannith Beach line access to the 'easy' pass between Kimberley and St. Marias Stone, where the Quidthovice-based railroad company had its tracks laid already. To avoid conflict, the Dzevogurski-Ladies Beach government (sitting in Vaenesston) let this slide.
Now, Quidthovice is trying to 'persuade' the two districts of Kimberley and Murrayville (in red/pink) to join their province. Their current 'parent' (the Dzevogurski province) naturally resists. This time, the Dzevogurski government will fight.
If Kimberley and Murrayville do flip, this will [exclave](https://en.wikipedia.org/wiki/Enclave_and_exclave) Yadzor.
The districts of Kimberley, Murrayville, Yadzor are mainly cattle ranches, with some fruit (in the mountains) and dairy production. The population is being influeced by both sides.
The question which I'm asking is this: Can two provinces in a federation have a war between themselves, with everybody else staying neutral?
Can you still call it a 'civil war'?
I know that opinion-based questions are frowned upon in this forum, hence this is an optional question: How would this conflict be resolved? | 2019/05/31 | [
"https://worldbuilding.stackexchange.com/questions/148103",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6500/"
] | **It depends**
I would say that if the question is purely about semantics, we do not have an internationally accepted definition of civil war. I think that the conflict between two provinces in a federation is not a civil war. Presumably, there is some sort of a federal government, and it's not taking part in it in the situation you describe. Nor is either of the two sides trying to overthrow the federal government.
It can be called 'civil war' in quotes later, if the conflict was especially long or bloody, and the description may stick. Or it may be treated as a big [range war](https://en.wikipedia.org/wiki/Range_war).
Most of other parts of your question depend on the strength of the federal government, the acceptable policies in your world. Will other provinces join in the war - depends on what they stand to win by participating and whether that's an acceptable part of their political culture. They may be content to solve some conflicts by proxy, supplying the combating provinces, but not risking their troops. Or they may treat it as a humanitarian catastrophe and declare strict policy of non-intervention in order to reap some political capital from it.
As for the ways to solve it - again, it severely depends on the structure of the federation and the strength of the federal government. It may be a literal intervention by federal troops that stops the silliness. Or, maybe, federal government is severely decentralized and has a huge latency - all other provinces need to summon a temporary Council in order to figure out what to do next. It also depends on the international conditions - what are the neighbors of your country like and what will they do when the shooting starts? | There are plenty of historical examples to confirm that such conflicts can exist. Provinces of the [Ottoman Empire](https://en.m.wikipedia.org/wiki/Ottoman_Empire) frequently feuded with each other. And in the US there was the third [Pennamite War](https://en.m.wikipedia.org/wiki/Pennamite%E2%80%93Yankee_War) between Pennsylvania and Connecticut (the first two occurred before the US existed). |
148,103 | [](https://i.stack.imgur.com/VlYZM.png)
I have a fictional world, consisting of a federation of 17 provinces (in blue on the map extract). Currently, it is in the late 1920's. The Dzevogurski and Quidthovitse provinces are on the brink of war. Historically, the province of Ladies Beach was part of Dzevogurski but split away peacefully several years ago for admisitrative reasons. The mountain range running NW-SE formed a natural boundry.
In the region concerned, there are two major railway lines involved in trans-continental transport. The Fyonas River - Kandice Beach line runs through two districts of Dzevogurski. To Quidthovice, this is a major point of 'pain': Their tracks run through their 'rivals' territory.
Also, in the 1890's Quidthovice managed to convince the Kimberley-district government to deny the builders of the Vaenesston-Tannith Beach line access to the 'easy' pass between Kimberley and St. Marias Stone, where the Quidthovice-based railroad company had its tracks laid already. To avoid conflict, the Dzevogurski-Ladies Beach government (sitting in Vaenesston) let this slide.
Now, Quidthovice is trying to 'persuade' the two districts of Kimberley and Murrayville (in red/pink) to join their province. Their current 'parent' (the Dzevogurski province) naturally resists. This time, the Dzevogurski government will fight.
If Kimberley and Murrayville do flip, this will [exclave](https://en.wikipedia.org/wiki/Enclave_and_exclave) Yadzor.
The districts of Kimberley, Murrayville, Yadzor are mainly cattle ranches, with some fruit (in the mountains) and dairy production. The population is being influeced by both sides.
The question which I'm asking is this: Can two provinces in a federation have a war between themselves, with everybody else staying neutral?
Can you still call it a 'civil war'?
I know that opinion-based questions are frowned upon in this forum, hence this is an optional question: How would this conflict be resolved? | 2019/05/31 | [
"https://worldbuilding.stackexchange.com/questions/148103",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6500/"
] | There are plenty of historical examples to confirm that such conflicts can exist. Provinces of the [Ottoman Empire](https://en.m.wikipedia.org/wiki/Ottoman_Empire) frequently feuded with each other. And in the US there was the third [Pennamite War](https://en.m.wikipedia.org/wiki/Pennamite%E2%80%93Yankee_War) between Pennsylvania and Connecticut (the first two occurred before the US existed). | Yes, it is not only possible to have neutral parties in internal conflicts, it has happened historically.
This would probably classified as a [Low Intensity Conflicts](https://en.wikipedia.org/wiki/Low_intensity_conflict) due to the localized nature and limited scale of fighting. While "Low Intensity" might not seem to be "Not really a war", low intensity refers to the infrequency of fighting. Low intensity actually conflicts have very higher casualty rates, due to the use of poorly trained soldiers, guerrilla tactics, and terrorism.
Some examples of civil low intensity conflicts with neutral parties:
[The Troubles](https://en.wikipedia.org/wiki/The_Troubles#Overview) - 30 year conflict between Irish nationalists and the United Kingdom over Northern Ireland. While the number of fighters was relatively small, many civilians were killed, even though most citizens of Northern Ireland remained neutral. (Give Ireland back to the Irish)
[Sudanese Civil Wars](https://en.wikipedia.org/wiki/Sudanese_Civil_War) - For most of these wars the Sudanese government participated in "Annual Dry Season Offensives" against the South Sudanese. The rough climate and poor transportation infrastructure of Sudan made it very difficult to hold territory during parts of the year. So almost every year since 1955 The Sudanese Army has invaded the south during the dry season, attempting to take as much land as possible. However, due to the logistical difficulty of holding the land The Sudanese Army retreats every rainy season.
[Myanmar Civil War](https://en.wikipedia.org/wiki/Internal_conflict_in_Myanmar) - Since around 1948, for very complex historical reasons, Myanmar has been in constant civil war. The conflict is the world's longest ongoing civil war and shows no signs of stopping. None of the many sides have made significant progress due to not being able to capture highly defensible terrain (mostly mountains and jungle) this has lead to all sides transforming into self-ruling militaristic states |
148,103 | [](https://i.stack.imgur.com/VlYZM.png)
I have a fictional world, consisting of a federation of 17 provinces (in blue on the map extract). Currently, it is in the late 1920's. The Dzevogurski and Quidthovitse provinces are on the brink of war. Historically, the province of Ladies Beach was part of Dzevogurski but split away peacefully several years ago for admisitrative reasons. The mountain range running NW-SE formed a natural boundry.
In the region concerned, there are two major railway lines involved in trans-continental transport. The Fyonas River - Kandice Beach line runs through two districts of Dzevogurski. To Quidthovice, this is a major point of 'pain': Their tracks run through their 'rivals' territory.
Also, in the 1890's Quidthovice managed to convince the Kimberley-district government to deny the builders of the Vaenesston-Tannith Beach line access to the 'easy' pass between Kimberley and St. Marias Stone, where the Quidthovice-based railroad company had its tracks laid already. To avoid conflict, the Dzevogurski-Ladies Beach government (sitting in Vaenesston) let this slide.
Now, Quidthovice is trying to 'persuade' the two districts of Kimberley and Murrayville (in red/pink) to join their province. Their current 'parent' (the Dzevogurski province) naturally resists. This time, the Dzevogurski government will fight.
If Kimberley and Murrayville do flip, this will [exclave](https://en.wikipedia.org/wiki/Enclave_and_exclave) Yadzor.
The districts of Kimberley, Murrayville, Yadzor are mainly cattle ranches, with some fruit (in the mountains) and dairy production. The population is being influeced by both sides.
The question which I'm asking is this: Can two provinces in a federation have a war between themselves, with everybody else staying neutral?
Can you still call it a 'civil war'?
I know that opinion-based questions are frowned upon in this forum, hence this is an optional question: How would this conflict be resolved? | 2019/05/31 | [
"https://worldbuilding.stackexchange.com/questions/148103",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6500/"
] | **It depends**
I would say that if the question is purely about semantics, we do not have an internationally accepted definition of civil war. I think that the conflict between two provinces in a federation is not a civil war. Presumably, there is some sort of a federal government, and it's not taking part in it in the situation you describe. Nor is either of the two sides trying to overthrow the federal government.
It can be called 'civil war' in quotes later, if the conflict was especially long or bloody, and the description may stick. Or it may be treated as a big [range war](https://en.wikipedia.org/wiki/Range_war).
Most of other parts of your question depend on the strength of the federal government, the acceptable policies in your world. Will other provinces join in the war - depends on what they stand to win by participating and whether that's an acceptable part of their political culture. They may be content to solve some conflicts by proxy, supplying the combating provinces, but not risking their troops. Or they may treat it as a humanitarian catastrophe and declare strict policy of non-intervention in order to reap some political capital from it.
As for the ways to solve it - again, it severely depends on the structure of the federation and the strength of the federal government. It may be a literal intervention by federal troops that stops the silliness. Or, maybe, federal government is severely decentralized and has a huge latency - all other provinces need to summon a temporary Council in order to figure out what to do next. It also depends on the international conditions - what are the neighbors of your country like and what will they do when the shooting starts? | Yes, it is not only possible to have neutral parties in internal conflicts, it has happened historically.
This would probably classified as a [Low Intensity Conflicts](https://en.wikipedia.org/wiki/Low_intensity_conflict) due to the localized nature and limited scale of fighting. While "Low Intensity" might not seem to be "Not really a war", low intensity refers to the infrequency of fighting. Low intensity actually conflicts have very higher casualty rates, due to the use of poorly trained soldiers, guerrilla tactics, and terrorism.
Some examples of civil low intensity conflicts with neutral parties:
[The Troubles](https://en.wikipedia.org/wiki/The_Troubles#Overview) - 30 year conflict between Irish nationalists and the United Kingdom over Northern Ireland. While the number of fighters was relatively small, many civilians were killed, even though most citizens of Northern Ireland remained neutral. (Give Ireland back to the Irish)
[Sudanese Civil Wars](https://en.wikipedia.org/wiki/Sudanese_Civil_War) - For most of these wars the Sudanese government participated in "Annual Dry Season Offensives" against the South Sudanese. The rough climate and poor transportation infrastructure of Sudan made it very difficult to hold territory during parts of the year. So almost every year since 1955 The Sudanese Army has invaded the south during the dry season, attempting to take as much land as possible. However, due to the logistical difficulty of holding the land The Sudanese Army retreats every rainy season.
[Myanmar Civil War](https://en.wikipedia.org/wiki/Internal_conflict_in_Myanmar) - Since around 1948, for very complex historical reasons, Myanmar has been in constant civil war. The conflict is the world's longest ongoing civil war and shows no signs of stopping. None of the many sides have made significant progress due to not being able to capture highly defensible terrain (mostly mountains and jungle) this has lead to all sides transforming into self-ruling militaristic states |
69,850,831 | I have a dataframe which looks something like the following (for example):
```
set.seed(42) ## for sake of reproducibility
n <- 6
dat <- data.frame(date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
category=rep(LETTERS[1:2], n/2),
daily_count=sample(18:100, n, replace=TRUE)
)
dat
# date category daily_count
#1 2020-12-26 A 60
#2 2020-12-27 B 32
#3 2020-12-28 B 39
#4 2020-12-29 B 75
#5 2020-12-30 A 25
#6 2020-12-31 A 53
#7 2020-12-26 A 60
#8 2020-12-27 A 32
#9 2020-12-28 A 39
#10 2020-12-29 B 75
#11 2020-12-30 B 25
#12 2020-12-31 B 53
.
.
.
```
I am trying to create a boxplot with month and year on its X-Axis and it looks like this:
[](https://i.stack.imgur.com/kIInC.png)
I would like to create a vertical line on ***2013-08-23***. I am using the following code for this:
```
library(ggplot2)
ggplot(dat) +
geom_boxplot(aes(y=daily_count,
x=reorder(format(dat$date,'%b %y'),dat$date),
fill=dat$category)) +
xlab('Month & Year') + ylab('Count') + guides(fill=guide_legend(title="Category")) +
theme_bw()+
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10))+
geom_vline(xintercept = as.numeric(as.Date("2013-08-23")), linetype=1, colour="red")
```
Any guidance please? | 2021/11/05 | [
"https://Stackoverflow.com/questions/69850831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17033294/"
] | In this answer:
* I've created a much bigger sample
* I'm using `yearmonth` from `tsibble` for simplicity
* I've solved the issue with the vertical line
* I cleaned up a bit the use of labs for a cleaner code
```r
set.seed(42)
dates <- seq.Date(as.Date("2012-08-01"), as.Date("2014-08-30"), "day")
n <- length(dates)
dat <- data.frame(date = dates,
category = rep(LETTERS[1:2], n/2),
daily_count = sample(18:100, n, replace=TRUE))
library(ggplot2)
library(tsibble)
ggplot(dat) +
geom_boxplot(aes(y = daily_count,
x = yearmonth(date),
group = paste(yearmonth(date), category),
fill = category)) +
labs(x = 'Month & Year',
y = 'Count',
fill = "Category") +
theme_bw() +
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10)) +
geom_vline(xintercept = lubridate::ymd("2013-08-23"), linetype=1, colour="red", size = 2)
```

Created on 2021-11-05 by the [reprex package](https://reprex.tidyverse.org) (v2.0.0)
I set the vertical line thicker so to be seen.
---
Unfortunately the chart is difficult to visualize. Why don't you use ribbons instead?
With random data is horrible, but with yours you should see something meaningful.
```
library(ggplot2)
library(tsibble)
library(dplyr)
library(tidyr)
dat %>%
group_by(category, yearmonth = yearmonth(date)) %>%
summarise(q = list(quantile(daily_count))) %>%
unnest_wider(q, names_sep = "_") %>%
ggplot(aes(x = yearmonth, fill = category, colour = category)) +
geom_ribbon(aes(ymin = `q_0%`, ymax = `q_100%`), alpha = 0.2) +
geom_ribbon(aes(ymin = `q_25%`, ymax = `q_75%`), alpha = 0.2) +
geom_line(aes(y = `q_50%`)) +
labs(x = 'Month & Year',
y = 'Count',
colour = "Category",
fill = "Category") +
theme_bw() +
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10)) +
geom_vline(xintercept = lubridate::ymd("2013-08-23"), linetype=1, colour="red", size = 2)
```
[](https://i.stack.imgur.com/gBi9j.png) | I think there is no need to do any "expansion"... This in NOT my solution, but a modified solution by @dario. I think the problem was in aesthetics.
```
ggplot(dat, aes(y=daily_count,
x=date,
fill=category)) +
geom_boxplot() +
labs(x = 'Month & Year', ylab= 'Count', fill = "Category") +
theme_bw()+
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10))+
geom_vline(xintercept = as.Date("2020-12-28"), linetype=1, colour="red")
``` |
13,612,837 | I'm using boost::regex to parse some formatting string where '%' symbol is escape character. Because I do not have much experience with boost::regex, and with regex at all to be honest I do some trial and error. This code is some kind of prototype that I came up with.
```
std::string regex_string =
"(?:%d\\{(.*)\\})|" //this group will catch string for formatting time
"(?:%([hHmMsSqQtTlLcCxXmMnNpP]))|" //symbols that have some meaning
"(?:\\{(.*?)\\})|" //some other groups
"(?:%(.*?)\\s)|"
"(?:([^%]*))";
boost::regex regex;
boost::smatch match;
try
{
regex.assign(regex_string, boost::regex_constants::icase);
boost::sregex_iterator res(pattern.begin(), pattern.end(), regex);
//pattern in line above is string which I'm parsing
boost::sregex_iterator end;
for(; res != end; ++res)
{
match = *res;
output << match.get_last_closed_paren();
//I want to know if the thing that was just written to output is from group describing time string
output << "\n";
}
}
catch(boost::regex_error &e)
{
output<<"regex error\n";
}
```
And this works pretty good, on the output I have exactly what I want to catch. But I do not know from which group it is. I could do something like `match[index_of_time_group]!=""` but this is kind of fragile, and doesn't look too good. If I change `regex_string` index that was pointing on group catching string for formatting time could also change.
Is there a neat way to do this? Something like naming groups? I'll be grateful for any help. | 2012/11/28 | [
"https://Stackoverflow.com/questions/13612837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1788633/"
] | You can use [`boost::sub_match::matched`](http://www.boost.org/doc/libs/release/libs/regex/doc/html/boost_regex/ref/sub_match.html#boost_regex.sub_match.matched) bool member:
```
if(match[index_of_time_group].matched) process_it(match);
```
It is also possible to use named groups in regexp like: `(?<name_of_group>.*)`, and with this above line could be changed to:
```
if(match["name_of_group"].matched) process_it(match);
``` | Dynamically build `regex_string` from pairs of name/pattern, and return a name->index mapping as well as the regex. Then write some code that determines if the match comes from a given name.
If you are insane, you can do it at compile time (the mapping from tag to index that is). It isn't worth it. |
38,817 | In Windows Vista, whenever I open a folder, the selection of columns is nonsensical: album, date taken, etc., for folders that contain no music or pictures whatsoever. I can select the correct columns for a particular folder, but all the other folders are still wrong, even when I go in to Folder Options and click the button to set the current options to all folders of this type.
How can I tell Windows to use the current column selection for all folders, unless otherwise specified? | 2009/09/10 | [
"https://superuser.com/questions/38817",
"https://superuser.com",
"https://superuser.com/users/10624/"
] | eZine Article: [Setup a Default Folder View in Windows Vista](http://ezinearticles.com/?Solved---Setup-a-Default-Folder-View-in-Windows-Vista!&id=1465143) talks about some registry stuff along with the points in `Daniel`'s answer. Below is from this link
>
> One of the problems many people face once they have installed Vista is
> that their folder view will change every time they close and reopen a
> folder. This is annoying right?
>
>
> Well here is the solution:
>
>
> 1 Open the registry: Simply click on the start orb and type in "regedit" into the search field. A file called regedit.exe will show
> up at the top, double-click it!
>
>
> 2 Locate the following folders in the registry editor by clicking on the small black arrows to expand the folder structure:
>
>
> [HKEY\_CURRENT\_USERSoftwareClassesLocal
> SettingsSoftwareMicrosoftWindowsShellBags]
>
>
> [HKEY\_CURRENT\_USERSoftwareClassesLocal
> SettingsSoftwareMicrosoftWindowsShellBagMRU]
>
>
> 3 Right click on the folder "Bags" and click on delete, do the same for BagMRU. This is how you get rid of disturbing folder view entries.
> Don't worry we will now create a new one called "DefaultFolders".
>
>
> 4 Right click on the folder "Shell" that is the parent folder of the folders you just deleted.
>
>
> Click on "New" -> "Key". Name it "DefaultFolders".
>
>
> 5 Repeat 4. but for the folder we just created and name the new folder "Shell". That way you will create a subfolder "Shell" inside
> the folder "DefaultFolders".
>
>
> 6 Now we right-click on the folder "Shell" and create a new String: "New" -> "String Value".
>
>
> Give the string the name "FolderType".
>
>
> 7 Double-click it and type "Documents" into the value field.
>
>
> 8 Almost done, now all folders will have the same folder view as the "Documents" folder. Time to set your default folder view. To do that
> open up the explorer (Windows-key + E is the shortcut).
>
>
> Now locate C:UsersYour\_User\_NameDocuments, where C: is the partition
> on which you installed Windows obviously. Make sure to set your
> favorite folder view (mine is Details) there.
>
>
> Click on "Organize" -> "Folder and Search Options".
>
>
> Now go to the tab "View" and finally click on "Apply to Folders"!
>
>
>
I have used the steps from `Daniel`'s answer on Windows XP machines.
If they do not work on the Vista, try the eZine article.
Meanwhile, this Vista64 thread suggests Vista SP2 has solved this problem. | First you set the columns the way you want in one folder, then on the Tools menu (`Alt`+`t` if the menu is hidden by default), click Folder Options... and then go to the View tab, click Apply to Folders. After confirming, you will see that all your folders (at least of that type) have been changed.
PS. Thanks for asking; it reminded me that I needed to set this up. |
38,817 | In Windows Vista, whenever I open a folder, the selection of columns is nonsensical: album, date taken, etc., for folders that contain no music or pictures whatsoever. I can select the correct columns for a particular folder, but all the other folders are still wrong, even when I go in to Folder Options and click the button to set the current options to all folders of this type.
How can I tell Windows to use the current column selection for all folders, unless otherwise specified? | 2009/09/10 | [
"https://superuser.com/questions/38817",
"https://superuser.com",
"https://superuser.com/users/10624/"
] | First you set the columns the way you want in one folder, then on the Tools menu (`Alt`+`t` if the menu is hidden by default), click Folder Options... and then go to the View tab, click Apply to Folders. After confirming, you will see that all your folders (at least of that type) have been changed.
PS. Thanks for asking; it reminded me that I needed to set this up. | See this article from annoyances.org : ["Default Folder Template Patch"](http://www.annoyances.org/exec/show/choosetemplate), which says:
>
> Windows Vista has a bug that prevents
> it from choosing the correct view for
> a folder based on its contents, which
> is why you may see thumbnails when
> they're not appropriate, and no
> thumbnails when they're needed. The
> following patch stops Vista from
> trying to guess how to display a
> folder, instead forcing it to use the
> template of your choice.
>
>
> |
38,817 | In Windows Vista, whenever I open a folder, the selection of columns is nonsensical: album, date taken, etc., for folders that contain no music or pictures whatsoever. I can select the correct columns for a particular folder, but all the other folders are still wrong, even when I go in to Folder Options and click the button to set the current options to all folders of this type.
How can I tell Windows to use the current column selection for all folders, unless otherwise specified? | 2009/09/10 | [
"https://superuser.com/questions/38817",
"https://superuser.com",
"https://superuser.com/users/10624/"
] | eZine Article: [Setup a Default Folder View in Windows Vista](http://ezinearticles.com/?Solved---Setup-a-Default-Folder-View-in-Windows-Vista!&id=1465143) talks about some registry stuff along with the points in `Daniel`'s answer. Below is from this link
>
> One of the problems many people face once they have installed Vista is
> that their folder view will change every time they close and reopen a
> folder. This is annoying right?
>
>
> Well here is the solution:
>
>
> 1 Open the registry: Simply click on the start orb and type in "regedit" into the search field. A file called regedit.exe will show
> up at the top, double-click it!
>
>
> 2 Locate the following folders in the registry editor by clicking on the small black arrows to expand the folder structure:
>
>
> [HKEY\_CURRENT\_USERSoftwareClassesLocal
> SettingsSoftwareMicrosoftWindowsShellBags]
>
>
> [HKEY\_CURRENT\_USERSoftwareClassesLocal
> SettingsSoftwareMicrosoftWindowsShellBagMRU]
>
>
> 3 Right click on the folder "Bags" and click on delete, do the same for BagMRU. This is how you get rid of disturbing folder view entries.
> Don't worry we will now create a new one called "DefaultFolders".
>
>
> 4 Right click on the folder "Shell" that is the parent folder of the folders you just deleted.
>
>
> Click on "New" -> "Key". Name it "DefaultFolders".
>
>
> 5 Repeat 4. but for the folder we just created and name the new folder "Shell". That way you will create a subfolder "Shell" inside
> the folder "DefaultFolders".
>
>
> 6 Now we right-click on the folder "Shell" and create a new String: "New" -> "String Value".
>
>
> Give the string the name "FolderType".
>
>
> 7 Double-click it and type "Documents" into the value field.
>
>
> 8 Almost done, now all folders will have the same folder view as the "Documents" folder. Time to set your default folder view. To do that
> open up the explorer (Windows-key + E is the shortcut).
>
>
> Now locate C:UsersYour\_User\_NameDocuments, where C: is the partition
> on which you installed Windows obviously. Make sure to set your
> favorite folder view (mine is Details) there.
>
>
> Click on "Organize" -> "Folder and Search Options".
>
>
> Now go to the tab "View" and finally click on "Apply to Folders"!
>
>
>
I have used the steps from `Daniel`'s answer on Windows XP machines.
If they do not work on the Vista, try the eZine article.
Meanwhile, this Vista64 thread suggests Vista SP2 has solved this problem. | See this article from annoyances.org : ["Default Folder Template Patch"](http://www.annoyances.org/exec/show/choosetemplate), which says:
>
> Windows Vista has a bug that prevents
> it from choosing the correct view for
> a folder based on its contents, which
> is why you may see thumbnails when
> they're not appropriate, and no
> thumbnails when they're needed. The
> following patch stops Vista from
> trying to guess how to display a
> folder, instead forcing it to use the
> template of your choice.
>
>
> |
113,574 | In D&D 5th edition, there is a continuity among the spells that deal with returning life to the dead. Virtually all of them require an expenditure of diamond or diamond dust.
* **Revivify** diamonds worth 300 gp
* **Raise Dead** diamond worth at least 500 gp
* **Resurrection** a diamond worth at least 1,000 gp
* **True Resurrection** a sprinkle of holy water and diamonds worth at least 25,000gp
Additionally, some restorative spells require similar materials:
* **Clone** diamond worth at least 1,000 gp
* **Greater Restoration** diamond dust worth at least 100 gp
Because of this, my players have realized that there is a different order of value placed upon any diamonds they find. An opal or sapphire might be spent, but the diamonds they find are hoarded against possible future need.To be fair, diamonds are used in other spells, but in these they are thematically linked enough to impart the gem a symbolic meaning of restoration, at least in the games we play.
I realize that this doesn't change the value of diamonds in a monetary sense. 500 gp worth of diamonds is worth 500 gp, regardless if they are 10gp/carat, or 50 gp/carat. However, it has got me wondering. Since this does make diamonds special in the eyes of my players, setting them apart from other gems which are largely treated as high denomination currency, **are there other gems or substances (precious or not) among the material components in the spell list which are likewise identified with a certain *type* of spell?**
Such information would be good to have for anything from simple flavor to home brewing new spells.
---
Related:
[Material Component of Reviving Spells](https://rpg.stackexchange.com/questions/101979/material-component-of-reviving-spells) | 2018/01/17 | [
"https://rpg.stackexchange.com/questions/113574",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/28927/"
] | Yes, some material components are thematically related to types of spells
-------------------------------------------------------------------------
I found [this spreadsheet](https://docs.google.com/spreadsheets/d/1KSibOeWub0_f79GYSnMu7om8kWwog1ob8dRY9LLoDAE/edit#gid=0) from this [reddit post](https://www.reddit.com/r/DnD/comments/5fz3k0/spreadsheet_all_material_spell_components_in_dd_5e/), where the user compiled the material components for a lot of spells.
Looking at this list, there are some thematic links, some more clear than others. The stronger ones that I noticed are:
* **Holy water:** Bless, Commune, Dispel Evil, Forbiddance, Magic Circle, Protection from Evil/Good, Regenerate, True Resurrection, Wind Walk
* **Feather:** Fly, Foresight, Identify, Wind Wall, Fear
* **Fleece:** Major Image, Minor Illusion, Phantasmal Force, Programmed Illusion, Silent Image
* **Phosphorous**: Conjure Elemental (Fire),
Dancing Lights,
Fire Shield,
Symbol,
Wall of Fire
* **Sulfur**: Conjure Elemental (Fire),
Delayed Blast Fireball,
Fireball,
Flame Strike
* **Water**: Armor of Agathys,
Conjure Elemental (Water),
Control Water,
Create Water,
Flesh to Stone,
Ice Knife (or as ice) (EEPC) (XGtE),
Ice Storm,
Sleet Storm,
Tidal Wave (EEPC) (XGtE),
Wall of Water (EEPC) (XGtE),
Watery Sphere (EEPC) (XGtE)
* **Lodestone**: Disintegrate, Mending, Reverse Gravity
However, there are a lot of spells that don't seem to have any thematic link but share similar material components. A handful of examples:
* **Ruby**: Infernal Calling, Forbiddance, Forcecage, Simulacrum, Continual Flame
* **Iron filings or powder**: Antimagic Field, Enlarge/Reduce, Flaming Sphere, Reverse Gravity
I'd suggest that you read through the entire list, as I'm sure you'll find something useful in it. | Thanks to someone on Reddit doing most of the legwork ([here](https://www.reddit.com/r/DnD/comments/5fz3k0/spreadsheet_all_material_spell_components_in_dd_5e/)), I found a couple common themes for components:
1. Water is a common component for water and ice spells (surprising, I know). See *conjure elemental (water), control water, create water, ice knife, ice storm, sleet storm, tidal wave, wall of water,* and *watery sphere*.
2. Holy water is a common component for 'holy' spells and wards (such as *bless, commune, dispel evil, magic circle,* and *protection from evil*).
3. Sand is common for sleep spells, including *catnap, dream,* and *sleep*.
4. Clay is common for earth spells, notably *conjure elemental (earth), earthquake,* and *stone shape*.
5. Sulfur is common for fire spells, such as *conjure elemental (fire), delayed blast fireball, fireball,* and *flame strike*.
Other than those, some other components are common (such as incense and rubies), but seemingly without any specific pattern to the spells they are components for. For example, rubies (whether whole or as dust) are needed for *continual flame, forbiddance, forcecage, infernal calling,* and *simulacrum*.
A few components are used in two or three spells of the same type or single-target v. mass target (for example, honeycomb is used for both *suggestion* and *mass suggestion*) but I didn't think this was necessarily worth noting here. |
38,461,449 | My Mac app has an NSMenu whose delegate functions `validateMenuItem` and `menuWillOpen` are never called. So far none of the solutions online have helped.
It seems like I'm doing everything right:
* The menu item's selectors are in the same class.
* The class managing it inherits from NSMenuDelegate
I suppose the best way to describe my problem is to post the relevant code. Any help would be appreciated.
```
import Cocoa
class UIManager: NSObject, NSMenuDelegate {
var statusBarItem = NSStatusBar.system().statusItem(withLength: -2)
var statusBarMenu = NSMenu()
var titleMenuItem = NSMenuItem()
var descriptionMenuItem = NSMenuItem()
// ...
override init() {
super.init()
createStatusBarMenu()
}
// ...
func createStatusBarMenu() {
// Status bar icon
guard let icon = NSImage(named: "iconFrame44")
else { NSLog("Error setting status bar icon image."); return }
icon.isTemplate = true
statusBarItem.image = icon
// Create Submenu items
let viewOnRedditMenuItem = NSMenuItem(title: "View on Reddit...", action: #selector(viewOnRedditAction), keyEquivalent: "")
let saveThisImageMenuItem = NSMenuItem(title: "Save This Image...", action: #selector(saveThisImageAction), keyEquivalent: "")
// Add to title submenu
let titleSubmenu = NSMenu(title: "")
titleSubmenu.addItem(descriptionMenuItem)
titleSubmenu.addItem(NSMenuItem.separator())
titleSubmenu.addItem(viewOnRedditMenuItem)
titleSubmenu.addItem(saveThisImageMenuItem)
// Create main menu items
titleMenuItem = NSMenuItem(title: "No Wallpaperer Image", action: nil, keyEquivalent: "")
titleMenuItem.submenu = titleSubmenu
getNewWallpaperMenuItem = NSMenuItem(title: "Update Now", action: #selector(getNewWallpaperAction), keyEquivalent: "")
let preferencesMenuItem = NSMenuItem(title: "Preferences...", action: #selector(preferencesAction), keyEquivalent: "")
let quitMenuItem = NSMenuItem(title: "Quit Wallpaperer", action: #selector(quitAction), keyEquivalent: "")
// Add to main menu
let statusBarMenu = NSMenu(title: "")
statusBarMenu.addItem(titleMenuItem)
statusBarMenu.addItem(NSMenuItem.separator())
statusBarMenu.addItem(getNewWallpaperMenuItem)
statusBarMenu.addItem(NSMenuItem.separator())
statusBarMenu.addItem(preferencesMenuItem)
statusBarMenu.addItem(quitMenuItem)
statusBarItem.menu = statusBarMenu
}
// ...
// Called whenever the menu is about to show. we use it to change the menu based on the current UI mode (offline/updating/etc)
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
NSLog("Validating menu item")
if (menuItem == getNewWallpaperMenuItem) {
if wallpaperUpdater!.state == .Busy {
DispatchQueue.main.async {
self.getNewWallpaperMenuItem.title = "Updating Wallpaper..."
}
return false
} else if wallpaperUpdater!.state == .Offline {
DispatchQueue.main.async {
self.getNewWallpaperMenuItem.title = "No Internet Connection"
}
return false
} else {
DispatchQueue.main.async {
self.preferencesViewController.updateNowButton.title = "Update Now"
}
return true
}
}
return true
}
// Whenever the menu is opened, we update the submitted time
func menuWillOpen(_ menu: NSMenu) {
NSLog("Menu will open")
if !noWallpapererImageMode {
DispatchQueue.main.async {
self.descriptionMenuItem.title = "Submitted \(self.dateSimplifier(self.updateManager!.thisPost.attributes.created_utc as Date)) by \(self.updateManager!.thisPost.attributes.author) to /r/\(self.updateManager!.thisPost.attributes.subreddit)"
}
}
}
// ...
// MARK: User-initiated actions
func viewOnRedditAction() {
guard let url = URL(string: "http://www.reddit.com\(updateManager!.thisPost.permalink)")
else { NSLog("Could not convert post permalink to URL."); return }
NSWorkspace.shared().open(url)
}
// Present a save panel to let the user save the current wallpaper
func saveThisImageAction() {
DispatchQueue.main.async {
let savePanel = NSSavePanel()
savePanel.makeKeyAndOrderFront(self)
savePanel.nameFieldStringValue = self.updateManager!.thisPost.id + ".png"
let result = savePanel.runModal()
if result == NSFileHandlingPanelOKButton {
let exportedFileURL = savePanel.url!
guard let lastImagePath = UserDefaults.standard.string(forKey: "lastImagePath")
else { NSLog("Error getting last post ID from persistent storage."); return }
let imageData = try! Data(contentsOf: URL(fileURLWithPath: lastImagePath))
if (try? imageData.write(to: exportedFileURL, options: [.atomic])) == nil {
NSLog("Error saving image to user-specified folder.")
}
}
}
}
func getNewWallpaperAction() {
updateManager!.refreshAndReschedule(userInitiated: true)
}
func preferencesAction() {
preferencesWindow.makeKeyAndOrderFront(nil)
NSApp.activateIgnoringOtherApps(true)
}
func quitAction() {
NSApplication.shared().terminate(self)
}
}
``` | 2016/07/19 | [
"https://Stackoverflow.com/questions/38461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3517395/"
] | `menuWillOpen:` belongs to the `NSMenuDelegate` protocol; for it to be called the menu in question needs a delegate:
```
let statusBarMenu = NSMenu(title: "")
statusBarMenu.delegate = self
```
---
`validateMenuItem:` belongs to the `NSMenuValidation` informal protocol; for it to be called the relevant menu *items* must have a `target`. The following passage is taken from Apple's [Application Menu and Pop-up List Programming Topics](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MenuList/Articles/EnablingMenuItems.html) documentation:
>
> When you use automatic menu enabling, NSMenu updates the status of every menu item whenever a user event occurs. To update the status of a menu item, NSMenu first determines the target of the item and then determines whether the target implements validateMenuItem: or validateUserInterfaceItem: (in that order).
>
>
>
```
let myMenuItem = NSMenuItem()
myMenuItem.target = self
myMenuItem.action = #selector(doSomething)
``` | The above (accepted) answer states that a target *must* be set, is a bit misleading. It is not required to set a target. You can (for example) also make the first responder, without explicitly setting a target.
Details can be found in the appel documentation, which can be found here: <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MenuList/Articles/EnablingMenuItems.html>
There is one tricky part though when using swift:
if validateMenuItem does not get called, then make sure your class not only declares conformance to NSMenuDelegate, but *also* to NSMenuItemValidation.
```
class SomeClass: NSMenuDelegate, NSMenuItemValidation {
...
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
return true // or whatever, on whichever condition
}
}
``` |
10,858,505 | I'm trying to run around 15000 soap requests through JMeter. I have 15000 individual soap files in a folder.
I know that the [WebService(SOAP) Request](http://jmeter.apache.org/usermanual/component_reference.html#WebService%28SOAP%29_Request) component has the option to point to a folder.
But, the problem is that the files in the folder will get picked up and run randomly and a file can get run multiple times.
This is not ideal because each request has a unique correlation id and if a file get's run twice, the second run will fail due to a duplicated correlation id.
Is there anyway, I could tell jmeter to run the files only once?
Also, as certain soap requests are dependent upon other request having already run, the ability to run these in a specified order would be desirable. Is this possible?
These seem like common problems that should have already been solved. But, I can't find much on google.
Do you guys have any ideas? | 2012/06/01 | [
"https://Stackoverflow.com/questions/10858505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499635/"
] | I would use [the JSR223 Sampler](http://jmeter.apache.org/usermanual/component_reference.html#JSR223_Sampler) to run a script (e.g. Groovy) to iterate through the files in the directory and store the text of each file in a String.
See, for example, [this other answer](https://stackoverflow.com/a/9733568/62667) about using a Groovy script to iterate a list of values. | You could put the data into a csv file and read it in using a CSV Data Set Config. If you need unique values over multiple threads then you have to create multiple files, one per thread.
You could also put the data in a database and use a JDBC Config/Sampler to access it, making sure to either a: delete the data after it is read, or b: mark it as 'read' using a flag. Both methods would prevent the same record being read twice by different threads.
If you need to run requests in order you should structure the test plan as such, requests will be made sequentially, top to bottom. |
64,231,141 | For tableviews, I have never had an issue with a text label persisting after a cell is reused.
When you reload a tableview after the datasource has changed, the tableviewcells get the latest data and draw themselves accordingly.
However, I am now having this problem with an attributed label. After removing an item from the datasource so that the tableviewcell gets re-used the attributed label persists in the cell. Needless to say, the leftover attributed label has nothing to do with what should be in the cell. It's just attached to the cell and won't go away.
The problem is described [here:](https://stackoverflow.com/questions/58628067/cant-reset-uilabel-attributedtext-when-a-uitableviewcell-is-reused)
In the above answer, the person said he got rid of the attributed label by setting it to nil prior to doing anything with the regular text label.
```
transactionDescriptionLabel.attributedText = nil
transactionValueLabel.attributedText = nil
Or, if I reset the attributedText first, and then reset the text, it also works:
transactionDescriptionLabel.attributedText = nil
transactionValueLabel.attributedText = nil
transactionDescriptionLabel.text = nil
transactionValueLabel.text = nil
```
Setting the attributed label to nil seems to solve the problem for me but I have never had to set a regular textLabel to nil before and am trying to get my arms around why I would have to set the attribute label to nil.
When you have an attribute label, is it necessary to set it to nil when you dequeue the cell? Or, apart from setting it to an empty string, what is the proper way to get it to disappear when you are no longer displaying it in the tableview?
Thanks in advance for any suggestions. | 2020/10/06 | [
"https://Stackoverflow.com/questions/64231141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6631314/"
] | I just stumbled upon the exact same issue with `NSUnderlineStyleAttributeName`. I have to underline some text in a `UILabel` inside a `UITableViewCell` only if a condition is met. After scrolling through the cell, the label keeps reusing the attributes.
I tried several workaround, by setting `label.text` and `label.attributedText` to `nil`, removing attributes etc... nothing worked.
Finally, I found the actual solution looking at `NSAttributedString` documentation (RTFM, is always the answer):
There are enums defined for underline, and strikethrough attributes :
**NSUnderlineStyleNone = 0x00**
```
UIKIT_EXTERN NSAttributedStringKey const NSStrikethroughStyleAttributeName API_AVAILABLE(macos(10.0), ios(6.0)); // NSNumber containing integer, default 0: no strikethrough
UIKIT_EXTERN NSAttributedStringKey const NSUnderlineStyleAttributeName API_AVAILABLE(macos(10.0), ios(6.0)); // NSNumber containing integer, default 0: no underline
```
---
In conclusion, the actual way to remove underline or strikeThrough attribute is to set it to `NSUnderlineStyleNone` or `0`.
```
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
[attributeString setAttributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleNone)} range:(NSRange){0, [attributeString length]}];
label.attributedText = attributeString;
``` | `label.attributedText` will have styling properties of the string as well.
Before reusing, I mean before setting the `attributedText` property even once, the styling property would be set to default. If you use a `xib/storyboard`, you can see the default style for the label in attribute inspector or if you have edited these values then you know it already.
Now, if you set `label.text = "This is just text"`. This takes the default styling provided.
And at some point if you have to assign
1. `label.attributedText = NSAttributedString(string: "Attributed text", attributes: someAttributes)`
So from now, if you reuse this label, and set just the text like
`label.text = "This is just text"`
This causes the label to reuse the styling provided in previous cases via `someAttributes`
So if there's a case where you reuse your cell and the label inside it has different styles in different rows, better always set the
`attributedText` property with you required attributes. *Like point 1*
Now, if you don't need the label entirely you can remove it from the view heirarchy by `label.removeFromSuperview()`(handle reuse carefully in this case, use this only when you are sure that you won't be reusing this view accessing the removed label) |
22,934,720 | I have a problem about create a query for text-searching starting at begining of column character. For example: I have a table 'BOOK' with a column 'TITLE'. I have 3 rows in 'BOOK' table with 'TITLE' values are: 'ANDROID APPLICATION', 'ANDROID APP DEVELOPMENT' and 'ANDROID APPLICATION PROGRAMMING'.
Now when my input is 'ANDROID APP', I need all 3 rows matched. When I type 'ANDROID APPLICATION', I need 2 rows matched: 'ANDROID APPLICATION' and 'ANDROID APPLICATION PROGRAMMING'. And when I type 'APP' or 'APPLICATION', I need no row matched (because we want to start searching at begining character of column value).
I've read the SQLite FTS document but I dont know how to use prefix query, phrase query... together with AND, OR, NOT operation to solve my problem? Anyone could give me an approriate query syntax? | 2014/04/08 | [
"https://Stackoverflow.com/questions/22934720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679361/"
] | FTS cannot search from the beginning of a column value.
(Actually, it can, but this is undocumented and not enabled in Android.)
To search from the beginning, you have to use `LIKE 'pattern%'`.
If you want this to be efficient, you have to use this with a normal table and a case-insensitive index ([COLLATE NOCASE](http://www.sqlite.org/lang_createindex.html)). | Try below:
```
String name = your book name which entered by search box;
String sql ="select "+TITLE+" from "+BOOK+" where TITLE like '"+ name +"%'";
``` |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | Formally it would be "the city from which you came", "the city whence you came" (except that 'whence' is definitely archaic), "your native city", or perhaps "your city of origin" or "original city".
Colloquially, in a sentence I would say "The city you came from" instead of "The city where you came from". If I were writing it though, e.g. on a form to label an input text field, then "The city where you came from" might be better because it's a little less ambiguous.
Note that neither is entirely grammatical though, because they're not complete sentences: they're missing a subject and a verb. | Erm. Isn't it "The city THAT you come from?" as in "The city that you originate from".
The other way is practically an innuendo.
[This may be my tenuous grasp of english afforded by being a Mancunian.] |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | If this is a form field in an application (to make it vaguely programming related :-) ), "Country of origin" seems to me more natural. | In *spoken* US English, it's fine with or without `where` -- **but** I wouldn't use either on a website. **Here's why**:
I am a native US English speaker. I would only say `I come from America` if I was traveling in another country, or if I had moved to another country and was THERE ALREADY. I would never say it while I was in America.
So the saying `I come from America` implies that you and I are somewhere OTHER than America.
So if you say on your website, `The country [where] you come from`, it would imply that your visitors are AWAY from their home country, or that your visitors have MOVED away from their original country.
I know it's subtle, but if you ask it online, it will sound slightly strange and "off".
---
Instead, ask exactly what you want to know. If you want to know where they live *right now*, say one of the following:
1. `Your country of residence`
2. `The country where you live`
3. `The country you live in` (Yes, in actual practical US English, the `in` can go at the end.)
If you want to know the country where people consider themselves a native, then say `The country you consider yourself a native of`. The word `native` means different things to different people, though. Similarly, you could say `Your home country`, but again, `home` means different things to different people.
Or if your visitors truly HAVE come from a different country and ARE NOW in a new country, say `The country you came from`. (Note I said **CAME** and not COME.) You could also say `Your country of origin` but that sounds robotic and bureaucratic.
I know you probably already deployed your form, but I hope this will bring you some more clarity. |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | Where is required for written English (UK), but would commonly be dropped in spoken (colloquial) English. | In *spoken* US English, it's fine with or without `where` -- **but** I wouldn't use either on a website. **Here's why**:
I am a native US English speaker. I would only say `I come from America` if I was traveling in another country, or if I had moved to another country and was THERE ALREADY. I would never say it while I was in America.
So the saying `I come from America` implies that you and I are somewhere OTHER than America.
So if you say on your website, `The country [where] you come from`, it would imply that your visitors are AWAY from their home country, or that your visitors have MOVED away from their original country.
I know it's subtle, but if you ask it online, it will sound slightly strange and "off".
---
Instead, ask exactly what you want to know. If you want to know where they live *right now*, say one of the following:
1. `Your country of residence`
2. `The country where you live`
3. `The country you live in` (Yes, in actual practical US English, the `in` can go at the end.)
If you want to know the country where people consider themselves a native, then say `The country you consider yourself a native of`. The word `native` means different things to different people, though. Similarly, you could say `Your home country`, but again, `home` means different things to different people.
Or if your visitors truly HAVE come from a different country and ARE NOW in a new country, say `The country you came from`. (Note I said **CAME** and not COME.) You could also say `Your country of origin` but that sounds robotic and bureaucratic.
I know you probably already deployed your form, but I hope this will bring you some more clarity. |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | **The city from which you came.**
"From" is a preposition. It's a grammatical error to end a sentence with a preposition.
However, used in the context of an input form, "[City or Country] of Origin" would be more suitable. | The complete form would be `The city from which you come`. As it's a relative clause with the pronoun as its object, you can leave it out. ("contact clause") |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | Erm. Isn't it "The city THAT you come from?" as in "The city that you originate from".
The other way is practically an innuendo.
[This may be my tenuous grasp of english afforded by being a Mancunian.] | In *spoken* US English, it's fine with or without `where` -- **but** I wouldn't use either on a website. **Here's why**:
I am a native US English speaker. I would only say `I come from America` if I was traveling in another country, or if I had moved to another country and was THERE ALREADY. I would never say it while I was in America.
So the saying `I come from America` implies that you and I are somewhere OTHER than America.
So if you say on your website, `The country [where] you come from`, it would imply that your visitors are AWAY from their home country, or that your visitors have MOVED away from their original country.
I know it's subtle, but if you ask it online, it will sound slightly strange and "off".
---
Instead, ask exactly what you want to know. If you want to know where they live *right now*, say one of the following:
1. `Your country of residence`
2. `The country where you live`
3. `The country you live in` (Yes, in actual practical US English, the `in` can go at the end.)
If you want to know the country where people consider themselves a native, then say `The country you consider yourself a native of`. The word `native` means different things to different people, though. Similarly, you could say `Your home country`, but again, `home` means different things to different people.
Or if your visitors truly HAVE come from a different country and ARE NOW in a new country, say `The country you came from`. (Note I said **CAME** and not COME.) You could also say `Your country of origin` but that sounds robotic and bureaucratic.
I know you probably already deployed your form, but I hope this will bring you some more clarity. |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | Formally it would be "the city from which you came", "the city whence you came" (except that 'whence' is definitely archaic), "your native city", or perhaps "your city of origin" or "original city".
Colloquially, in a sentence I would say "The city you came from" instead of "The city where you came from". If I were writing it though, e.g. on a form to label an input text field, then "The city where you came from" might be better because it's a little less ambiguous.
Note that neither is entirely grammatical though, because they're not complete sentences: they're missing a subject and a verb. | In *spoken* US English, it's fine with or without `where` -- **but** I wouldn't use either on a website. **Here's why**:
I am a native US English speaker. I would only say `I come from America` if I was traveling in another country, or if I had moved to another country and was THERE ALREADY. I would never say it while I was in America.
So the saying `I come from America` implies that you and I are somewhere OTHER than America.
So if you say on your website, `The country [where] you come from`, it would imply that your visitors are AWAY from their home country, or that your visitors have MOVED away from their original country.
I know it's subtle, but if you ask it online, it will sound slightly strange and "off".
---
Instead, ask exactly what you want to know. If you want to know where they live *right now*, say one of the following:
1. `Your country of residence`
2. `The country where you live`
3. `The country you live in` (Yes, in actual practical US English, the `in` can go at the end.)
If you want to know the country where people consider themselves a native, then say `The country you consider yourself a native of`. The word `native` means different things to different people, though. Similarly, you could say `Your home country`, but again, `home` means different things to different people.
Or if your visitors truly HAVE come from a different country and ARE NOW in a new country, say `The country you came from`. (Note I said **CAME** and not COME.) You could also say `Your country of origin` but that sounds robotic and bureaucratic.
I know you probably already deployed your form, but I hope this will bring you some more clarity. |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | Formally it would be "the city from which you came", "the city whence you came" (except that 'whence' is definitely archaic), "your native city", or perhaps "your city of origin" or "original city".
Colloquially, in a sentence I would say "The city you came from" instead of "The city where you came from". If I were writing it though, e.g. on a form to label an input text field, then "The city where you came from" might be better because it's a little less ambiguous.
Note that neither is entirely grammatical though, because they're not complete sentences: they're missing a subject and a verb. | I believe the way you have it is correct - "where" is optional. |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | **The city from which you came.**
"From" is a preposition. It's a grammatical error to end a sentence with a preposition.
However, used in the context of an input form, "[City or Country] of Origin" would be more suitable. | Erm. Isn't it "The city THAT you come from?" as in "The city that you originate from".
The other way is practically an innuendo.
[This may be my tenuous grasp of english afforded by being a Mancunian.] |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | **The city from which you came.**
"From" is a preposition. It's a grammatical error to end a sentence with a preposition.
However, used in the context of an input form, "[City or Country] of Origin" would be more suitable. | In *spoken* US English, it's fine with or without `where` -- **but** I wouldn't use either on a website. **Here's why**:
I am a native US English speaker. I would only say `I come from America` if I was traveling in another country, or if I had moved to another country and was THERE ALREADY. I would never say it while I was in America.
So the saying `I come from America` implies that you and I are somewhere OTHER than America.
So if you say on your website, `The country [where] you come from`, it would imply that your visitors are AWAY from their home country, or that your visitors have MOVED away from their original country.
I know it's subtle, but if you ask it online, it will sound slightly strange and "off".
---
Instead, ask exactly what you want to know. If you want to know where they live *right now*, say one of the following:
1. `Your country of residence`
2. `The country where you live`
3. `The country you live in` (Yes, in actual practical US English, the `in` can go at the end.)
If you want to know the country where people consider themselves a native, then say `The country you consider yourself a native of`. The word `native` means different things to different people, though. Similarly, you could say `Your home country`, but again, `home` means different things to different people.
Or if your visitors truly HAVE come from a different country and ARE NOW in a new country, say `The country you came from`. (Note I said **CAME** and not COME.) You could also say `Your country of origin` but that sounds robotic and bureaucratic.
I know you probably already deployed your form, but I hope this will bring you some more clarity. |
872,891 | I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**. | 2009/05/16 | [
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] | Where is required for written English (UK), but would commonly be dropped in spoken (colloquial) English. | I believe the way you have it is correct - "where" is optional. |
37,727 | As we all know that Upanishads were written to understand Vedas. Some great scholars also said that they are the branches of Vedas. My question is related to it. Yesterday in a library, I was reading some books and then I found a book written by Dr. Surendra KR Sharma. The name of the book was in Hindi **Kya baloo ki bhit par khada hai Hindu dharma (Does Hinduism stand on the wall of sand)**. On page no. 344.
In this book he quoted Mundak Upanishad 1:1:5. I am giving the English translation by Dr. Sarvepalli Radhakrishnan.

So my question I am confused now that **Why Vedas are called inferior in Upanishads?** | 2020/01/04 | [
"https://hinduism.stackexchange.com/questions/37727",
"https://hinduism.stackexchange.com",
"https://hinduism.stackexchange.com/users/19001/"
] | We should also read the next verse (1:1:6) in continuation for understanding Mundak Upanishad 1.1.5
Please [read the following](https://www.swami-krishnananda.org/mundak1/mundak1_1.html):
>
> We cannot go to the Veda directly and understand anything out of it
> unless we are proficient in these six auxiliary shastras, or
> scriptures, called śikṣā kalpo vyākaraṇaṁ niruktaṁ chando jyotiṣam.
> All these, says the great Master, together with the original Vedas—the
> **Rigveda, Yajurveda, Samaveda and Atharvaveda—\*\*should be considered \*\*\*as lower knowledge.\***
>
>
> They purify our minds and enlighten us into the mysteries of the whole
> of creation. They purify our minds because of ***the power that is
> embedded in the mantras*** and the emotional or religious awareness that
> is stimulated within us on account of the meaning that we see in the
> mantras, the blessing that we receive from the sages, who composed the
> mantras, and also the special power that is generated by the metre.
>
>
> All these put together create a religious atmosphere in the person who
> takes to the study of the Veda. It is great and grand, worth studying.
> It will lift us to the empyrean of a comprehension of values that are
> not merely physical, but ***superphysical***. Yet, it is not enough. There
> is a ‘but’ behind it. What is that greater knowledge, which is higher
> than this mentioned?
>
>
> ***Atha parā yayā tad akṣaram adhigamyate***: That is the ***higher knowledge*** with which alone can we reach the imperishable Reality. Learning is
> different from wisdom; scholarship is not the same as insight. One may
> be a learned Vedic scholar and very proficient in the performance of
> sacrifices and the invocation of gods in the heavens, but eternity is
> different from temporality.
>
>
>
All these glories of the Veda are in the
region of time, and the Eternal is timeless. What is that timeless
thing, that which is called **Imperishable**?
>
> Yat tad adreśyam, agrāhyam, agotram, avarṇam, acakṣuḥ- śrotraṁ tad
> apāṇi-padām, nityam vibhuṁ sarva-gataṁ susūkṣmaṁ tad avyayam yad
> bhūta-yonim paripaśyanti dhīrāḥ (1.1.6)
>
>
>
That great Reality is to be encountered in ***direct experience***.
* **Adreśyam**: that Reality which is not capable of perception through the eyes;
* **agrāhyam**: that which cannot be grasped with the hands;
* **avarnam**: which has no origin;
* **agotram**: which has no shape or form;
* **acakṣuḥ-śrotraṁ**: which has no sense organs like us;
* **tad apāṇi-padam**: which has no limbs such as feet, hands, etc.;
* **nityam vibhum sarva-gataṁ susūkṣmaṁ**: which is permanent, eternal, all-pervading, subtler than the subtlest;
* **tad avyayam**: which is imperishable;
* **bhūta-yonim**: which is the origin of all beings;
* **paripaśyanti dhīrāḥ**: heroes on the path of the spirit will behold that great **Reality** ***within their own selves***.
---
Mundak Upanishad 1.1.5 was saying that mere learning Vedic mantras of Vedas is not sufficient to attain the Ultimate Wisdom. That is why it is calling the Vedas as Inferior to the ***ULTIMATE KNOWLEDGE***. | The Upanishad verse in question refers to the Vedas interpreted only ritualistically, as inferior. It does not negate the importance of Vedic knowledge itself. Because we see the same Upanishad talk about the Vedas in high regard.
2.1.6:
>
> तस्मादृचः साम यजूंषि दीक्षा यज्ञाश्च सर्वे क्रतवो दक्षिणाश्च
>
>
> From the Atman, came the Rk, Sama, Yajus, consecrations, yajnas, all holy works and holy donations.
>
>
>
3.2.10:
>
> क्रियावन्तः श्रोत्रिया ब्रह्मनिष्ठाः स्वयं जुह्वत एकर्षिं श्रद्धयन्तः ।
>
> तेषामेवैतां ब्रह्मविद्यां वदेत शिरोव्रतं विधिवद्यैस्तु चीर्णम् ॥
>
>
> This Brahmavidyā should be taught only to those who regularly perform all the rituals (kriyāvanta), are well-versed in the Vedas (śrotriya), committed to Vedic learning (brahmaniṣṭha), who perform their own yajnas (svayam juhvata), and have truth-belief in the Atman.
>
>
>
So clearly, the Upanishad feels that the prerequisite for learning about Brahman is to be completely leading a committed Vaidika lifestyle and a wise knowledge of Vedas. This shows that the Upanishad knew about the secret spiritual teachings in the Vedas hidden under symbolism. It only criticises the superficial application of Vedas. |
37,727 | As we all know that Upanishads were written to understand Vedas. Some great scholars also said that they are the branches of Vedas. My question is related to it. Yesterday in a library, I was reading some books and then I found a book written by Dr. Surendra KR Sharma. The name of the book was in Hindi **Kya baloo ki bhit par khada hai Hindu dharma (Does Hinduism stand on the wall of sand)**. On page no. 344.
In this book he quoted Mundak Upanishad 1:1:5. I am giving the English translation by Dr. Sarvepalli Radhakrishnan.

So my question I am confused now that **Why Vedas are called inferior in Upanishads?** | 2020/01/04 | [
"https://hinduism.stackexchange.com/questions/37727",
"https://hinduism.stackexchange.com",
"https://hinduism.stackexchange.com/users/19001/"
] | The Vedas are divisible into two parts which are [Purva Mimamsa](https://en.wikipedia.org/wiki/M%C4%ABm%C4%81%E1%B9%83s%C4%81) or Karma Mimamsa dealing with rituals for Dharma, Artha, Kama and Gyana Kanda or Uttara Mimamsa/Upanishads for Moksha. Dharma, Artha, Kama and Moksha together are [Purusartha](https://en.wikipedia.org/wiki/Puru%E1%B9%A3%C4%81rtha) or purpose of society and its beings. Upanishads have called Purva Mimamsa as inferior when compared to Gyana Kanda Vedanta.
[Mundaka Upanishad Chapter 1](https://www.wisdomlib.org/hinduism/book/mundaka-upanishad-shankara-bhashya/d/doc145078.html)
>
> 3. Saunaka, a great grihasta, having duly approached Angiras, questioned him “What is that, O Bhagavan which being known, all this
> becomes known.” (3)
> 4. **To him he said “There are two sorts of knowledge to he acquired. So those who know the Brahman say; namely, Para and Apara, i.e., the
> higher and the lower.**
> 5. **Of these, the Apara is the Rig Veda, the Yajur Veda, the Sama Veda, and the Atharva Veda, the siksha, the code of rituals, grammar,
> nirukta, chhandas and astrology. Then the para is that by which the
> immortal is known.**
> 6. That which cannot be perceived, which cannot be seized, which has no origin, which has no properties, which has neither ear nor eye,
> which lias neither hands nor feet, which is eternal, diversely
> manifested, all-pervading, extremely subtle, and undecaying, which the
> intelligent cognized as the source of the Bhutas. (6)
> 7. As the spider creates and absorbs, as medicinal plants grow from the earth, as hairs grow from the living person, so this universe
> proceeds from the immortal.
> 8. By tapas Brahman increases in size and from it food is produced; from food the prana, the mind, the Bhûtas the worlds, karma and with
> it, its fruits.
> 9. From the Brahman who knows all and everything of all and whose tapas is in the nature of knowledge, this Brahma, name, form and food
> are produced.
>
>
>
Importance of Brahmgyan over memorizing Vedic Karma kanda alone, was also explained by sage Yagyavalkya to Gargi and sage Uddalak to his son Shvetaketu.
>
> [Brihadarayanka Upanishad 3.8.9](https://www.wisdomlib.org/hinduism/book/the-brihadaranyaka-upanishad/d/doc118359.html). **He, O Gārgī, who in this world,
> without knowing this Immutable, offers oblations in the fire, performs
> sacrifices and undergoes austerities even for many thousand years,
> finds all such acts but perishable; he, O Gārgī, who departs from this
> world without knowing this Immutable, is miserable.** But he, O Gārgī,
> who departs from this world after knowing this Immutable, is a knower
> of Brahman.
>
>
>
[Chandogya Upanishad Chapter 6](https://www.wisdomlib.org/hinduism/book/chandogya-upanishad-english/d/doc239254.html)
>
> 1.1. Āruṇi had a son named Śvetaketu. Once Āruṇi told him: ‘Śvetaketu, you should now live as a brahmacārin. No one in our family has not
> studied the scriptures and has not been a good brāhmin’.
>
>
> 1.2. **Śvetaketu went to his teacher’s house at the age of twelve. After studying all the Vedas, he returned home when he was twenty-four,
> having become very serious and vain, and thinking himself to be a
> great scholar. [Noticing this,] his father said to him: ‘O Śvetaketu,
> you have now become very serious and vain, and you think you are a
> great scholar. But did you ask your teacher for that teaching [about
> Brahman]—**
>
>
> 1.3.**‘—that teaching by which what is never heard becomes heard, what is never thought of becomes thought of, what is never known becomes
> known?’** [Śvetaketu asked,] ‘Sir, what is that teaching?’.
>
>
> 1.5. O Somya, it is like this: By knowing a single lump of gold you know all objects made of gold. All changes are mere words, in name
> only. But gold is the reality.
>
>
> 1.7. [Śvetaketu said:] ‘Surely my revered teachers did not know this truth. If they knew it, why should they not have told me? So please
> explain it to me, sir.’ His father said, ‘Let it be so, my son’.
>
>
> 2.1. Somya, before this world was manifest there was only existence, one without a second. On this subject, some maintain that before this
> world was manifest there was only non-existence, one without a second.
> Out of that non-existence, existence emerged.
>
>
> 2.2. The father said: ‘O Somya, what proof is there for this—that from nothing something has emerged? Rather, before this world came into
> being, O Somya, there was only existence, one without a second’.
>
>
> 2.3. That Existence decided: ‘I shall be many. I shall be born.’ He then created fire. That fire also decided: ‘I shall be many. I shall
> be born.’ Then fire produced water. That is why whenever or wherever a
> person mourns or perspires, he produces water.
>
>
> 3.2. That god [Existence] decided: ‘Entering into these three deities [fire, water, and earth], as the individual self, I shall manifest
> myself in many names and forms’.
>
>
> 3.3. Sat [Existence] thought, ‘I shall divide each of these three deities threefold.’ Then, having entered into these three deities as
> the individual self, he manifested himself as names and forms.
>
>
>
Thats why, after Buddhism spread in India during reign of Ashoka, many leftout Hindus attached themselves to Purva Mimamsa for Dharma,Artha and Kama naturally, and Adi Shankaracharya, champion of Uttara Mimamsa defeated Buddhists and followers of Karma Mimamsa like [Mandana Mishra](https://en.wikipedia.org/wiki/Ma%E1%B9%87%E1%B8%8Dana_Mi%C5%9Bra) in [scriptural debates](https://www.esamskriti.com/e/Spirituality/Vedanta/The-classic-debate-between-Mandana-Misra-and-Adi-Shankara-1.aspx) and made them enter into Sanyass or Bhakti Hinduism of Puranas. | The Upanishad verse in question refers to the Vedas interpreted only ritualistically, as inferior. It does not negate the importance of Vedic knowledge itself. Because we see the same Upanishad talk about the Vedas in high regard.
2.1.6:
>
> तस्मादृचः साम यजूंषि दीक्षा यज्ञाश्च सर्वे क्रतवो दक्षिणाश्च
>
>
> From the Atman, came the Rk, Sama, Yajus, consecrations, yajnas, all holy works and holy donations.
>
>
>
3.2.10:
>
> क्रियावन्तः श्रोत्रिया ब्रह्मनिष्ठाः स्वयं जुह्वत एकर्षिं श्रद्धयन्तः ।
>
> तेषामेवैतां ब्रह्मविद्यां वदेत शिरोव्रतं विधिवद्यैस्तु चीर्णम् ॥
>
>
> This Brahmavidyā should be taught only to those who regularly perform all the rituals (kriyāvanta), are well-versed in the Vedas (śrotriya), committed to Vedic learning (brahmaniṣṭha), who perform their own yajnas (svayam juhvata), and have truth-belief in the Atman.
>
>
>
So clearly, the Upanishad feels that the prerequisite for learning about Brahman is to be completely leading a committed Vaidika lifestyle and a wise knowledge of Vedas. This shows that the Upanishad knew about the secret spiritual teachings in the Vedas hidden under symbolism. It only criticises the superficial application of Vedas. |
37,727 | As we all know that Upanishads were written to understand Vedas. Some great scholars also said that they are the branches of Vedas. My question is related to it. Yesterday in a library, I was reading some books and then I found a book written by Dr. Surendra KR Sharma. The name of the book was in Hindi **Kya baloo ki bhit par khada hai Hindu dharma (Does Hinduism stand on the wall of sand)**. On page no. 344.
In this book he quoted Mundak Upanishad 1:1:5. I am giving the English translation by Dr. Sarvepalli Radhakrishnan.

So my question I am confused now that **Why Vedas are called inferior in Upanishads?** | 2020/01/04 | [
"https://hinduism.stackexchange.com/questions/37727",
"https://hinduism.stackexchange.com",
"https://hinduism.stackexchange.com/users/19001/"
] | Vedic karma Kanda and Jnana Kanda are both far below spiritual experience.
>
> They study the Vedas and discuss. **But they do not realize the Ultimate
> Reality just as a spoon does not know the taste of food**.
>
>
> The head
> carries the flowers, the nose knows the scent. The people study the
> Vedas. But, very few persons understand the same. **Not knowing the
> Reality of the self, a fool is infatuated by the sastras.**
>
>
> When the
> goat stands in the shed, the shepherd seeks for it in the well in
> vain. **The knowledge of the sastras is not competent to destroy the
> infatuation accruing from worldly affairs.**
>
>
> ….
>
>
> Having studied the
> Vedas and realized their essence **the wise man should leave all the
> sastras just as one desiring corn leaves the husk**.
>
>
> Just as one
> satiated with nectar has no use of food, **no one who is in search of
> Reality has anything to do with the sastras**.
>
>
> One cannot obtain release
> by reading the Vedas or the sastras. **Release comes from experience,
> not otherwise,** O son of Vinata.
>
>
>
[**Garuda Purana, Dharma Khanda, Chapter XLIX**] | The Upanishad verse in question refers to the Vedas interpreted only ritualistically, as inferior. It does not negate the importance of Vedic knowledge itself. Because we see the same Upanishad talk about the Vedas in high regard.
2.1.6:
>
> तस्मादृचः साम यजूंषि दीक्षा यज्ञाश्च सर्वे क्रतवो दक्षिणाश्च
>
>
> From the Atman, came the Rk, Sama, Yajus, consecrations, yajnas, all holy works and holy donations.
>
>
>
3.2.10:
>
> क्रियावन्तः श्रोत्रिया ब्रह्मनिष्ठाः स्वयं जुह्वत एकर्षिं श्रद्धयन्तः ।
>
> तेषामेवैतां ब्रह्मविद्यां वदेत शिरोव्रतं विधिवद्यैस्तु चीर्णम् ॥
>
>
> This Brahmavidyā should be taught only to those who regularly perform all the rituals (kriyāvanta), are well-versed in the Vedas (śrotriya), committed to Vedic learning (brahmaniṣṭha), who perform their own yajnas (svayam juhvata), and have truth-belief in the Atman.
>
>
>
So clearly, the Upanishad feels that the prerequisite for learning about Brahman is to be completely leading a committed Vaidika lifestyle and a wise knowledge of Vedas. This shows that the Upanishad knew about the secret spiritual teachings in the Vedas hidden under symbolism. It only criticises the superficial application of Vedas. |
34,102,231 | Good evening!
I'm a beginner programmer and am finishing up my first semester of C++. Currently I'm looking a final exam review sheet my professor gave us and I just don't understand exactly what it's asking me to do. I feel like if I saw an example I would get it immediately but as is I am rather lost.
Here's the review question.
```
Problem: Given the following class definition, implement the class methods.
class CreditCard {
public:
CreditCard(string & no, string & nm, int lim, double bal = 0);
string getNumber();
string getName();
double getBalance();
int getLimit();
// Does the card have enough to buy something?
bool chargelt(double price);
private:
string number;
string name;
int limit;
double balance;
};
```
I know there isn't much context here, but let's just say in the context of this being a introductory C++ course, what is likely asking me to do/learn? I'm really not sure what "implement the class methods" means here, and while it may be something that I've seen already, more than likely it's just an issue I have with not understanding it in plain English.
And I suppose it can also be asked that: If you were to teach an beginner student with this code, what would you expect them to do with it or learn from it?
Any insight would be greatly appreciated =) | 2015/12/05 | [
"https://Stackoverflow.com/questions/34102231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5026229/"
] | Think of the credit card as the real world object. And it will have the attributes of name,number,limit.
So, you have to do is set the values of these each in the constructor method, as because when we create a credit card we have these values assigned to them, like this
```
CreditCard::CreditCard(string & no, string & nm, int lim, double bal = 0)
{
this->number = no; //you can also use number = no
this->limit = lim;
this->name = nm;
this->balance = bal;
}
```
Now, as we have a credit card we may want to know the name of the card, so this can be implemented as follows:
```
string CreditCard::getName();
{
return name;
}
```
The same way we can get the limits and number. I will leave that for you. | This code is the definition of a class, the blueprint of an object. It is an introduction to the strong object-oriented programming of C++ and contains some key concepts.
You have the elements of a basic object.
```
class CreditCard {
public:
// Constructor.(to construct an object).
CreditCard(string & no, string & nm, int lim, double bal = 0);
// Accessors (to access the attributes of the object).
string getNumber();
string getName();
double getBalance();
int getLimit();
// Does the card have enough to buy something?
/// A public method of the class.
bool chargelt(double price);
private:
// Attributes.
string number;
string name;
int limit;
double balance;
}
```
The term *implement* means that you have to *create* the functions that you defined for the class. Usually, for each class, one will make a header file for the definition and a source file for the implementation, but you can make it on the same page too.
The implementation of a method can follow this template :
```
string CreditCard::getNumber()
{
return number; // Instructions as you're making a standard function.
}
```
For the constructor, it is important that you initialize the attributes of the object. So, in your implementation of the constructor, you have to associate the input parameters to the attributes. Notethat you don't need to return any value since the created object can be seen as the "returned value". |
34,102,231 | Good evening!
I'm a beginner programmer and am finishing up my first semester of C++. Currently I'm looking a final exam review sheet my professor gave us and I just don't understand exactly what it's asking me to do. I feel like if I saw an example I would get it immediately but as is I am rather lost.
Here's the review question.
```
Problem: Given the following class definition, implement the class methods.
class CreditCard {
public:
CreditCard(string & no, string & nm, int lim, double bal = 0);
string getNumber();
string getName();
double getBalance();
int getLimit();
// Does the card have enough to buy something?
bool chargelt(double price);
private:
string number;
string name;
int limit;
double balance;
};
```
I know there isn't much context here, but let's just say in the context of this being a introductory C++ course, what is likely asking me to do/learn? I'm really not sure what "implement the class methods" means here, and while it may be something that I've seen already, more than likely it's just an issue I have with not understanding it in plain English.
And I suppose it can also be asked that: If you were to teach an beginner student with this code, what would you expect them to do with it or learn from it?
Any insight would be greatly appreciated =) | 2015/12/05 | [
"https://Stackoverflow.com/questions/34102231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5026229/"
] | Strictly speaking, the C++ language doesn't have "methods". It has "member functions", and perhaps that's the terminology that you're more familiar with. But many other languages do use the term "method", so it's actually fairly common for C++ programmers to say "methods" when what they're really talking about is member functions.
The class definition shows that the class defines four member functions:
```
string getNumber();
string getName();
double getBalance();
int getLimit();
```
The definition also shows that there is a constructor:
```
CreditCard(string & no, string & nm, int lim, double bal = 0);
```
A constructor is also a type of member function, but most people don't refer to constructors as "methods". Some probably do, though.
So, the instruction "implement the class methods" means: "write the code for the member functions `getNumber()` `getName()` `getBalance()` and `getLimit()`."
It might also mean "and write the code for the constructor, `CreditCard(string & no, string & nm, int lim, double bal)`", too. | Think of the credit card as the real world object. And it will have the attributes of name,number,limit.
So, you have to do is set the values of these each in the constructor method, as because when we create a credit card we have these values assigned to them, like this
```
CreditCard::CreditCard(string & no, string & nm, int lim, double bal = 0)
{
this->number = no; //you can also use number = no
this->limit = lim;
this->name = nm;
this->balance = bal;
}
```
Now, as we have a credit card we may want to know the name of the card, so this can be implemented as follows:
```
string CreditCard::getName();
{
return name;
}
```
The same way we can get the limits and number. I will leave that for you. |
34,102,231 | Good evening!
I'm a beginner programmer and am finishing up my first semester of C++. Currently I'm looking a final exam review sheet my professor gave us and I just don't understand exactly what it's asking me to do. I feel like if I saw an example I would get it immediately but as is I am rather lost.
Here's the review question.
```
Problem: Given the following class definition, implement the class methods.
class CreditCard {
public:
CreditCard(string & no, string & nm, int lim, double bal = 0);
string getNumber();
string getName();
double getBalance();
int getLimit();
// Does the card have enough to buy something?
bool chargelt(double price);
private:
string number;
string name;
int limit;
double balance;
};
```
I know there isn't much context here, but let's just say in the context of this being a introductory C++ course, what is likely asking me to do/learn? I'm really not sure what "implement the class methods" means here, and while it may be something that I've seen already, more than likely it's just an issue I have with not understanding it in plain English.
And I suppose it can also be asked that: If you were to teach an beginner student with this code, what would you expect them to do with it or learn from it?
Any insight would be greatly appreciated =) | 2015/12/05 | [
"https://Stackoverflow.com/questions/34102231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5026229/"
] | Strictly speaking, the C++ language doesn't have "methods". It has "member functions", and perhaps that's the terminology that you're more familiar with. But many other languages do use the term "method", so it's actually fairly common for C++ programmers to say "methods" when what they're really talking about is member functions.
The class definition shows that the class defines four member functions:
```
string getNumber();
string getName();
double getBalance();
int getLimit();
```
The definition also shows that there is a constructor:
```
CreditCard(string & no, string & nm, int lim, double bal = 0);
```
A constructor is also a type of member function, but most people don't refer to constructors as "methods". Some probably do, though.
So, the instruction "implement the class methods" means: "write the code for the member functions `getNumber()` `getName()` `getBalance()` and `getLimit()`."
It might also mean "and write the code for the constructor, `CreditCard(string & no, string & nm, int lim, double bal)`", too. | This code is the definition of a class, the blueprint of an object. It is an introduction to the strong object-oriented programming of C++ and contains some key concepts.
You have the elements of a basic object.
```
class CreditCard {
public:
// Constructor.(to construct an object).
CreditCard(string & no, string & nm, int lim, double bal = 0);
// Accessors (to access the attributes of the object).
string getNumber();
string getName();
double getBalance();
int getLimit();
// Does the card have enough to buy something?
/// A public method of the class.
bool chargelt(double price);
private:
// Attributes.
string number;
string name;
int limit;
double balance;
}
```
The term *implement* means that you have to *create* the functions that you defined for the class. Usually, for each class, one will make a header file for the definition and a source file for the implementation, but you can make it on the same page too.
The implementation of a method can follow this template :
```
string CreditCard::getNumber()
{
return number; // Instructions as you're making a standard function.
}
```
For the constructor, it is important that you initialize the attributes of the object. So, in your implementation of the constructor, you have to associate the input parameters to the attributes. Notethat you don't need to return any value since the created object can be seen as the "returned value". |
20,950,967 | I know that `UNIQUE` can be used for unique value on table creating.
I read in a database management book that
>
> When we apply UNIQUE to a subquery, the
> resulting condition returns true if no row appears twice in the answer to the
> subquery that is, there are no duplicates; in particular, it returns true if the
> answer is empty.
>
>
>
I didn't see any query like that ,Is it possible? | 2014/01/06 | [
"https://Stackoverflow.com/questions/20950967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2040375/"
] | `UNIQUE` is defined by *SQL92* Section 8.9: `<unique predicate> ::= UNIQUE <table subquery>` so it certainly exists but is not widely supported by vendors.
As an alternative you could use EXISTS with a HAVING COUNT. | The UNIQUE constraint is typically used for defining table based constraints.
You should consider using `Select Distinct` for queries.
The following link provides details regarding the `Unique` and `Distinct` keywords.
<http://psoug.org/definition/DISTINCT.htm> |
37,866,905 | I'm wondering in which format the compiled source code of an program written (in C or Rust for example) will result.
I know that the output file is a binary coded file in machine language (like every handbook and documentation explains). I thought that opening the file with an editor of my choice like VIM should show me a lot of 1s and 0s, right? But every time I search the web for that topic, I only find how to open a binary file in VI in hex (mostly using 'xxd').
Isn't there a way to see the binary file like a binary file? --> 100101101111
What is the format of an compiled program? | 2016/06/16 | [
"https://Stackoverflow.com/questions/37866905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2349787/"
] | Found the solution:
```
OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();
```
If we use the builder to input the proxy, it will work like a charm =D | okhttp version:`3.11.0`. SOCKS proxy example
```
String hostname = "localhost"/*127.0.0.1*/;
int port = 1080;
Proxy proxy = new Proxy(Proxy.Type.SOCKS,
new InetSocketAddress(hostname, port));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.build();
``` |
37,866,905 | I'm wondering in which format the compiled source code of an program written (in C or Rust for example) will result.
I know that the output file is a binary coded file in machine language (like every handbook and documentation explains). I thought that opening the file with an editor of my choice like VIM should show me a lot of 1s and 0s, right? But every time I search the web for that topic, I only find how to open a binary file in VI in hex (mostly using 'xxd').
Isn't there a way to see the binary file like a binary file? --> 100101101111
What is the format of an compiled program? | 2016/06/16 | [
"https://Stackoverflow.com/questions/37866905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2349787/"
] | Found the solution:
```
OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();
```
If we use the builder to input the proxy, it will work like a charm =D | SOCKS5 Auth example
I think it's the easiest working soulution. But it seems to me that it can be not 100% safe. I took this code from this code [from here](https://stackoverflow.com/a/16340273/9466638) and modified it because my proxy's RequestorType is SERVER.
Actually, java has a strange api for proxies, you should to set auth for proxy through system env ( you can see it from the same link)
```
final int proxyPort = 1080; //your proxy port
final String proxyHost = "your proxy host";
final String username = "proxy username";
final String password = "proxy password";
InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestingHost().equalsIgnoreCase(proxyHost)) {
if (proxyPort == getRequestingPort()) {
return new PasswordAuthentication(username, password.toCharArray());
}
}
return null;
}
});
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.build();
``` |
19,280,494 | ```
<html>
<head></head>
<body>
<h1>Welcome to Our Website!</h1>
<hr/>
<h2>News</h2>
<h4><?=$data['title'];?></h4>
<p><?=$data['content'];?></p>
</body>
</html>
```
Can anyone tell me what's the "=" sign before variable names ? I thought of some echo alias but I couldn't find anything, thanks for your help | 2013/10/09 | [
"https://Stackoverflow.com/questions/19280494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2802552/"
] | `<?=$a?>` is the shortcut for `<? echo $a ?>`, they are called "short tags" in PHP terminology
Check PHP documentation [Escaping from HTML](http://www.php.net/manual/en/language.basic-syntax.phpmode.php) example #2 3rd item, and related ini setting [short-open-tag](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag) | This tag is interpreted as `<?php echo`.
You can check it by writing `<?= ?>`, you'll receive error. |
576,538 | So, a little background. I work for a company that has a number of extremely important, non-public facing websites. People's safety and livelihoods depend on these staying up. We have very little downtime, but there are always catastrophic situations that mean restoring from bare metal.
Our current setup is inadequate, but I'd like opinions on what I see as the potential options. We host everything internally on an incredibly nice vSphere setup. Right now, we have one monstrous Ubuntu instance that hosts everything--all sites, databases, assets, et cetera.
We backup every way you can imagine, and one of the benefits of the vSphere setup is that we can restore offsite if we have to, but having one massive machine means the restore time isn't insignificant.
I see two roads I can head down.
1. Simple redundancy. Migrating from this one machine to a web server, a SAN and a database server, and then either having redundant machines ready full time, or be able to spin them up quickly. This is what I'd traditionally expect to exist, but I don't know that it helps us that much. Restoring offsite means taking hours to get *all* sites back up, and it seems difficult to restore in a way that I could give preference to the most mission critical things. Internally, with vSphere, this doesn't seem like a massive advantage. But, this is fairly easy to maintain.
2. Split everything up with vSphere. Each site could be its own vSphere instance (or small set of vSphere instances to split out database/assets). This means more work maintaining a number of small servers instead of the one monolithic one, but it also means I could easily choose to restore Site A and Site B in a catastrophic situation, and leave the non-mission critical things for later. This also allows things to diverge software wise where necessary, which is both a positive thing and a negative thing.
Opinions? Am I ignoring an obvious option? | 2014/02/18 | [
"https://serverfault.com/questions/576538",
"https://serverfault.com",
"https://serverfault.com/users/209899/"
] | * Leverage VMware SRM, or at least VMware Replication. It will drastically reduce the amount of time it takes you to come online in a secondary datacenter. (Hyper-V Replica and HVRM are the equivalent in the Microsoft stack.
* Separate your front-end from your back-end. It sounds like you need a web tier and a database tier.
* Invest in proper load balancing for your front end. This can mean installing and configuring a multi-site Netscalar cluster, or configuring something like HAProxy.
* Introduce redundancy in your database tier. You don't mention which DB product you're using, but many have high availability, replication, clustering, etc available. Use this.
* Make your DR site a "warm site" where you have some servers running constantly, such as database mirrors. Then you don't have to restore them in a disaster, you just make them the active node.
vSphere makes backup and recovery easier by abstracting the hardware away, but it's no substitute for tried and true HA methods when availability is critical.
There's no reason to have a single vSphere instance per-website. This doesn't gain you anything. | I've seen the second setup more often than the first, especially when your DR site doesn't have the same capacity as your primary site. However, I think this question isn't really appropriate for SF, since it's very much opinion based (although I'm not going to flag it as such since I see some value to the question). |
54,910,019 | I am new to Angular and I have two collapse div elements and when I click on button1 then div element-1 need to collapse and element-2 need to be hide.
And when I click button2 then div element-2 need to collapse and element-1 need to be hide, but it's not working using below code.
```
<div class="container">
<h2>Simple Collapsible</h2>
<button type="button" class="btn btn-info" (click)="selectItem='one'" data-toggle="collapse" data-target="#demo1">Simple
collapsible</button>
<button type="button" class="btn btn-info" (click)="selectItem='two'" data-toggle="collapse" data-target="#demo2">Simple
collapsible</button>
<div [ngClass]="(selectItem=='one')?'visiable':'hide'">
<div id="demo1" class="collapse">
<h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</h2>
</div>
</div>
<div [ngClass]="(selectItem=='two')?'visiable':'hide'">
<div id="demo2" class="collapse">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
```
<https://stackblitz.com/edit/angular5-bootstrap4-crud-device-list-simple-zxunj1?file=app%2Fapp.component.html> | 2019/02/27 | [
"https://Stackoverflow.com/questions/54910019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5571461/"
] | Try using single quote marks inside the ternary
```
<div
class='@(Model.HeroBannerImageSmall ? "--imageSmall" : "--image")'
style='@(Model.isSelected ? "background-position-x:@Model.CropPositionX" % "background-position-y:@Model.CropPositionY"&; : "background-position:@Model.UniformCropPosition"&;')
background-image: url(@Model.ContentUrl)'>
</div>
``` | You've gotta mix and match your single and double quotes to make this work! For example:
```
class='@(Model.HeroBannerImageSmall ? "--imageSmall" : "--image")'
```
Potentially might be easier to read if you pulled it out into a code branch ahead of the div. ie:
```
@{
var imageClass = Model.HeroBannerImageSmall ? "--imageSmall" : "--image";
var imgageStyle = Model.isSelected ?
"background-position-x: " + Model.CropPositionX + "% background-position-y: " + Model.CropPositionY + "%;" :
"background-position: " + Model.UniformCropPosition + "%; ";
imgageStyle += "background-image: url(" + Model.ContentUrl + ")";
}
class='@imageClass' style='@imageStyle'
``` |
50,574,593 | I am trying to do a simple thing , navigate to an external url
```
<a href="http://18.217.228.108/angularapp1/book/"> Class Books </a>
```
However I am getting a 404 because the Http// portion is being deleted I am not sure if this is an mvc thing or html thing. Here is link <http://18.217.228.108/angularapp1>.
Here is a link to a screen shot of me accessing url
<https://gyazo.com/455b01f1ceded24f9b4ce6c58b0e10e1> | 2018/05/28 | [
"https://Stackoverflow.com/questions/50574593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8066170/"
] | I do not agree to the formula "after certain number of words".
Note that the first target line has 4 words, whereas remaining 2 have
5 words each.
Actually you need to replace each comma and following sequence of
spaces (if any) with a comma and `\n`.
So the intuitive way to do it is:
```
$x =~ s/,\s*/,\n/g;
``` | You probably want to use regular expressions. You can do this:
```
$x =~ s/^(\S+\s+){3}\K/\n/;
```
Or if this is about the commas and not the spaces:
```
$x =~ s/^([^,]+,+){2}\s*\K/\n/;
```
(in this case I also remove any potential space that would be after the comma)
You can also configure separately how many words or comma you want, by putting this in a variable:
```
my $nbwords = 7; # add a line after the 7th word
$x =~ s/^(\S+\s+){$nbwords}\K/\n/;
```
Now, that would keep the last space so you may want to do this:
```
my $nbwords = 7; # add a line after the 7th word
$nbwords--; # becomes 6 because there is another word after that we match as well
$x =~ s/^(\S+\s+){$nbwords}\S+\K\s+/\n/;
```
You should probably learn to use Regexps but just to explain the above:
* \s is any space character (like space, tab, line feed, etc)
* \S (uppercase) is any character except a space character
* + means any number of characters of that type described with what is before. So \s+ means any number of consecutive space characters.
* {123} means 123 times that type of character ...
* {3,80} means 3 to 80 times. So + is equivalent to {1,} (one to unlimited)
* \K means that whatever is before will not be replaced, only what is after. |
50,574,593 | I am trying to do a simple thing , navigate to an external url
```
<a href="http://18.217.228.108/angularapp1/book/"> Class Books </a>
```
However I am getting a 404 because the Http// portion is being deleted I am not sure if this is an mvc thing or html thing. Here is link <http://18.217.228.108/angularapp1>.
Here is a link to a screen shot of me accessing url
<https://gyazo.com/455b01f1ceded24f9b4ce6c58b0e10e1> | 2018/05/28 | [
"https://Stackoverflow.com/questions/50574593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8066170/"
] | The simplest way is to split the string on `comma followed by a space` and then
join the word groups with a `comma followed by a newline`.
```
my $x = "This a variable, start a new line here, This is a new line.";
print join(",\n", split /, /, $x) . "\n";
```
**output**
```
This a variable,
start a new line here,
This is a new line.
```
---
For solving the general, `how do I reformat this string with line breaks after n-columns?` problem, use the [Text::Wrap](https://perldoc.perl.org/Text/Wrap.html) library (as suggested by @ikegami):
```
use Text::Wrap;
my $x = "The quick brown fox jumped over the lazy dog.";
$Text::Wrap::columns = 15;
# wrap() needs an array of words
my @words = split /\s+/, $x;
# Initial tab, subsequent tab values set to '' (think indent amount)
print wrap('', '', @words) . "\n";
```
**output**
```
The quick
brown fox
jumped over
the lazy dog.
``` | You probably want to use regular expressions. You can do this:
```
$x =~ s/^(\S+\s+){3}\K/\n/;
```
Or if this is about the commas and not the spaces:
```
$x =~ s/^([^,]+,+){2}\s*\K/\n/;
```
(in this case I also remove any potential space that would be after the comma)
You can also configure separately how many words or comma you want, by putting this in a variable:
```
my $nbwords = 7; # add a line after the 7th word
$x =~ s/^(\S+\s+){$nbwords}\K/\n/;
```
Now, that would keep the last space so you may want to do this:
```
my $nbwords = 7; # add a line after the 7th word
$nbwords--; # becomes 6 because there is another word after that we match as well
$x =~ s/^(\S+\s+){$nbwords}\S+\K\s+/\n/;
```
You should probably learn to use Regexps but just to explain the above:
* \s is any space character (like space, tab, line feed, etc)
* \S (uppercase) is any character except a space character
* + means any number of characters of that type described with what is before. So \s+ means any number of consecutive space characters.
* {123} means 123 times that type of character ...
* {3,80} means 3 to 80 times. So + is equivalent to {1,} (one to unlimited)
* \K means that whatever is before will not be replaced, only what is after. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | This doesn't fit case 3 exactly, but I don't know if any of your cases capture a very common problem used to teach dynamic programming: [Matrix Chain Multiplication](http://en.wikipedia.org/wiki/Matrix_chain_multiplication).
To solve this problem, (and many others, this is just the canonical one) we fill up the matrix diagonal by diagonal instead of row by row.
So the rule is something like this:
 | This is exactly not the search space you are looking for but i've an idea of the top of my head which might be of help.
**Problem :**
Given a $n × n$ matrix say, $M$ with distinct integers in which the entries of each row (from left to right) and each column (from top to bottom) are both sorted in increasing order and the entries in each column are in increasing order . Give an efficient algorithm to find the position of an integer $x$ in $M$ (or say the integer is not present in the matrix).
**Answer**
This can be solved in the following recursive way :
We have an n×n matrix. Let $k = \lceil{\frac{1+n}{2}}\rceil$. Now compare $x$ with
$m\_{k,k}$. If $x<m\_{k,k}$ we can discard any element $m\_{i,j}$ for $k\leq i\leq n$ and $k\leq j\leq n$ i.e., the search space is reduced by $1/4$. Similarly, when $x>m\_{k,k}$, the search space is reduced by $1/4$. So after the first iteration, the size of the search space becomes $\frac{3}{4} n^2$. You can do this recursively further as follows: we make 3 comparisons: $x$ with the middle element in each of the remaining three quadrants, and the size of the remaining search space then becomes $\left(\frac{3}{4}\right)^3 n^2$ and so on. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | There are plenty of other examples of dynamic programming algorithms that don't fit your pattern at all.
* The longest increasing subsequence problem requires only a one-dimensional table.
* There are several natural dynamic programming algorithms whose tables require three or even more dimensions. For example: Find the maximum-area white rectangle in a bitmap. The natural dynamic programming algorithm uses a three-dimensional table.
* But most importantly, **dynamic programming isn't about tables**; it's about unwinding recursion. There are lots of natural dynamic programming algorithms where the data structure used to store intermediate results is not an array, because the recurrence being unwound isn't over a range of integers. Two easy examples are finding the largest independent set of vertices in a tree, and finding the largest common subtree of two trees. A more complex example is the $(1+\epsilon)$-approximation algorithm for the Euclidean traveling salesman problem by Arora and Mitchell. | This is exactly not the search space you are looking for but i've an idea of the top of my head which might be of help.
**Problem :**
Given a $n × n$ matrix say, $M$ with distinct integers in which the entries of each row (from left to right) and each column (from top to bottom) are both sorted in increasing order and the entries in each column are in increasing order . Give an efficient algorithm to find the position of an integer $x$ in $M$ (or say the integer is not present in the matrix).
**Answer**
This can be solved in the following recursive way :
We have an n×n matrix. Let $k = \lceil{\frac{1+n}{2}}\rceil$. Now compare $x$ with
$m\_{k,k}$. If $x<m\_{k,k}$ we can discard any element $m\_{i,j}$ for $k\leq i\leq n$ and $k\leq j\leq n$ i.e., the search space is reduced by $1/4$. Similarly, when $x>m\_{k,k}$, the search space is reduced by $1/4$. So after the first iteration, the size of the search space becomes $\frac{3}{4} n^2$. You can do this recursively further as follows: we make 3 comparisons: $x$ with the middle element in each of the remaining three quadrants, and the size of the remaining search space then becomes $\left(\frac{3}{4}\right)^3 n^2$ and so on. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | I know its a silly example, but I think a simple iterative problem like
>
> Find the sum of the numbers in a square matrix
>
>
>
might qualify. The the traditional "for each row for each column" kinda looks like your case 3. | This is exactly not the search space you are looking for but i've an idea of the top of my head which might be of help.
**Problem :**
Given a $n × n$ matrix say, $M$ with distinct integers in which the entries of each row (from left to right) and each column (from top to bottom) are both sorted in increasing order and the entries in each column are in increasing order . Give an efficient algorithm to find the position of an integer $x$ in $M$ (or say the integer is not present in the matrix).
**Answer**
This can be solved in the following recursive way :
We have an n×n matrix. Let $k = \lceil{\frac{1+n}{2}}\rceil$. Now compare $x$ with
$m\_{k,k}$. If $x<m\_{k,k}$ we can discard any element $m\_{i,j}$ for $k\leq i\leq n$ and $k\leq j\leq n$ i.e., the search space is reduced by $1/4$. Similarly, when $x>m\_{k,k}$, the search space is reduced by $1/4$. So after the first iteration, the size of the search space becomes $\frac{3}{4} n^2$. You can do this recursively further as follows: we make 3 comparisons: $x$ with the middle element in each of the remaining three quadrants, and the size of the remaining search space then becomes $\left(\frac{3}{4}\right)^3 n^2$ and so on. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | Computing Ackermann function is in this spirit. To compute $A(m,n)$ you need to know $A(m,n-1)$ and $A(m-1,k)$ for some large $k$. Either the second coordinate decreases, or the first decreases, and second potentially increases.
This does not ideally fit the requirements, since the number of columns is infinite, and the computation is usually done top-down with memorization, but I think it is worth to mention. | This is exactly not the search space you are looking for but i've an idea of the top of my head which might be of help.
**Problem :**
Given a $n × n$ matrix say, $M$ with distinct integers in which the entries of each row (from left to right) and each column (from top to bottom) are both sorted in increasing order and the entries in each column are in increasing order . Give an efficient algorithm to find the position of an integer $x$ in $M$ (or say the integer is not present in the matrix).
**Answer**
This can be solved in the following recursive way :
We have an n×n matrix. Let $k = \lceil{\frac{1+n}{2}}\rceil$. Now compare $x$ with
$m\_{k,k}$. If $x<m\_{k,k}$ we can discard any element $m\_{i,j}$ for $k\leq i\leq n$ and $k\leq j\leq n$ i.e., the search space is reduced by $1/4$. Similarly, when $x>m\_{k,k}$, the search space is reduced by $1/4$. So after the first iteration, the size of the search space becomes $\frac{3}{4} n^2$. You can do this recursively further as follows: we make 3 comparisons: $x$ with the middle element in each of the remaining three quadrants, and the size of the remaining search space then becomes $\left(\frac{3}{4}\right)^3 n^2$ and so on. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | There are plenty of other examples of dynamic programming algorithms that don't fit your pattern at all.
* The longest increasing subsequence problem requires only a one-dimensional table.
* There are several natural dynamic programming algorithms whose tables require three or even more dimensions. For example: Find the maximum-area white rectangle in a bitmap. The natural dynamic programming algorithm uses a three-dimensional table.
* But most importantly, **dynamic programming isn't about tables**; it's about unwinding recursion. There are lots of natural dynamic programming algorithms where the data structure used to store intermediate results is not an array, because the recurrence being unwound isn't over a range of integers. Two easy examples are finding the largest independent set of vertices in a tree, and finding the largest common subtree of two trees. A more complex example is the $(1+\epsilon)$-approximation algorithm for the Euclidean traveling salesman problem by Arora and Mitchell. | This doesn't fit case 3 exactly, but I don't know if any of your cases capture a very common problem used to teach dynamic programming: [Matrix Chain Multiplication](http://en.wikipedia.org/wiki/Matrix_chain_multiplication).
To solve this problem, (and many others, this is just the canonical one) we fill up the matrix diagonal by diagonal instead of row by row.
So the rule is something like this:
 |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | This doesn't fit case 3 exactly, but I don't know if any of your cases capture a very common problem used to teach dynamic programming: [Matrix Chain Multiplication](http://en.wikipedia.org/wiki/Matrix_chain_multiplication).
To solve this problem, (and many others, this is just the canonical one) we fill up the matrix diagonal by diagonal instead of row by row.
So the rule is something like this:
 | I know its a silly example, but I think a simple iterative problem like
>
> Find the sum of the numbers in a square matrix
>
>
>
might qualify. The the traditional "for each row for each column" kinda looks like your case 3. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | There are plenty of other examples of dynamic programming algorithms that don't fit your pattern at all.
* The longest increasing subsequence problem requires only a one-dimensional table.
* There are several natural dynamic programming algorithms whose tables require three or even more dimensions. For example: Find the maximum-area white rectangle in a bitmap. The natural dynamic programming algorithm uses a three-dimensional table.
* But most importantly, **dynamic programming isn't about tables**; it's about unwinding recursion. There are lots of natural dynamic programming algorithms where the data structure used to store intermediate results is not an array, because the recurrence being unwound isn't over a range of integers. Two easy examples are finding the largest independent set of vertices in a tree, and finding the largest common subtree of two trees. A more complex example is the $(1+\epsilon)$-approximation algorithm for the Euclidean traveling salesman problem by Arora and Mitchell. | I know its a silly example, but I think a simple iterative problem like
>
> Find the sum of the numbers in a square matrix
>
>
>
might qualify. The the traditional "for each row for each column" kinda looks like your case 3. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | There are plenty of other examples of dynamic programming algorithms that don't fit your pattern at all.
* The longest increasing subsequence problem requires only a one-dimensional table.
* There are several natural dynamic programming algorithms whose tables require three or even more dimensions. For example: Find the maximum-area white rectangle in a bitmap. The natural dynamic programming algorithm uses a three-dimensional table.
* But most importantly, **dynamic programming isn't about tables**; it's about unwinding recursion. There are lots of natural dynamic programming algorithms where the data structure used to store intermediate results is not an array, because the recurrence being unwound isn't over a range of integers. Two easy examples are finding the largest independent set of vertices in a tree, and finding the largest common subtree of two trees. A more complex example is the $(1+\epsilon)$-approximation algorithm for the Euclidean traveling salesman problem by Arora and Mitchell. | Computing Ackermann function is in this spirit. To compute $A(m,n)$ you need to know $A(m,n-1)$ and $A(m-1,k)$ for some large $k$. Either the second coordinate decreases, or the first decreases, and second potentially increases.
This does not ideally fit the requirements, since the number of columns is infinite, and the computation is usually done top-down with memorization, but I think it is worth to mention. |
196 | I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems? | 2012/03/10 | [
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] | Computing Ackermann function is in this spirit. To compute $A(m,n)$ you need to know $A(m,n-1)$ and $A(m-1,k)$ for some large $k$. Either the second coordinate decreases, or the first decreases, and second potentially increases.
This does not ideally fit the requirements, since the number of columns is infinite, and the computation is usually done top-down with memorization, but I think it is worth to mention. | I know its a silly example, but I think a simple iterative problem like
>
> Find the sum of the numbers in a square matrix
>
>
>
might qualify. The the traditional "for each row for each column" kinda looks like your case 3. |
28,872,375 | ```
SQL> desc invoices
Name Null? Type
----------------------------------------- -------- ----------------------------
INVOICE_ID NOT NULL NUMBER(6)
COMPANY_ID NUMBER(6)
STUDENT_ID NUMBER(6)
BILLING_DATE DATE
SQL>
```
I would like to insert some sample data into this table. The `company_id` and `student_id` are foreign keys. This is what I'am entering:
`INSERT INTO invoices
VALUES (SEQ_INVOICE.NEXTVAL,[what1],[what2],SYSDATE);`
I don't know what I am supposed to put in the what1 and what2
```
SQL> desc companies
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPANY_ID NOT NULL NUMBER(6)
COMPANY_NAME VARCHAR2(30)
ADDRESS VARCHAR2(128)
CONTACT_NO VARCHAR2(11)
NO_OF_EMP NUMBER(10)
SQL>
SQL> desc students
Name Null? Type
----------------------------------------- -------- ----------------------------
STUDENT_ID NOT NULL NUMBER(6)
ST_FNAME VARCHAR2(16)
ST_SNAME VARCHAR2(16)
ADDRESS VARCHAR2(128)
DOB DATE
SQL>
``` | 2015/03/05 | [
"https://Stackoverflow.com/questions/28872375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592364/"
] | you have to enter an existed `STUDENT_ID` from `students` table and an existed `COMPANY_ID` from `compaies` table to invoices.
Consider you have data like next
```
COMPANY_ID COMPANY_NAME ADDRESS CONTACT_NO NO_OF_EMP
----------- ------------ -------- ---------- ---------
1 Blah LLC blah st. 123456 100
2 My Company My Street 987654321 50
```
and
```
STUDENT_ID ST_FNAME ST_SNAME ADDRESS DOB
----------- --------- --------- -------- ------------
11 Jim Carrey .... 1900.25.04
22 Jack Sparrow Carrib st. 1700.30.08
```
then you can use `1` or `2` as `COMPANY_ID` (in your query [what1]) and `11` or `22` as `STUDENT_ID` (in your query [what2]) | You need to first enter companies in "companies", and students in "students". Then use those ID's for [what1] and [what2] |
28,872,375 | ```
SQL> desc invoices
Name Null? Type
----------------------------------------- -------- ----------------------------
INVOICE_ID NOT NULL NUMBER(6)
COMPANY_ID NUMBER(6)
STUDENT_ID NUMBER(6)
BILLING_DATE DATE
SQL>
```
I would like to insert some sample data into this table. The `company_id` and `student_id` are foreign keys. This is what I'am entering:
`INSERT INTO invoices
VALUES (SEQ_INVOICE.NEXTVAL,[what1],[what2],SYSDATE);`
I don't know what I am supposed to put in the what1 and what2
```
SQL> desc companies
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPANY_ID NOT NULL NUMBER(6)
COMPANY_NAME VARCHAR2(30)
ADDRESS VARCHAR2(128)
CONTACT_NO VARCHAR2(11)
NO_OF_EMP NUMBER(10)
SQL>
SQL> desc students
Name Null? Type
----------------------------------------- -------- ----------------------------
STUDENT_ID NOT NULL NUMBER(6)
ST_FNAME VARCHAR2(16)
ST_SNAME VARCHAR2(16)
ADDRESS VARCHAR2(128)
DOB DATE
SQL>
``` | 2015/03/05 | [
"https://Stackoverflow.com/questions/28872375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592364/"
] | you have to enter an existed `STUDENT_ID` from `students` table and an existed `COMPANY_ID` from `compaies` table to invoices.
Consider you have data like next
```
COMPANY_ID COMPANY_NAME ADDRESS CONTACT_NO NO_OF_EMP
----------- ------------ -------- ---------- ---------
1 Blah LLC blah st. 123456 100
2 My Company My Street 987654321 50
```
and
```
STUDENT_ID ST_FNAME ST_SNAME ADDRESS DOB
----------- --------- --------- -------- ------------
11 Jim Carrey .... 1900.25.04
22 Jack Sparrow Carrib st. 1700.30.08
```
then you can use `1` or `2` as `COMPANY_ID` (in your query [what1]) and `11` or `22` as `STUDENT_ID` (in your query [what2]) | [what1] is ID of COMPANY\_ID
[what2] is ID of STUDENT\_ID
if table Student and Company are empty, you must Insert the record to both tables before Insert |
20,319,813 | In my for loop, my code generates a list like this one:
```
list([0.0,0.0]/sum([0.0,0.0]))
```
The loop generates all sort of other number vectors but it also generates `[nan,nan]`, and to avoid it I tried to put in a conditional to prevent it like the one below, but it doesn't return true.
```
nan in list([0.0,0.0]/sum([0.0,0.0]))
>>> False
```
Shouldn't it return true?

Libraries I've loaded:
```
import PerformanceAnalytics as perf
import DataAnalyticsHelpers
import DataHelpers as data
import OptimizationHelpers as optim
from matplotlib.pylab import *
from pandas.io.data import DataReader
from datetime import datetime,date,time
import tradingWithPython as twp
import tradingWithPython.lib.yahooFinance as data_downloader # used to get data from yahoo finance
import pandas as pd # as always.
import numpy as np
import zipline as zp
from scipy.optimize import minimize
from itertools import product, combinations
import time
from math import isnan
``` | 2013/12/02 | [
"https://Stackoverflow.com/questions/20319813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] | I think this makes sense because of your pulling `numpy` into scope indirectly via the star import.
```
>>> import numpy as np
>>> [0.0,0.0]/0
Traceback (most recent call last):
File "<ipython-input-3-aae9e30b3430>", line 1, in <module>
[0.0,0.0]/0
TypeError: unsupported operand type(s) for /: 'list' and 'int'
>>> [0.0,0.0]/np.float64(0)
array([ nan, nan])
```
When you did
```
from matplotlib.pylab import *
```
it pulled in `numpy.sum`:
```
>>> from matplotlib.pylab import *
>>> sum is np.sum
True
>>> [0.0,0.0]/sum([0.0, 0.0])
array([ nan, nan])
```
You can test that **this** `nan` object (`nan` isn't unique in general) is in a list via identity, but if you try it in an `array` it seems to test via equality, and `nan != nan`:
```
>>> nan == nan
False
>>> nan == nan, nan is nan
(False, True)
>>> nan in [nan]
True
>>> nan in np.array([nan])
False
```
You could use `np.isnan`:
```
>>> np.isnan([nan, nan])
array([ True, True], dtype=bool)
>>> np.isnan([nan, nan]).any()
True
``` | You should use the [`math`](http://docs.python.org/2/library/math.html) module.
```
>>> import math
>>> math.isnan(item)
``` |
20,319,813 | In my for loop, my code generates a list like this one:
```
list([0.0,0.0]/sum([0.0,0.0]))
```
The loop generates all sort of other number vectors but it also generates `[nan,nan]`, and to avoid it I tried to put in a conditional to prevent it like the one below, but it doesn't return true.
```
nan in list([0.0,0.0]/sum([0.0,0.0]))
>>> False
```
Shouldn't it return true?

Libraries I've loaded:
```
import PerformanceAnalytics as perf
import DataAnalyticsHelpers
import DataHelpers as data
import OptimizationHelpers as optim
from matplotlib.pylab import *
from pandas.io.data import DataReader
from datetime import datetime,date,time
import tradingWithPython as twp
import tradingWithPython.lib.yahooFinance as data_downloader # used to get data from yahoo finance
import pandas as pd # as always.
import numpy as np
import zipline as zp
from scipy.optimize import minimize
from itertools import product, combinations
import time
from math import isnan
``` | 2013/12/02 | [
"https://Stackoverflow.com/questions/20319813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] | You should use the [`math`](http://docs.python.org/2/library/math.html) module.
```
>>> import math
>>> math.isnan(item)
``` | May be this is what you are looking for...
```
a = [2,3,np.nan]
b = True if True in np.isnan(np.array(a)) else False
print(b)
``` |
20,319,813 | In my for loop, my code generates a list like this one:
```
list([0.0,0.0]/sum([0.0,0.0]))
```
The loop generates all sort of other number vectors but it also generates `[nan,nan]`, and to avoid it I tried to put in a conditional to prevent it like the one below, but it doesn't return true.
```
nan in list([0.0,0.0]/sum([0.0,0.0]))
>>> False
```
Shouldn't it return true?

Libraries I've loaded:
```
import PerformanceAnalytics as perf
import DataAnalyticsHelpers
import DataHelpers as data
import OptimizationHelpers as optim
from matplotlib.pylab import *
from pandas.io.data import DataReader
from datetime import datetime,date,time
import tradingWithPython as twp
import tradingWithPython.lib.yahooFinance as data_downloader # used to get data from yahoo finance
import pandas as pd # as always.
import numpy as np
import zipline as zp
from scipy.optimize import minimize
from itertools import product, combinations
import time
from math import isnan
``` | 2013/12/02 | [
"https://Stackoverflow.com/questions/20319813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] | I think this makes sense because of your pulling `numpy` into scope indirectly via the star import.
```
>>> import numpy as np
>>> [0.0,0.0]/0
Traceback (most recent call last):
File "<ipython-input-3-aae9e30b3430>", line 1, in <module>
[0.0,0.0]/0
TypeError: unsupported operand type(s) for /: 'list' and 'int'
>>> [0.0,0.0]/np.float64(0)
array([ nan, nan])
```
When you did
```
from matplotlib.pylab import *
```
it pulled in `numpy.sum`:
```
>>> from matplotlib.pylab import *
>>> sum is np.sum
True
>>> [0.0,0.0]/sum([0.0, 0.0])
array([ nan, nan])
```
You can test that **this** `nan` object (`nan` isn't unique in general) is in a list via identity, but if you try it in an `array` it seems to test via equality, and `nan != nan`:
```
>>> nan == nan
False
>>> nan == nan, nan is nan
(False, True)
>>> nan in [nan]
True
>>> nan in np.array([nan])
False
```
You could use `np.isnan`:
```
>>> np.isnan([nan, nan])
array([ True, True], dtype=bool)
>>> np.isnan([nan, nan]).any()
True
``` | May be this is what you are looking for...
```
a = [2,3,np.nan]
b = True if True in np.isnan(np.array(a)) else False
print(b)
``` |
109,317 | I have been reading quite a bit in order to make the following choice: which path-finding solution should one implement in a game where the world proceduraly generated, of really large dimensions?
Here is how I see the main solutions and their pros/cons:
1) grid-based path-finding - this is the only option that would not require any pre-processing, which fits well. However, as the world expands, memory used grows exponentially up to insane levels. This can be handled in terms of processing paths, trough solutions such as the Block A\* or Subgoal A\* algorithms. However, the memory usage is the problem difficult to circumvent;
2) navmesh - this would be lovely to have, due to its precision, fast path calculation and low memory usage. However, it can take an obscene pre-processing time.
3) visibility graph - this option also needs high pre-processing time, although it can be lessened by the use of fast pre-processing algorithms. Then, path calculation is generally fast too. But memory usage can get even more insane than grid-based depending on the configuration of the procedural world.
So, what would be best approach (others not present in this list are also welcome) for such a situation? Are there techniques or tricks that can be used to handle procedural infinite-like worlds?
Suggestions, ideas and references are all welcome.
EDIT:
Just to give more details, one should see the application I am talking about as a very very large office level, where rooms are generated prodecuraly. The algorithm works like the following. First, rooms are placed. Next, walls. Then the doors and later the furniture/obstacles that go in each room. So, the environment can get really huge and with lots of objects, since new rooms are generated once the players approaches the boundary of the already generated area. It means that there will be not large open areas without obstacles. | 2015/10/06 | [
"https://gamedev.stackexchange.com/questions/109317",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/72314/"
] | Given that the rooms are procedural built, portals created and then populated, I have a couple of ideas.
A\* works really well on navigation meshes, and works hierarchically as well. I would consider building a pathfinding system that works at two levels - first, the room by room level, and second within each room, from portal to portal. I think you can do this during generation at an affordable rate. You only need to path from room to room once you enter it, so it's very affordable from a memory/cpu cost.
High level A\* can be done by creating a graph of each portal and room - a room is the node, and the 'path' or edge is the portal to another room. The cost of traversal has some options - it can be from the centre point of the room to the centre point of the other room, for example. Or you might want to make specific edges from portal to portal with real distances, which is more useful, I suspect. This let's you do high level pathfinding from room A to room B. Doors can be opened and closed, enabling or disabling specific paths, which is nice for certain types of game. Because it's room/portal based it should be pretty easy and affordable to calculate - just distance calculations and graph book keeping. The great thing about this is it reduces the pathfinding memory costs dramatically in large environments since you are doing only the room-to-room finding.
The harder part will be the low level A\* because it should be polygonal navigation mesh. If each room is square, you can start with a polygon. When you place obstacles, subtract the area occupied from the polygon, making holes in it. When it's all finished you'll want to tesselate it into triangles again, building up the graph. I don't think this is as slow as you think. The difficult part is performing the polygon hole cutting, which requires a good amount of book keeping on that kind of stuff, but it is well documented within half-edge structures, and established computer science graphics books. You can also perform this generation lazily, in a background graph, as you don't actual need the A\* results of this level until someone is in the room - the high level takes care of basic path planning for you. Someone may never even enter the room in a run, because the high level A\* never leads them there.
I know I have glossed over the low level navigation mesh generation, but I think it's one of those things you set your mind to and solve and then it's done. There are a bunch of libraries out there like CGAL (<http://www.cgal.org>) and others that can do this stuff, but really to get it going fast you might need to write it yourself so you only have the things you need.
Alternatively, you could make each room be a grid, and the obstacles fill up parts of the grid, and then do all the standard grid smoothing algorithms, but I like navmesh data as it is small and fast.
Hope that makes some sense. | I'm going to take a stab and recommend a **hierarchical pathfinding algorithm**, such as [**HPA\***](http://aigamedev.com/open/review/near-optimal-hierarchical-pathfinding/). Even though I'm not an expert in AI, I'm fairly confident in this guess because your generator sounds almost identical to [the one in a game I'm working on](https://github.com/cxong/cdogs-sdl/wiki/Classic%20Maps), i.e. I've thought about this problem a bit too.
HPA\* (Hierarchical Path-Finding A\*) is a method of optimising regular A\* by first clustering the map into areas that are inter-connected, then producing a high-level graph of those clusters. When pathfinding, A\* (or any pathfinding algorithm) is run on the high-level graph, then in each of the clusters that form the best high-level path. Apparently it's widely used in RTS games, where lots of units will need to navigate unique paths across a large map in real time, so this should give you an idea of how efficient this method is.
Here's an image from their paper; the left is the clusters with connecting nodes, and the right is the high-level graph:
[](https://i.stack.imgur.com/5anyR.png)
Fortunately for your generator, it is very suitable for this algorithm, because of the rooms that you place: this gives you half the clustering for free. Your high-level graph is essentially made up of all the doors of your rooms. So what HPA\* is for you is: find the series of rooms/doors I need to go through, and how to navigate every room in that sequence.
Some more neat things about this algorithm:
* A\* is slow because it has to find the complete path before returning any results; with HPA\*, you can find the high-level path plus the path for the first room, so you can follow it immediately and defer the paths for the rest of the rooms later. This makes the algorithm responsive.
* You can cache the pathfinding results between pairs of doors for each room, since paths that traverse but don't start or end in this room are guaranteed to follow one such path.
* You can have multiple levels in this hierarchy, although this is only useful for truly gigantic maps.
Do note that HPA\* is *near*-optimal. You can easily see why by imagining a room with so many obstacles that it takes a long time to get through it. For the same reason, you should watch out if a room has enough obstacles to effectively partition it - don't treat this room as a single cluster in the high-level graph.
For some other possible algorithms, you could try this question on [cstheory.SE](https://cstheory.stackexchange.com/q/11855), which lists a ton of them. |
44,179,585 | I have installed LAMP in CentOS 7
When I placed my files in the default directory (var/www/html in my case)
I receive the following when I access my page:
>
> Erreur : PB de connexion au serveur mysql de la langue : fr
> Erreur : PB de connexion � la base de donn�es de la langue : fr
> Erreur SQL : SELECT \* FROM parametres
> Access denied for user 'apache'@'localhost' (using password: NO)
>
>
>
The following is my config file:
```
$action = "action";
@error_reporting (E_ALL);
@setlocale(LC_TIME, 'french');
$host = "localhost";
$user = "";
$password = "" ;
//---> La langue utilisée (fr, en, ar)
global $lang ;
$lang = isset($_REQUEST["lang"])? $_REQUEST["lang"] : "";
switch($lang)
{
case "ar" : $lang = "ar" ; break;
case "en" : $lang = "en" ; break;
case "fr" : $lang = "fr" ; break;
default : $lang = "fr" ; //---> La langue par défaut
} //Fin switch
global $lang_param;
$lang_param = array
(
//---> principal = TRUE
"fr" => array(
"host" => "localhost" ,
"db" => "database_fr" ,
"user" => "user1" ,
"password" => "" ,
"chemin" => "fr" ,
"description" => "Langue française" ,
"short" => "Français" ,
),
//---> principal = FALSE
"en" => array(
"host" => "localhost" ,
"db" => "database_en" ,
"user" => "user1" ,
"password" => "" ,
"chemin" => "en" ,
"description" => "Langue anglaise" ,
"short" => "Anglais" ,
) ,
"ar" => array(
"host" => "localhost" ,
"db" => "database_ar" ,
"user" => "user1" ,
"password" => "" ,
"chemin" => "ar" ,
"description" => "Langue arabe" ,
"short" => "Arabe" ,
)
); //Fin $lang_param
//---> Se connecter
$r = @mysql_pconnect($lang_param[$lang]["host"], $lang_param[$lang] ["user"], $lang_param[$lang]["password"]);
if ($r==0)
{
echo "Erreur : PB de connexion au serveur mysql de la langue : $lang<br>";
} //Fsi
$r = @mysql_select_db($lang_param[$lang]["db"]);
if ($r==0) {
echo "Erreur : PB de connexion à la base de données de la langue : $lang<br>";
} //Fsi
```
How can I gain access for apache@localhost? | 2017/05/25 | [
"https://Stackoverflow.com/questions/44179585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8064758/"
] | It seems using a simple `import 'angular-ui-router'` works. | You can set `allowSyntheticDefaultImports` to true in your `tsconfig.json` to continue importing `import uibootstrap from 'angular-ui-bootstrap';` as if `angular-ui-bootstrap` had a default export.
```
"compilerOptions": {
"allowSyntheticDefaultImports": true
}
``` |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | I need the same functionality. At the moment I'm considering reading using data from NSLocale as default, but adding a setting in settings.app for user to customise this if it does not match.
This function is taken from [an answer to another question of mine](https://stackoverflow.com/questions/2639684/itunes-music-store-link-maker-how-to-search-from-within-my-app/2668190#2668190).
```
- (NSString *)getUserCountry
{
NSLocale *locale = [NSLocale currentLocale];
return [locale objectForKey: NSLocaleCountryCode];
}
``` | You should probably use
```
[[userDefaults dictionaryRepresentation] objectForKey:@"NSLocaleCode"];
```
This will return a language code like en\_US or en\_UK or en\_AU or even zh\_CN, zh\_MY, jp\_JP and so on.
Parse the correct codes which you support and direct them accordingly. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | The approach of getting the country code of the user's locale will work ... but only if the user's iTunes store is the same as their locale. This won't always be the case.
If you create an in-app purchase item, you can use Apple's StoreKit APIs to find out the user's actual iTunes country even if it's different from their device locale. Here's some code that worked for me:
```
- (void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:
[NSSet setWithObject: PRODUCT_ID]];
request.delegate = self;
[request start];
}
- (void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray *myProducts = response.products;
for (SKProduct* product in myProducts) {
NSLocale* storeLocale = product.priceLocale;
storeCountry = (NSString*)CFLocaleGetValue((CFLocaleRef)storeLocale, kCFLocaleCountryCode);
NSLog(@"Store Country = %@", storeCountry);
}
[request release];
// If product request didn't work, fallback to user's device locale
if (storeCountry == nil) {
CFLocaleRef userLocaleRef = CFLocaleCopyCurrent();
storeCountry = (NSString*)CFLocaleGetValue(userLocaleRef, kCFLocaleCountryCode);
}
// Now we're ready to start creating URLs for the itunes store
[super start];
}
``` | A hard way to get this function is to set up up a single app for every app store country. Each app holds it's own country store information. This assumes, that a user sticks to one store, which should be true for most people. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | I suggest you try iTunes [deep links](http://developer.apple.com/iphone/appstore/marketing.html#deeplinks). For example, <http://itunes.com/apps/appname> should take the user to the local App Store where she spends money. | You should probably use
```
[[userDefaults dictionaryRepresentation] objectForKey:@"NSLocaleCode"];
```
This will return a language code like en\_US or en\_UK or en\_AU or even zh\_CN, zh\_MY, jp\_JP and so on.
Parse the correct codes which you support and direct them accordingly. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | The approach of getting the country code of the user's locale will work ... but only if the user's iTunes store is the same as their locale. This won't always be the case.
If you create an in-app purchase item, you can use Apple's StoreKit APIs to find out the user's actual iTunes country even if it's different from their device locale. Here's some code that worked for me:
```
- (void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:
[NSSet setWithObject: PRODUCT_ID]];
request.delegate = self;
[request start];
}
- (void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray *myProducts = response.products;
for (SKProduct* product in myProducts) {
NSLocale* storeLocale = product.priceLocale;
storeCountry = (NSString*)CFLocaleGetValue((CFLocaleRef)storeLocale, kCFLocaleCountryCode);
NSLog(@"Store Country = %@", storeCountry);
}
[request release];
// If product request didn't work, fallback to user's device locale
if (storeCountry == nil) {
CFLocaleRef userLocaleRef = CFLocaleCopyCurrent();
storeCountry = (NSString*)CFLocaleGetValue(userLocaleRef, kCFLocaleCountryCode);
}
// Now we're ready to start creating URLs for the itunes store
[super start];
}
``` | I need the same functionality. At the moment I'm considering reading using data from NSLocale as default, but adding a setting in settings.app for user to customise this if it does not match.
This function is taken from [an answer to another question of mine](https://stackoverflow.com/questions/2639684/itunes-music-store-link-maker-how-to-search-from-within-my-app/2668190#2668190).
```
- (NSString *)getUserCountry
{
NSLocale *locale = [NSLocale currentLocale];
return [locale objectForKey: NSLocaleCountryCode];
}
``` |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | The approach of getting the country code of the user's locale will work ... but only if the user's iTunes store is the same as their locale. This won't always be the case.
If you create an in-app purchase item, you can use Apple's StoreKit APIs to find out the user's actual iTunes country even if it's different from their device locale. Here's some code that worked for me:
```
- (void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:
[NSSet setWithObject: PRODUCT_ID]];
request.delegate = self;
[request start];
}
- (void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray *myProducts = response.products;
for (SKProduct* product in myProducts) {
NSLocale* storeLocale = product.priceLocale;
storeCountry = (NSString*)CFLocaleGetValue((CFLocaleRef)storeLocale, kCFLocaleCountryCode);
NSLog(@"Store Country = %@", storeCountry);
}
[request release];
// If product request didn't work, fallback to user's device locale
if (storeCountry == nil) {
CFLocaleRef userLocaleRef = CFLocaleCopyCurrent();
storeCountry = (NSString*)CFLocaleGetValue(userLocaleRef, kCFLocaleCountryCode);
}
// Now we're ready to start creating URLs for the itunes store
[super start];
}
``` | I suggest you try iTunes [deep links](http://developer.apple.com/iphone/appstore/marketing.html#deeplinks). For example, <http://itunes.com/apps/appname> should take the user to the local App Store where she spends money. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | So far you can use 2 methods with their pros and cons:
**StoreFront**
->SDK >= 13
->The **three-letter** code representing the country associated with the App Store storefront
```
if let storeFront = SKPaymentQueue.default().storefront{
print("StoreFront CountryCode = ", storeFront.countryCode)
}
else {
print("StoreFront NOT Available")
}
```
OR
**SKCloudServiceController**
-> Available from iOS 9.3.
-> Requires permission. On tvOS it can become messy as I can't find a way to change the permissions in settings...
-> Permission text quite confusing.
```
let skCloudServiceController = SKCloudServiceController()
SKCloudServiceController.requestAuthorization { (status) in
guard status == .authorized else {
return
}
skCloudServiceController.requestStorefrontCountryCode(completionHandler: { (countryCode, error) in
if let error = error {
print("Failure: ", error)
}
else if let countryCode = countryCode {
print("Country code: ", countryCode)
}
})
}
```
Don't forget to include that in your .plist file:
```
<key>NSAppleMusicUsageDescription</key>
<string>Store information</string>
``` | You should probably use
```
[[userDefaults dictionaryRepresentation] objectForKey:@"NSLocaleCode"];
```
This will return a language code like en\_US or en\_UK or en\_AU or even zh\_CN, zh\_MY, jp\_JP and so on.
Parse the correct codes which you support and direct them accordingly. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | So far you can use 2 methods with their pros and cons:
**StoreFront**
->SDK >= 13
->The **three-letter** code representing the country associated with the App Store storefront
```
if let storeFront = SKPaymentQueue.default().storefront{
print("StoreFront CountryCode = ", storeFront.countryCode)
}
else {
print("StoreFront NOT Available")
}
```
OR
**SKCloudServiceController**
-> Available from iOS 9.3.
-> Requires permission. On tvOS it can become messy as I can't find a way to change the permissions in settings...
-> Permission text quite confusing.
```
let skCloudServiceController = SKCloudServiceController()
SKCloudServiceController.requestAuthorization { (status) in
guard status == .authorized else {
return
}
skCloudServiceController.requestStorefrontCountryCode(completionHandler: { (countryCode, error) in
if let error = error {
print("Failure: ", error)
}
else if let countryCode = countryCode {
print("Country code: ", countryCode)
}
})
}
```
Don't forget to include that in your .plist file:
```
<key>NSAppleMusicUsageDescription</key>
<string>Store information</string>
``` | A hard way to get this function is to set up up a single app for every app store country. Each app holds it's own country store information. This assumes, that a user sticks to one store, which should be true for most people. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | So far you can use 2 methods with their pros and cons:
**StoreFront**
->SDK >= 13
->The **three-letter** code representing the country associated with the App Store storefront
```
if let storeFront = SKPaymentQueue.default().storefront{
print("StoreFront CountryCode = ", storeFront.countryCode)
}
else {
print("StoreFront NOT Available")
}
```
OR
**SKCloudServiceController**
-> Available from iOS 9.3.
-> Requires permission. On tvOS it can become messy as I can't find a way to change the permissions in settings...
-> Permission text quite confusing.
```
let skCloudServiceController = SKCloudServiceController()
SKCloudServiceController.requestAuthorization { (status) in
guard status == .authorized else {
return
}
skCloudServiceController.requestStorefrontCountryCode(completionHandler: { (countryCode, error) in
if let error = error {
print("Failure: ", error)
}
else if let countryCode = countryCode {
print("Country code: ", countryCode)
}
})
}
```
Don't forget to include that in your .plist file:
```
<key>NSAppleMusicUsageDescription</key>
<string>Store information</string>
``` | I suggest you try iTunes [deep links](http://developer.apple.com/iphone/appstore/marketing.html#deeplinks). For example, <http://itunes.com/apps/appname> should take the user to the local App Store where she spends money. |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | Since iOS 13.0, Apple introduced the [SKStorefront](https://developer.apple.com/documentation/storekit/skstorefront) API.
It allows you to check the current AppStore country the user is connected to.
>
> **SKStorefront**: An object containing the location and unique identifier of an Apple App Store storefront.
>
>
> ### Overview
>
>
> In-app products you create through App Store Connect are available for sale in every region with an App Store. You can use the storefront information to determine the customer's region, and offer in-app products suitable for that region. You must maintain your own list of product identifiers and the storefronts in which you want to make them available.
>
>
> ### Topics
>
>
> * **countryCode**: The three-letter code representing the country associated with the App Store storefront.
> * **identifier**: A value defined by Apple that uniquely identifies an App Store storefront.
>
>
>
<https://developer.apple.com/documentation/storekit/skstorefront> | I need the same functionality. At the moment I'm considering reading using data from NSLocale as default, but adding a setting in settings.app for user to customise this if it does not match.
This function is taken from [an answer to another question of mine](https://stackoverflow.com/questions/2639684/itunes-music-store-link-maker-how-to-search-from-within-my-app/2668190#2668190).
```
- (NSString *)getUserCountry
{
NSLocale *locale = [NSLocale currentLocale];
return [locale objectForKey: NSLocaleCountryCode];
}
``` |
2,540,530 | I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186184/"
] | So far you can use 2 methods with their pros and cons:
**StoreFront**
->SDK >= 13
->The **three-letter** code representing the country associated with the App Store storefront
```
if let storeFront = SKPaymentQueue.default().storefront{
print("StoreFront CountryCode = ", storeFront.countryCode)
}
else {
print("StoreFront NOT Available")
}
```
OR
**SKCloudServiceController**
-> Available from iOS 9.3.
-> Requires permission. On tvOS it can become messy as I can't find a way to change the permissions in settings...
-> Permission text quite confusing.
```
let skCloudServiceController = SKCloudServiceController()
SKCloudServiceController.requestAuthorization { (status) in
guard status == .authorized else {
return
}
skCloudServiceController.requestStorefrontCountryCode(completionHandler: { (countryCode, error) in
if let error = error {
print("Failure: ", error)
}
else if let countryCode = countryCode {
print("Country code: ", countryCode)
}
})
}
```
Don't forget to include that in your .plist file:
```
<key>NSAppleMusicUsageDescription</key>
<string>Store information</string>
``` | I need the same functionality. At the moment I'm considering reading using data from NSLocale as default, but adding a setting in settings.app for user to customise this if it does not match.
This function is taken from [an answer to another question of mine](https://stackoverflow.com/questions/2639684/itunes-music-store-link-maker-how-to-search-from-within-my-app/2668190#2668190).
```
- (NSString *)getUserCountry
{
NSLocale *locale = [NSLocale currentLocale];
return [locale objectForKey: NSLocaleCountryCode];
}
``` |
36,312,509 | I wanted to first say this is a really nice plugin (<https://github.com/katzer/cordova-plugin-local-notifications>) but having some difficulties getting it working.
I am using an Android and Phonegap CLI. I have tried both CLI 5.0 and now Phonegap 3.5.0, this is my config.xml:
`<preference name="phonegap-version" value="3.5.0" />`
In my config.xml I have tried all these combinations:
```
<plugin name="de.appplant.cordova.plugin.local-notification" spec="0.8.1" source="pgb" />
<gap:plugin name="de.appplant.cordova.plugin.local-notification" />
<plugin name="de.appplant.cordova.plugin.local-notification" source="pgb" />
```
However the notifications do not appear - nothing happens on the phone - nothing, nada, zilch. I have also downloaded the KitchenSink App (<https://github.com/katzer/cordova-plugin-local-notifications/tree/example>) and installed on Phonegap build and my phone and nothing again happens..
This is my code on index.html so when the phone fires it should register a local notification asap:
```
cordova.plugins.notification.local.registerPermission(function (granted) {
// console.log('Permission has been granted: ' + granted);
});
cordova.plugins.notification.local.schedule({
id: 1,
title: 'Reminder',
text: 'Dont forget to pray today.',
every: 'minute',
icon: 'res://icon',
smallIcon: 'res://ic_popup_sync'
});
```
I also tried
```
cordova.plugins.notification.local.schedule({
id: 2,
text: "Good morning!",
firstAt: tomorrow_at_8_am,
every: "day" // "minute", "hour", "week", "month", "year"
});
```
Even the KitchenSink app is not working - nothing happens on the phone??
My Android version is: 5.1.1
**How can I get local notifications to appear in Phonegap?** | 2016/03/30 | [
"https://Stackoverflow.com/questions/36312509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596952/"
] | I too have spent many hours trying to get this plugin working & I have, but i do find it to be one of the most temperamental.
Within your js -
```
var testNotifications = function () {
document.addEventListener("deviceready", function () {
console.warn("testNotifications Started");
// Checks for permission
cordova.plugin.notification.local.hasPermission(function (granted) {
console.warn("Testing permission");
if( granted == false ) {
console.warn("No permission");
// If app doesnt have permission request it
cordova.plugin.notification.local.registerPermission(function (granted) {
console.warn("Ask for permission");
if( granted == true ) {
console.warn("Permission accepted");
// If app is given permission try again
testNotifications();
} else {
alert("We need permission to show you notifications");
}
});
} else {
var pathArray = window.location.pathname.split( "/www/" ),
secondLevelLocation = window.location.protocol +"//"+ pathArray[0],
now = new Date();
console.warn("sending notification");
var isAndroid = false;
if ( device.platform === "Android" ) {
isAndroid = true;
}
cordova.plugin.notification.local.schedule({
id: 9,
title: "Test notification 9",
text: "This is a test notification",
sound: isAndroid ? "file://sounds/notification.mp3" : "file://sounds/notification.caf",
at: new Date( new Date().getTime() + 10 )
// data: { secret:key }
});
}
});
}, false);
};
```
Now on your html tag -
```
<button onclick="testNotifications()">Test notification</button>
```
That should trigger a notification or warn you that it needs permissions
Also top tip is to make sure your notifications are in a folder in the root of the project. android should be mp3 and ios caf | **Answer 1 :for version 3.5.0**
have a look at [plugin's plugin.xml](https://github.com/katzer/cordova-plugin-local-notifications/blob/master/plugin.xml). see line 22
```
<engine name="cordova" version=">=3.6.0" />
```
that means plugin **only supports version greater than 3.6.0** and you are using 3.5.0
**Answer 2 :for version 5.0 or higher**
Try the following code as **index.html**. if it runs perfectly then and other options in to `notification.schedule`.
as we haven't provided time(at) option notification will triggered immediately.
```
<html>
<script type="text/javascript" src="cordova.js"></script>
<script>
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
cordova.plugins.notification.local.schedule({
id: 1,
title: "Sample Notification",
text: "foo",
every: "week",
data: { meetingId: "123#fg8" }
});
};
</script>
<body>
</body>
</html>
``` |
6,319 | Ever since upgrading to Google Maps 5.1.0 on my Droid X, I have often had Google Maps bog down and freeze to the point of completely crashing the phone. Anyone else seeing this crash? Anyone find a solution? | 2011/02/23 | [
"https://android.stackexchange.com/questions/6319",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/3078/"
] | You can usually uninstall updates from the app's page in the market. However, previous updates to Google Maps had similar problems for users that never turned their phones off. Try just restarting your phone. | Another option is to go to `Settings` -> `Applications` -> `Manage applications` -> `All` (tab at top) -> `Maps` -> `Clear data` and/or `Clear cache`.
If somehow something is corrupted in there, this will more-or-less reset things as if Google Maps was just installed but was never used. |
6,319 | Ever since upgrading to Google Maps 5.1.0 on my Droid X, I have often had Google Maps bog down and freeze to the point of completely crashing the phone. Anyone else seeing this crash? Anyone find a solution? | 2011/02/23 | [
"https://android.stackexchange.com/questions/6319",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/3078/"
] | You can usually uninstall updates from the app's page in the market. However, previous updates to Google Maps had similar problems for users that never turned their phones off. Try just restarting your phone. | Upgrade to Google Maps 5.2.1, released today. |
6,319 | Ever since upgrading to Google Maps 5.1.0 on my Droid X, I have often had Google Maps bog down and freeze to the point of completely crashing the phone. Anyone else seeing this crash? Anyone find a solution? | 2011/02/23 | [
"https://android.stackexchange.com/questions/6319",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/3078/"
] | Upgrade to Google Maps 5.2.1, released today. | Another option is to go to `Settings` -> `Applications` -> `Manage applications` -> `All` (tab at top) -> `Maps` -> `Clear data` and/or `Clear cache`.
If somehow something is corrupted in there, this will more-or-less reset things as if Google Maps was just installed but was never used. |
11,385,214 | By default Gson uses fields as a basis for it's serialization. Is there a way to get it to use accessors instead? | 2012/07/08 | [
"https://Stackoverflow.com/questions/11385214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089998/"
] | The developers of Gson [say](https://groups.google.com/forum/#!topic/google-gson/4G6Lv9PghUY) that they never felt swayed by the requests to add this feature and they were worried about murkying up the api to add support for this.
One way of adding this functionality is by using a TypeAdapter (I apologize for the gnarly code but this demonstrates the principle):
```
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.google.common.base.CaseFormat;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class AccessorBasedTypeAdaptor<T> extends TypeAdapter<T> {
private Gson gson;
public AccessorBasedTypeAdaptor(Gson gson) {
this.gson = gson;
}
@SuppressWarnings("unchecked")
@Override
public void write(JsonWriter out, T value) throws IOException {
out.beginObject();
for (Method method : value.getClass().getMethods()) {
boolean nonBooleanAccessor = method.getName().startsWith("get");
boolean booleanAccessor = method.getName().startsWith("is");
if ((nonBooleanAccessor || booleanAccessor) && !method.getName().equals("getClass") && method.getParameterTypes().length == 0) {
try {
String name = method.getName().substring(nonBooleanAccessor ? 3 : 2);
name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, name);
Object returnValue = method.invoke(value);
if(returnValue != null) {
TypeToken<?> token = TypeToken.get(returnValue.getClass());
TypeAdapter adapter = gson.getAdapter(token);
out.name(name);
adapter.write(out, returnValue);
}
} catch (Exception e) {
throw new ConfigurationException("problem writing json: ", e);
}
}
}
out.endObject();
}
@Override
public T read(JsonReader in) throws IOException {
throw new UnsupportedOperationException("Only supports writes.");
}
}
```
You can register this as a normal type adapter for a given type or through a TypeAdapterfactory - possibly checking for the presence of a runtime annotation:
```
public class TypeFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
Class<? super T> t = type.getRawType();
if(t.isAnnotationPresent(UseAccessor.class)) {
return (TypeAdapter<T>) new AccessorBasedTypeAdaptor(gson);
}
return null;
}
```
This can be specified as normal when creating your gson instance:
```
new GsonBuilder().registerTypeAdapterFactory(new TypeFactory()).create();
``` | **Note:** I'm the [**EclipseLink JAXB (MOXy)**](http://www.eclipse.org/eclipselink/moxy.php) lead and a member of the [**JAXB (JSR-222)**](http://jcp.org/en/jsr/detail?id=222) expert group.
If you can't get Gson to do what you want, below is how you can accomplish this using MOXy's native JSON binding. MOXy like any JAXB implementation will use property (public) access by default. You can configure field access using `@XmlAccessorType(XmlAccessType.FIELD)`. Below is an example:
**Customer**
```
package forum11385214;
public class Customer {
private String foo;
private Address bar;
public String getName() {
return foo;
}
public void setName(String name) {
this.foo = name;
}
public Address getAddress() {
return bar;
}
public void setAddress(Address address) {
this.bar = address;
}
}
```
**Address**
```
package forum11385214;
public class Address {
private String foo;
public String getStreet() {
return foo;
}
public void setStreet(String street) {
this.foo = street;
}
}
```
**jaxb.properties**
To configure MOXy as your JAXB provider you need to add a file called `jaxb.properties` in the same package as your domain model with the following entry (see: <http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html>).
```
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
```
**Demo**
```
package forum11385214;
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource json = new StreamSource("src/forum11385214/input.json");
Customer customer = (Customer) unmarshaller.unmarshal(json, Customer.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
```
**input.json/Output**
```
{
"name" : "Jane Doe",
"address" : {
"street" : "1 Any Street"
}
}
```
**For More Information**
* <http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html>
* <http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html>
* <http://blog.bdoughan.com/2012/04/jaxb-and-unmapped-properties.html> |
21,006,390 | I need to consume the services of a number of third party systems on my applications homepage. The data pertaining to these downstream systems are updated at different intervals and ideally my system will surface the latest data. It's not a scalable solution for my system to generate requests to each of these downstream systems each time a user hits my homepage. What strategy can i use to ensure the data i surface is current without effecting the reliability of these downstream systems?
Is a consumer/producer strategy most suitable for this requirement? | 2014/01/08 | [
"https://Stackoverflow.com/questions/21006390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24481/"
] | Have the method accept an expression, just as the method you're passing it to does:
```
public class Foo
{
public void UpdateEmployeeOrders(IEnumerable<Employee> employees,
Expression<Func<Employee, object>> selector)
{
foreach (var employee in employees)
{
UpdateSpecificEmployeeOrder(employee.id, selector);
}
}
}
```
Also, since the only thing we ever do with `employees` is iterate over it, we can type the parameter as `IEnumerable` instead of `ICollection`. It provides all of the guarantees that this methods needs, while allowing a broader range of possible input types. | You have the answer in your answer... you're using lambdas... so pass a delegate in your method.
```
public void SaveEmployeeDisplayOrder<T>(ICollection<Employee> employees, Func<Employee, T> fetchProperty)
{
//some code
foreach( var employee in employees)
{
UpdateSpecificEmployeeOrder(employee.id, fetchProperty(employee));
}
}
```
Then you would call it similar to what you had:
```
SaveEmployeeDisplayOrder(employees, e => e.EmployeeDisplayOrder);
```
or
```
SaveEmployeeDisplayOrder(employees, e => e.EmployeeEnrollOrder);
``` |
60,362 | I'm coming from an understanding of the continuous-time Fourier Transform, and the effects of doing a DFT and the inverse DFT are mysterious to me.
I have created a noiseless signal as:
```
import numpy as np
def f(x):
return x*(x-0.8)*(x+1)
X = np.linspace(-1,1,50)
y = f(X)
```
Now, if I were to perform a *continuous* Fourier transform on the function $f$ given above, restricted to $[-1,1]$, I would expect the sum of the first few Fourier basis components to give a reasonable approximation to the function $f$ (this is an observation specific to our $f$, since it is approximately sine-wavey over $[-1,1]$). The discrete Fourier transform is an approximation to the continuous one, so assuming that my points `y` are sampled noiselessly from $f$ (which they are by design), then the DFT coefficients should approximate the CFT coefficients (I think). So, I obtain a DFT like so ([formulae employed](https://docs.scipy.org/doc/numpy/reference/routines.fft.html#implementation-details)):
```
def DFT(y):
# the various frequencies
terms = np.tile(np.arange(y.shape[0]), (y.shape[0],1))
# the various frequencies cross the equi-spaced "X" values
terms = np.einsum('i,ij->ij',np.arange(y.shape[0]),terms)
# the "inside" of the sum in the DFT formula
terms = y * np.exp(-1j*2*np.pi*terms/y.shape[0])
# sum up over all points in y
return np.sum(terms, axis=1)
def iDFT_componentwise(fy, X):
# this function returns the various basis function components of y, sampled at X
# so the result is a len(X) x len(fy) matrix with each:
# row corresponding to a point in X and each
# column corresponding to a particular frequency.
terms = np.tile(np.arange(len(fy)), (X.shape[0],1))
terms = fy * np.exp(1j*2*np.pi*np.einsum('i,ij->ij',np.arange(X.shape[0])*fy.shape[0]/X.shape[0],terms)/fy.shape[0])
return terms/fy.shape[0]
def iDFT(fy,X):
# summing the Fourier components over all frequencies gives back the original function
return np.sum(iDFT_componentwise(fy,X), axis=1)
```
I am interested in inspecting the various basis functions that comprise my signal, so I oversample the domain to get a better-resolved picture:
```
oversampled_X = np.linspace(-1,1,100)
```
and proceed to check out my components:
```
fy = DFT(y)
y_f_components = iDFT_componentwise(fy, oversampled_X)
```
The positive-frequency components look as expected.
```
import matplotlib.pyplot as plt
plt.plot(oversampled_X, y_f_components[:,1],c='r')
plt.plot(X,y)
plt.show()
```
[](https://i.stack.imgur.com/KUvMW.png)
However, the *negative* frequency components look all weird:
```
plt.plot(oversampled_X, y_f_components[:,49],c='r')
plt.plot(X,y)
plt.show()
```
[](https://i.stack.imgur.com/Wfmfy.png)
This last image looks like it has problems with [aliasing](https://en.wikipedia.org/wiki/Aliasing). This, in turn, causes problems when I try to reconstitute the function from the Fourier components (see image below)
```
plt.plot(oversampled_X, iDFT(fy,oversampled_X),c='r')
plt.plot(X,y)
plt.show()
```
This problem does not occur when I truncate the continuous time Fourier transform of the function to include the same number of terms (see image below):
```
import sympy
from sympy import fourier_series
from sympy.abc import x
from sympy.utilities.lambdify import lambdify
f = x*(x-0.8)*(x+1)
fourier_f = fourier_series(f, (x, -1, 1))
lambda_fourier_f = lambdify(x,fourier_f.truncate(25),'numpy')
reconstructed_y = lambda_fourier_f(oversampled_X)
plt.plot(oversampled_X,reconstructed_y,c='r')
plt.plot(X,y)
```
tl;dr
=====
My oversampled inverse Discrete Fourier Transform has a terrible aliasing problem as illustrated here:
The oversampled inverse Discrete Transform:
[](https://i.stack.imgur.com/QaFCR.png)
As opposed to the oversampled inverse Continuous Transform (trucated to the number of terms in the discrete version).
[](https://i.stack.imgur.com/FWgVz.png)
What is the intrinsic property of the DFT that causes this? If the DFT coefficients approximate the CFT coefficients, then why doesn't the CFT have this problem?
Update: The spectrum
====================
As requested, here is the spectrum of $f$. Note that since $f$ is real, the discrete spectrum (excepting the constant term) is symmetric about n/2. I have not attempted to fix the units.
[](https://i.stack.imgur.com/H5jcz.png)
Update2: Extending the function
===============================
Per @robertbristow-johnsons suggestion, I decided to check out a slightly different function: $x(x-1)(x+1)$ on $[-1,1]$ (so that the "ends" agree) and I have "repeated" the data a number of times end-to-end. The thought was that this would alleviate some of the weird effects. However, the exact same features appear. (one may wish to open this figure by itself in a new window to enable zooming)
[](https://i.stack.imgur.com/x4LHX.png) | 2019/08/26 | [
"https://dsp.stackexchange.com/questions/60362",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/33763/"
] | Let me summarize my understanding of what you're trying to do. You have a real-valued sequence $x[n]$, obtained by sampling a real-valued continuous function, and you computed its DFT $X[k]$. The sequence can be expressed in terms of its DFT coefficients:
$$x[n]=\frac{1}{N}\sum\_{k=0}^{N-1}X[k]e^{j2\pi nk/N},\qquad n\in[0,N-1]\tag{1}$$
where $N$ is the length of the sequence.
Now you want to interpolate that sequence, and I believe you're trying to do this in the following way:
$$\tilde{x}[m]=\frac{1}{N}\sum\_{k=0}^{N-1}X[k]e^{j2\pi mk/M},\qquad m\in[0,M-1],\quad M>N\tag{2}$$
This, however, doesn't work. If $M$ happens to be an integer multiple of $N$, then $\tilde{x}[nM/N]=x[n]$ is satisfied, but the other values of $\tilde{x}[m]$ are by no means interpolated values of $x[n]$. Note that these values are not even real-valued.
What you *can* do is approximately compute the Fourier coefficients of the original continuous function using the (length $N$) DFT of the sampled function, and then approximately reconstruct samples of the function on a dense grid (of length $M>N$):
$$\tilde{x}[m]=\frac{1}{N}\sum\_{k=-K}^KX[k]e^{j2\pi mk/M},\qquad m\in[0,M-1]\tag{3}$$
Note that in $(3)$ the summation indices are symmetric, and the number $K$ cannot exceed $N/2$ because that's the number of independent DFT coefficients you have due to conjugate symmetry of $X[k]$ (because $x[n]$ is assumed to be real-valued).
Eq. $(3)$ is just equivalent to zero-padding in the frequency domain, which corresponds to interpolation in the time domain. Note, however, that the zero padding is done in such a way that conjugate symmetry is retained, i.e., the zeros are inserted around the Nyquist frequency, and not simply appended to the DFT coefficients.
With $X[-k]=X[N-k]$ and $X[k]=X^\*[N-k]$, Eq. $(3)$ can be rewritten as
$$\begin{align}\tilde{x}[m]&=\frac{1}{N}X[0]+\frac{1}{N}\sum\_{k=1}^K\left(X[k]e^{j2\pi mk/M}+X[-k]e^{-j2\pi mk/M}\right)\\&=\frac{1}{N}X[0]+\frac{1}{N}\sum\_{k=1}^K\left(X[k]e^{j2\pi mk/M}+X^\*[k]e^{-j2\pi mk/M}\right)\\&=\frac{1}{N}X[0]+\frac{2}{N}\textrm{Re}\left\{\sum\_{k=1}^KX[k]e^{j2\pi mk/M}\right\},\qquad m\in[0,M-1]\end{align}\tag{4}$$
The following Matlab/Octave code illustrates the above:
```
N = 100;
t = linspace (-1,1,N);
M = 200;
ti = linspace (-1,1,M);
x = t .* (t - 0.8) .* (t + 1);
x = x(:);
X = fft(x);
X = X(:);
Nc = 20; % # Fourier coefficients (must not exceed N/2)
x2 = X(1) + 2*real( exp( 1i * 2*pi/M * (0:M-1)' * (1:Nc-1) ) * X(2:Nc) );
x2 = x2 / N;
plot(t,x,ti,x2)
```
[](https://i.stack.imgur.com/Ujau8.png)
Note that the approximation of the blue curve by the green curve in the above figure is two-fold: first, there's only a finite number of Fourier coefficients, and second, the Fourier coefficients are only approximately computed from samples of the original function. | I have looked at your image (and didn't read the post) and its explanation is as follows.
Let the data in the blue curve be $x[n]$, and the data in the red curve be $y[n]$; then it can be seen and shown that:
$$y[n] = \tfrac12 ( x[n] + (-1)^n x[n] ) $$
In the DTFT domain this relationship becomes :
$$ Y(e^{j\omega}) = \tfrac12 \big( X(e^{j\omega}) + X(e^{j(\omega-\pi)}) \big) $$
In the DFT domain, for even $N$, this becomes:
$$ Y[k] = \tfrac12 \big( X[k] + X[k - \tfrac{N}2] \big) $$
Now, in the frequency domain we do not have an **interpolated** spectrum but an **aliased** one... Who does or what causes this aliasing? I don't know as I didn't read your post in such detail, but it's neverthess there...
Hence when you convert $Y[k]$ back into time-domain, you will obtain $y[n]$ sequence as an inversion of an **aliased** spectrum of $X[k]$ ; There's no interpolation in any domains...
The following MATLAB / OCTAVE code demonstrates what you try to achieve by your *oversampled CFT* approximation(?) of DFT.
```
L = 32;
t = linspace(-1,1,L);
x = t.*(t-0.8).*(t+1); % Polynomial signal of length L
N = L ; % DFT length... (make it even)
X = fft(x,N);
Y = 0.5*(X + fftshift(X)); % is this an "INTERPOLATION " of
% X[k]? No. It's: X[k] + X[k-N/2]
y = real(ifft(Y,N)); % inverse-DFT to reconstruct y[n]
y = y(1:L); % Trim the trailing zeros, if any, on the
% reconstructed y[n] of length N
figure,stem(t,x)
hold on
stem(t,y,'+r');title('x[n] vs y[n]'); %
legend('x[n]','','y[n]');
```
The result is :
[](https://i.stack.imgur.com/IjLfZ.png) |
7,060 | recently I bought 3 solar panels rated at 5V 200 mA each. I want to use them to charge a 5V battery bank to charge a phone. Thinking about the proper way to put them, I thought i can connect all in parallel to get maximum current, but realized that if the sun light was a little weak it will no generate full 5v thus preventing charging. So I decided to put 2 in parallel to give the equivalent of one 5V solar panel, connected in series with the 3rd panel to give the equivalent of 10v. sacrificing a little current to get higher voltage, to allow the charging to happen on a wider range of sun light power. The following picture shows the wiring and the schematic I intend to replicate.
[](https://i.stack.imgur.com/4oFHJ.jpg)
[](https://i.stack.imgur.com/lHrv9.jpg)
Now that I have an equivalent of 10v, 400mA solar panel. I used a 7805 voltage regulator to cut down the excess to 5v.
[](https://i.stack.imgur.com/IbnN3.jpg)
Final step, I added a standard diode to prevent the panels from leaking the battery in the shade.
and now measuring:
[](https://i.stack.imgur.com/A0RIw.jpg)
Questions:
1. I didn't think about this before putting the diode, but is it okay to put the blocking diode on the ground wire? because I know some applications do not use the ground except for safety (i.e. 3 phase system). it would be helpful also to avoid the 0.7v drop across the diode before the regulator.
2. according to previous calculations, I'm supposed to get a maximum of 10v output before regulation, and considering that the sun was pretty shinny today, why was the reading I got not more then 6v? I have measured across each panel seperatly and got around 5.5V, are the connections right? | 2016/01/23 | [
"https://engineering.stackexchange.com/questions/7060",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/1736/"
] | Putting a single panel in series with two other panels that are in parallel does not accomplish what you think it does. The overall current of such a setup is limited by the single panel to 200 mA, so the three panels will not produce any more power than you'd get by just putting two panels in series.
A single solar cell can be thought of as a current source in parallel with a silicon diode. The current source is driven by the incoming light. The diode "shorts out" the current source, which is why the voltage across a single cell can never be more than about 0.65 V, the forward drop of a silicon diode. A 5V panel is approximately 10 such cells connected in series. The current through all of the cells will be limited by the cell that is receiving the least amount of light.
Also, the blocking diode in your diagram is pointing the wrong way.
If your panels are rated at 5V, and your "battery bank" requires 5V to charge, then you don't need to do anything more than put all three panels in parallel and hook them directly to the battery. Forget about blocking diodes. | That's a mess, and your labels about what is + and what is - out of each panel seem inconsistant.
For the most effective use of the panels, wire them all in series. That will put out around 15 V under full sun. Now use a buck converter to make a regulated 5 V from that.
There are many buck converter chips available off the shelf at these low voltages. Finding one with a built-in switch and synchronous rectification shouldn't be too hard. You only have to supply the inductor, a few caps, and maybe a charge pump diode depending on the chip you chose.
The other advantage of a switching power supply is that you probably won't need heat sinking. The resulting overall circuit will be smaller, cheaper, and give better performance than just throwing a 7805 regulator at it. At 10 V in and 5 V 1 A out, the 7805 will dissipate 5 W. That's way beyond what it can do without a heat sink. |
73,665,822 | Currently struggling to add the .is-active class to my header via javascript. If you add "is-active" to the header classes it works well. But I can't seem to work it out in javascript.
I just want the class to be added as soon as you start scrolling, and then removed when returning to the top.
Appreciate all the help!
HTML:
```
<header class="header">
<div class="header-nav flex container">
<figure class="header-logo">
<a href="#">
<img class="header-logo-light" src="images/logoWhite.png" alt="San Miguel Services Logo">
<img class="header-logo-dark" src="images/logoDark.png" alt="San Miguel Services Logo">
</a>
</figure>
<nav class="header-menu flex">
<div class="header-menu-li">
<a href="">WELCOME</a>
<a href="">SERVICES</a>
<a href="">ABOUT</a>
<a href="">PORTFOLIO</a>
<a href="">CONTACT</a>
</div>
</nav>
<div class="header-btn">
<button href="#" class="button header-btn">REQUEST A QUOTE</button>
</div>
</div>
</header>
```
CSS:
```
.header {
position: fixed;
z-index: 1;
width: 100vw;
line-height: 18px;
}
.header .header-logo-dark {
opacity: 0;
display: none;
}
.header .header-logo-light {
opacity: 1;
display: block;
}
.header.is-active .header-logo-dark {
opacity: 1;
display: block;
}
.header.is-active .header-logo-light {
opacity: 0;
display: none;
}
.header.is-active .header-menu-li a {
color: $darkBlue;
&::before {
background: linear-gradient(to right, $mediumGreen, $lightGreen);
}
}
.header.is-active .header-btn button {
background: $mediumGreen;
color: $white;
transition: 300ms ease-in-out;
&:hover {
box-shadow: inset 0 0 0 2px $darkBlue;
color: $darkBlue;
background: transparent;
}
}
.header.is-active {
background: $white;
}
.header-nav {
padding: 20px 5.5%;
position: relative;
justify-content: space-between;
margin: auto;
}
.header-logo {
position: relative;
a img {
height: 46px;
}
}
.header-menu {
align-items: center;
}
.header-menu-li {
a {
position: relative;
margin: 0 0.625rem;
font-weight: 500;
font-size: $font-sm;
color: $white;
transition: color 300ms ease-in-out;
&::before {
content: "";
display: block;
position: absolute;
height: 5px;
background: $white;
left: 0;
right: 0;
bottom: -33px;
opacity: 0;
transition: opacity 300ms ease-in-out;
}
&:hover {
opacity: 0.95;
&::before {
opacity: 1;
}
}
}
}
.header-btn {
height: 46px;
font-size: $font-sm;
font-weight: 500;
button {
background: transparent;
border: 1px solid $white;
transition: 200ms ease-in-out;
&:hover {
background: $white;
color: $darkBlue;
}
}
}
``` | 2022/09/09 | [
"https://Stackoverflow.com/questions/73665822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17472782/"
] | Try this code:
```
window.addEventListener("scroll", function(){
var header = document.querySelector(".header");
header.classList.toggle("is-active", window.scrollY > 0);
})
``` | Try to use more semantic HTML, this will help you in building the site.
```
<div class="menu">
<ul>
<li><a href="#home">Home</a></li>
</ul>
</div>
<section id="home">
<div class="wrapper">
</div>
</section>
```
---
You can also add some initial CSS settings to help you build your site, like `:root`, `* {}`, etc...
If you still don't know what a `:root` is, look it up, this will make it a lot easier.
I left some example code.
```
/* GENERAL */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
text-decoration: none;
}
:root {
font-size: 62.5%; /* 1rem = 10px */
}
html {
scroll-behavior: smooth;
}
html,
body {
width: 100%;
height: 100%;
}
body {
font-family: " ";
font-size: 1.6rem;
text-align: center;
overflow: overlay;
background-color: var(--name-var);
}
.wrapper {
width: min(50rem, 100%);
margin-inline: auto;
padding-inline: 2.4rem;
}
```
---
```
window.addEventListener('scroll', onScroll)
onScroll()
function onScroll() {
showNavOnScroll ();
showBackToTopButtonOnScroll();
activateMenuAtCurrentSection(home);
}
function activateMenuAtCurrentSection(section) {
const targetLine = scrollY + innerHeight / 2
// check if the section has passed the line
// what data will I need?
const sectionTop = section.offsetTop
const sectionHeight = section.offsetHeight
const sectionTopReachOrPassedTargetLine = targetLine >= sectionTop
// check if the base is below the target line
// what data will I need?
const sectionEndAst = sectionTop + sectionHeight
const sectionEndPassedTargetLine = sectionEndAst <= targetLine
console.log('Did the session bottom go over the line?', sectionEndPassedTargetLine)
// section boundaries
const sectionBoundaries =
sectionTopReachOrPassedTargetLine && !sectionEndPassedTargetLine
const sectionId = section.getAttribute('id')
const menuElement = document.querySelector(`.menu a[href*=${sectionId}]`)
menuElement.classList.remove('active')
if (sectionBoundaries) {
menuElement.classList.add('active')
}
}
// This is so that when you scroll down your navigation bar goes out
function showNavOnScroll() {
if (scrollY > 0) {
navigation.classList.add('scroll');
} else {
navigation.classList.remove('scroll');
}
}
// Will make them appear smooth
ScrollReveal({
origin:'top',
distance: '30px',
duration: 700,
}).reveal(`
#home`);
``` |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | Suppose you throw a ball up into the air. You could ask how the ball manages to move upwards when gravity is pulling it down, and the answer is that it started with an upwards velocity. Gravity pulls on the ball and slows it down so it will eventually reach a maximum height and fall back, but the ball manages to move upwards against gravity because of its initial velocity.
Basically the same is true of the expansion of the universe. A moment after the Big Bang everything in the universe was expanding away from everything else with an extremely high velocity. In fact if we extrapolate back to time zero those velocities become infinite. In the several billion years following the Big Bang gravity was slowing the expansion, in basically the same way gravity slows the ball you threw upwards, but the gravity didn't stop the expansion - it only slowed it.
The obvious next question is how did the universe get to start off expanding with such high velocities, and the answer is that we don't know because we have no theory telling us what happened at the Big Bang.
There is a slight complication that I'll mention in case anyone is interested: dark energy acts as a sort of anti-gravity and makes the expansion faster not slower. This has only become an important effect in the last few billion years, but as a result of dark energy right now gravity isn't slowing the expansion at all - in fact it's making the expansion faster. | update: the accepted answer has now been updated to make my answer superfluous.
**we totally don't know.**
we don't know why the universe started expanding at the beginning of time. we basically just shrug and say "it seems like there was this big bang". your question seems to imply that gravity should have stopped the expansion by now, which makes sense. originally, we thought that the universe was still expanding simply because **it hasn't been long enough since the big bang for gravity to stop the expansion**. but now we know, the universe appears to be expanding faster over time, rather than more slowly. we don't know why that is happening either. ask a physicist why the universe is expanding and he will say "dark energy". then ask him what dark energy is, and he'll say "the thing that makes the universe expand". this circular definition reflects the fact that we dont' really know why, but **we expect to find an explanation that fits our mathematical models. in the mean time, we call that something "dark energy"**.
i don't feel qualified to address the math or physics of your question about a "bigger object" pulling the universe apart. but from a philosophical perspective, it seems to be an unproductive [homunculus argument](https://en.wikipedia.org/wiki/Homunculus_argument). although, i admit i like the parallels it draws between [vacuum polorization](https://en.wikipedia.org/wiki/Vacuum_polarization) and the big bang.
side note: John Rennie's answer is also excellent (as usual). i felt he kind of dodged the question by illustrating what we do know (or theorize), but he has since updated his answer to include the points about which we are ignorant (dark energy and the big bang). we just don't have a good explanation for some things yet, and it is good to admit that. to quote einstein: [the larger the circle of light, the larger the perimeter of darkness around it](http://www.goodreads.com/quotes/143906-as-our-circle-of-knowledge-expands-so-does-the-circumference). |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | update: the accepted answer has now been updated to make my answer superfluous.
**we totally don't know.**
we don't know why the universe started expanding at the beginning of time. we basically just shrug and say "it seems like there was this big bang". your question seems to imply that gravity should have stopped the expansion by now, which makes sense. originally, we thought that the universe was still expanding simply because **it hasn't been long enough since the big bang for gravity to stop the expansion**. but now we know, the universe appears to be expanding faster over time, rather than more slowly. we don't know why that is happening either. ask a physicist why the universe is expanding and he will say "dark energy". then ask him what dark energy is, and he'll say "the thing that makes the universe expand". this circular definition reflects the fact that we dont' really know why, but **we expect to find an explanation that fits our mathematical models. in the mean time, we call that something "dark energy"**.
i don't feel qualified to address the math or physics of your question about a "bigger object" pulling the universe apart. but from a philosophical perspective, it seems to be an unproductive [homunculus argument](https://en.wikipedia.org/wiki/Homunculus_argument). although, i admit i like the parallels it draws between [vacuum polorization](https://en.wikipedia.org/wiki/Vacuum_polarization) and the big bang.
side note: John Rennie's answer is also excellent (as usual). i felt he kind of dodged the question by illustrating what we do know (or theorize), but he has since updated his answer to include the points about which we are ignorant (dark energy and the big bang). we just don't have a good explanation for some things yet, and it is good to admit that. to quote einstein: [the larger the circle of light, the larger the perimeter of darkness around it](http://www.goodreads.com/quotes/143906-as-our-circle-of-knowledge-expands-so-does-the-circumference). | Everything is measured with atoms (upon atomic properties)
oooooo < these are atoms in the lab now
|\_\_\_\_\_| This space at left is $\approx 5\ $ units long .
**OOOOOO** < the very same atoms in the past
radiated at longer wavelengths (redshifted).
|\_\_\_\_\_| This space at left is $\approx 3.5\ $ units long.
Is it clear that any space expansion is an artifact of the measuring process ?
If you do not beleive in your eyes and intuition please present one fundamental equation (from all physics) able to discriminante between the atoms version 1 and version 2 (besides the radiated light wavelengths as said above).
For those that want to check the validity of, or deny, my viewpoint please comment the proof in this document "[A self-similar model of the Universe unveils the nature of dark energy](http://vixra.org/pdf/1107.0016v1.pdf)".
In physics there is no mention to any *absolute or invariant* size of the particles. This absolute notion was never questioned before and is an hidden postulate of the standard Model.
Because the "oos/OOs" is not clear enough here is the balloon analogy:
[](https://i.stack.imgur.com/y5w0n.jpg)
Explaining "more field" in ligth blue in the 'present' balloon:
The light cone of the fields associated with the particles grows as time goes by. Thus, the overall energetic content of particles+field is constant thru time.
The next ideas are not part of the Model because it is speculation:
There are infinite events of matter creation, with CMB, in a cyclic way.
The one versioned Universe of Standard Model, with a begining and an end, is phylosophically repugnant to my mind. I'm a rationalist and I fully respect the PSR-Principle of Sufficient Reason as Spinoza, ...Poincaré, and Einstein did. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | Something the other answers don't really delve into is this: **Space itself is what's expanding**
Let's think about a regular Newtonian Spacetime with zero expansion, borrowing Jim's example of a car on the road. You're sitting completely still, as is a friend you're following on a roadtrip, with about a hundred feet of distance between you. If I move towards them at a few feet per second, then my distance is going to decrease at the same rate. I'll also be approaching another car a few hundred feet ahead of them at the same speed, because again none of us are moving.
Now, if we were in a classical, flat, non-expanding spacetime that's more or less what we'd see. Galaxies would gravitationally attract, and eventually (Meaning over a literally infinite timeframe) everything would re-merge.
This is where things get bizzare, and well outside the scope of our daily experience. We're not on a road as we know it, **The road itself is growing. Space itself is expanding.**
Imagine that, somehow, every 10 feet of road is growing an extra foot every second. If I were standing still, I'd see my friend move away from me at about 10 ft/s for the first second. A car 500 feet away would move away at 50 ft/s, and a car a mile away would rocket off at **over 500 ft/s** If I started moving towards my friend at 20 ft/s, I'd only see him getting closer at a rate of 10 ft/s, and the car a mile away would still be speeding into the distance faster than I could catch up to it.
This is where the idea of the Observable Universe comes from. There are points in space that we can never see, because they're "expanding" away from us faster than the speed of light. | Everything is measured with atoms (upon atomic properties)
oooooo < these are atoms in the lab now
|\_\_\_\_\_| This space at left is $\approx 5\ $ units long .
**OOOOOO** < the very same atoms in the past
radiated at longer wavelengths (redshifted).
|\_\_\_\_\_| This space at left is $\approx 3.5\ $ units long.
Is it clear that any space expansion is an artifact of the measuring process ?
If you do not beleive in your eyes and intuition please present one fundamental equation (from all physics) able to discriminante between the atoms version 1 and version 2 (besides the radiated light wavelengths as said above).
For those that want to check the validity of, or deny, my viewpoint please comment the proof in this document "[A self-similar model of the Universe unveils the nature of dark energy](http://vixra.org/pdf/1107.0016v1.pdf)".
In physics there is no mention to any *absolute or invariant* size of the particles. This absolute notion was never questioned before and is an hidden postulate of the standard Model.
Because the "oos/OOs" is not clear enough here is the balloon analogy:
[](https://i.stack.imgur.com/y5w0n.jpg)
Explaining "more field" in ligth blue in the 'present' balloon:
The light cone of the fields associated with the particles grows as time goes by. Thus, the overall energetic content of particles+field is constant thru time.
The next ideas are not part of the Model because it is speculation:
There are infinite events of matter creation, with CMB, in a cyclic way.
The one versioned Universe of Standard Model, with a begining and an end, is phylosophically repugnant to my mind. I'm a rationalist and I fully respect the PSR-Principle of Sufficient Reason as Spinoza, ...Poincaré, and Einstein did. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | update: the accepted answer has now been updated to make my answer superfluous.
**we totally don't know.**
we don't know why the universe started expanding at the beginning of time. we basically just shrug and say "it seems like there was this big bang". your question seems to imply that gravity should have stopped the expansion by now, which makes sense. originally, we thought that the universe was still expanding simply because **it hasn't been long enough since the big bang for gravity to stop the expansion**. but now we know, the universe appears to be expanding faster over time, rather than more slowly. we don't know why that is happening either. ask a physicist why the universe is expanding and he will say "dark energy". then ask him what dark energy is, and he'll say "the thing that makes the universe expand". this circular definition reflects the fact that we dont' really know why, but **we expect to find an explanation that fits our mathematical models. in the mean time, we call that something "dark energy"**.
i don't feel qualified to address the math or physics of your question about a "bigger object" pulling the universe apart. but from a philosophical perspective, it seems to be an unproductive [homunculus argument](https://en.wikipedia.org/wiki/Homunculus_argument). although, i admit i like the parallels it draws between [vacuum polorization](https://en.wikipedia.org/wiki/Vacuum_polarization) and the big bang.
side note: John Rennie's answer is also excellent (as usual). i felt he kind of dodged the question by illustrating what we do know (or theorize), but he has since updated his answer to include the points about which we are ignorant (dark energy and the big bang). we just don't have a good explanation for some things yet, and it is good to admit that. to quote einstein: [the larger the circle of light, the larger the perimeter of darkness around it](http://www.goodreads.com/quotes/143906-as-our-circle-of-knowledge-expands-so-does-the-circumference). | >
> How can the universe expand if there is gravitation?
>
>
>
Because gravity alters the motion of light and matter through space. But *it doesn't make space fall down*.
>
> We live in an expanding universe - so I'm told. But how can that be possible?
>
>
>
Because the expanding universe is something like a stress ball. Squeeze it down in your fist, then let go. It expands.
>
> Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe?
>
>
>
Because a gravitational field is a place where space is "neither homogeneous nor isotropic", this being modelled as curved spacetime. See the [Einstein digital papers](http://einsteinpapers.press.princeton.edu/vol7-trans/192?highlightText=%22neither%20homogeneous%22):
[](https://i.stack.imgur.com/gIswA.jpg)
And on the very largest scale space is homogeneous and isotropic, see the [FLRW metric](https://en.wikipedia.org/wiki/Friedmann%E2%80%93Lema%C3%AEtre%E2%80%93Robertson%E2%80%93Walker_metric#General_metric). There is no overall gravitational field in the universe. And even if there was, it wouldn't stop space expanding.
>
> I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object?
>
>
>
No. A massive body such as a star "conditions" the surrounding space. It *alters* it, and this effect diminishes with distance. As a result there's a gravitational field. But the space doesn't fall down towards the star. The [waterfall analogy](http://jila.colorado.edu/~ajsh/insidebh/waterfall.html) is badly misleading in this respect. In similar vein expanding space is not falling up towards some other object. NB: dark energy is not gravity: gravity is *not* making the universe expand faster. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | Something the other answers don't really delve into is this: **Space itself is what's expanding**
Let's think about a regular Newtonian Spacetime with zero expansion, borrowing Jim's example of a car on the road. You're sitting completely still, as is a friend you're following on a roadtrip, with about a hundred feet of distance between you. If I move towards them at a few feet per second, then my distance is going to decrease at the same rate. I'll also be approaching another car a few hundred feet ahead of them at the same speed, because again none of us are moving.
Now, if we were in a classical, flat, non-expanding spacetime that's more or less what we'd see. Galaxies would gravitationally attract, and eventually (Meaning over a literally infinite timeframe) everything would re-merge.
This is where things get bizzare, and well outside the scope of our daily experience. We're not on a road as we know it, **The road itself is growing. Space itself is expanding.**
Imagine that, somehow, every 10 feet of road is growing an extra foot every second. If I were standing still, I'd see my friend move away from me at about 10 ft/s for the first second. A car 500 feet away would move away at 50 ft/s, and a car a mile away would rocket off at **over 500 ft/s** If I started moving towards my friend at 20 ft/s, I'd only see him getting closer at a rate of 10 ft/s, and the car a mile away would still be speeding into the distance faster than I could catch up to it.
This is where the idea of the Observable Universe comes from. There are points in space that we can never see, because they're "expanding" away from us faster than the speed of light. | The attraction of any two objects is proportional to the product of their masses times the distance between them squared. This force always accelerates the objects toward each other. But that "distance between them squared" term means that the force drops off faster than the velocity does. This means that any two objects that are initially moving away from each other will be continuously slowing down, and there can be two outcomes:
1) They eventually slow down to the point where they start moving back toward each other, which happens if their initial relative velocities are below a certain threshold for a given pair of objects, or
2) Above this threshold, the gravitational force drops off faster than the velocity does, so that while they continuously decelerate, they never get down to zero relative to each other. Remember, gravitational force drops off with the square of the distance.
Based on the estimated total mass of the universe and the observed speed at which everything is moving away from each other, it is believed that the universe is in the latter condition, and will always be expanding.
Or to put it another way, on average, everything in the universe is moving away from each other faster than their mutual escape velocity. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | update: the accepted answer has now been updated to make my answer superfluous.
**we totally don't know.**
we don't know why the universe started expanding at the beginning of time. we basically just shrug and say "it seems like there was this big bang". your question seems to imply that gravity should have stopped the expansion by now, which makes sense. originally, we thought that the universe was still expanding simply because **it hasn't been long enough since the big bang for gravity to stop the expansion**. but now we know, the universe appears to be expanding faster over time, rather than more slowly. we don't know why that is happening either. ask a physicist why the universe is expanding and he will say "dark energy". then ask him what dark energy is, and he'll say "the thing that makes the universe expand". this circular definition reflects the fact that we dont' really know why, but **we expect to find an explanation that fits our mathematical models. in the mean time, we call that something "dark energy"**.
i don't feel qualified to address the math or physics of your question about a "bigger object" pulling the universe apart. but from a philosophical perspective, it seems to be an unproductive [homunculus argument](https://en.wikipedia.org/wiki/Homunculus_argument). although, i admit i like the parallels it draws between [vacuum polorization](https://en.wikipedia.org/wiki/Vacuum_polarization) and the big bang.
side note: John Rennie's answer is also excellent (as usual). i felt he kind of dodged the question by illustrating what we do know (or theorize), but he has since updated his answer to include the points about which we are ignorant (dark energy and the big bang). we just don't have a good explanation for some things yet, and it is good to admit that. to quote einstein: [the larger the circle of light, the larger the perimeter of darkness around it](http://www.goodreads.com/quotes/143906-as-our-circle-of-knowledge-expands-so-does-the-circumference). | The attraction of any two objects is proportional to the product of their masses times the distance between them squared. This force always accelerates the objects toward each other. But that "distance between them squared" term means that the force drops off faster than the velocity does. This means that any two objects that are initially moving away from each other will be continuously slowing down, and there can be two outcomes:
1) They eventually slow down to the point where they start moving back toward each other, which happens if their initial relative velocities are below a certain threshold for a given pair of objects, or
2) Above this threshold, the gravitational force drops off faster than the velocity does, so that while they continuously decelerate, they never get down to zero relative to each other. Remember, gravitational force drops off with the square of the distance.
Based on the estimated total mass of the universe and the observed speed at which everything is moving away from each other, it is believed that the universe is in the latter condition, and will always be expanding.
Or to put it another way, on average, everything in the universe is moving away from each other faster than their mutual escape velocity. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | Ok I am no professional physicist, so feel free to scrap this if you want to, but as I have had explained to me: the expansion of space is the phenomenon that distances increase, *without* relating to any motion.
It is the space in between atoms and galaxies that gets "stretched", not that objects "move" away from each other. Like you blow a ballon up, points on the balloon get further away, but it is because of the fabric of reality itself that is expanding and not any motion of the matter in it. | I would like to start by clarifying a couple of misconceptions you have.
1)Everything is NOT attracted to a "**bigger** thing". Everything IS attracted to **everything**.
2)For the expansion of our universe to be caused by a "bigger thing," the thing would have to be a "shell" bigger than our universe, and the shell itself would have to be expanding as well. Therefore, this shell would also need a "bigger" shell, etc., ad infinitum (for ever).
Gravitation **could** stop the expansion. However, this is **only one of three** possible outcomes. Einstein came up with a formula that shows that if the amount of energy and matter (E & M) in the universe is more than a critical amount (CA), the universe will not only stop, but also reverse direction and start contracting (outcome 1). If the amount of (E & M) is equal to the (CA), the universe will stop expanding and **remain at the size attained** (outcome 2). If the amount of (E & M) is less than (CA), then the universe will continue to expand (outcome 3).
At the present time, it appears that outcome 3 is the one that is going to happen, since the amount of (E & M) calculated is about 22% of the critical amount. However, if those doing the calculations did not take into consideration the (E & M) of the black holes, and the fact that the universe **is bigger** (at least twice) than the **observable universe**, this number could easily be around 90%! But because of the additional effect of "space expansion," even this larger amount won't be enough to stop the expansion. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | Something the other answers don't really delve into is this: **Space itself is what's expanding**
Let's think about a regular Newtonian Spacetime with zero expansion, borrowing Jim's example of a car on the road. You're sitting completely still, as is a friend you're following on a roadtrip, with about a hundred feet of distance between you. If I move towards them at a few feet per second, then my distance is going to decrease at the same rate. I'll also be approaching another car a few hundred feet ahead of them at the same speed, because again none of us are moving.
Now, if we were in a classical, flat, non-expanding spacetime that's more or less what we'd see. Galaxies would gravitationally attract, and eventually (Meaning over a literally infinite timeframe) everything would re-merge.
This is where things get bizzare, and well outside the scope of our daily experience. We're not on a road as we know it, **The road itself is growing. Space itself is expanding.**
Imagine that, somehow, every 10 feet of road is growing an extra foot every second. If I were standing still, I'd see my friend move away from me at about 10 ft/s for the first second. A car 500 feet away would move away at 50 ft/s, and a car a mile away would rocket off at **over 500 ft/s** If I started moving towards my friend at 20 ft/s, I'd only see him getting closer at a rate of 10 ft/s, and the car a mile away would still be speeding into the distance faster than I could catch up to it.
This is where the idea of the Observable Universe comes from. There are points in space that we can never see, because they're "expanding" away from us faster than the speed of light. | update: the accepted answer has now been updated to make my answer superfluous.
**we totally don't know.**
we don't know why the universe started expanding at the beginning of time. we basically just shrug and say "it seems like there was this big bang". your question seems to imply that gravity should have stopped the expansion by now, which makes sense. originally, we thought that the universe was still expanding simply because **it hasn't been long enough since the big bang for gravity to stop the expansion**. but now we know, the universe appears to be expanding faster over time, rather than more slowly. we don't know why that is happening either. ask a physicist why the universe is expanding and he will say "dark energy". then ask him what dark energy is, and he'll say "the thing that makes the universe expand". this circular definition reflects the fact that we dont' really know why, but **we expect to find an explanation that fits our mathematical models. in the mean time, we call that something "dark energy"**.
i don't feel qualified to address the math or physics of your question about a "bigger object" pulling the universe apart. but from a philosophical perspective, it seems to be an unproductive [homunculus argument](https://en.wikipedia.org/wiki/Homunculus_argument). although, i admit i like the parallels it draws between [vacuum polorization](https://en.wikipedia.org/wiki/Vacuum_polarization) and the big bang.
side note: John Rennie's answer is also excellent (as usual). i felt he kind of dodged the question by illustrating what we do know (or theorize), but he has since updated his answer to include the points about which we are ignorant (dark energy and the big bang). we just don't have a good explanation for some things yet, and it is good to admit that. to quote einstein: [the larger the circle of light, the larger the perimeter of darkness around it](http://www.goodreads.com/quotes/143906-as-our-circle-of-knowledge-expands-so-does-the-circumference). |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | After the Big Bang, the universe was left already expanding. Imagine sitting in a car. You step on the gas and get it to top speed. Then you put it in neutral and turn off the engine. What happens? You keep moving forward. But why? The car can't take off by itself. Friction should prevent it from moving. This answer is obvious, the car keeps moving because it has inertia; momentum. Similarly, the universe kept expanding initially; back when radiation and matter dominated the universe. In those eras, gravity, as you'd expect, caused expansion to slow. Much like friction and air resistance slows your car. Then, when dark energy became dominant in the universe, its negative pressure caused the universe to begin accelerated expansion. Dark energy is like negative friction. I know that doesn't make sense, but you have to expect that not every crazy and wonderful thing in the universe has a simple analogy to things in everyday life.
I see in John Rennie's answer, he described dark energy as a sort of anti-gravity. Here, I describe it as a form of energy itself that counteracts the gravitational influence of normal matter and radiation. You might think those are two different things and that only one of us can be right, but no! Dark energy can easily be described as either a part of gravity or as a form of energy. It's completely up to you. Both are valid and each just represents where you want to include dark energy in the gravity vs. matter-energy equation.
But Jim, you absent-minded artichoke, you forgot to mention why the universe had such a large initial expansion in the first place. Oops, you're right. We can't give you a single good, accepted reason for the initial expansion of the Big Bang. But we can tell you that very soon after the initial curvature singularity (that's the Big Bang), if it existed, inflation drove expansion. This was the part where you stepped on the gas. Inflatons, which are quasi-particle things present during inflation, caused the universe to expand almost exponentially. If you don't like comparing it to stepping on the gas, then it's like if the car started on a large hill. In park, nothing happens. But put the car in neutral and it'll just start rolling down the hill and then continue once it hits the level area at the bottom. Still with me?
Now let me be clear, in my analogy, the car doesn't represent any galaxies or matter or nonsense like that (us cosmologists don't really care about anything *in* the universe), it represents the expansion of space itself. Because that's what's expanding; space. The speed of the car represents the rate of expansion; basically the amount of distance that's added per second between two distinct points some initial distance apart. So when I say dark energy drives acceleration of expansion, that's like stepping on the gas. The car accelerates, representing an increase in the rate of space expansion.
Now some of you readers out there may be thinking "But Jim, you foggy London morning, you're still unclear". That may be true (the unclear part. I resent being called a morning), and if something is still bothering anyone about this, I can point you to some excellent other posts on the site that speak about the expansion of space or any other weird and wonderful cosmological ideas. But for now, I think the question is sufficiently answered, so I'm going to end there. | Ok I am no professional physicist, so feel free to scrap this if you want to, but as I have had explained to me: the expansion of space is the phenomenon that distances increase, *without* relating to any motion.
It is the space in between atoms and galaxies that gets "stretched", not that objects "move" away from each other. Like you blow a ballon up, points on the balloon get further away, but it is because of the fabric of reality itself that is expanding and not any motion of the matter in it. |
276,351 | We live in an expanding universe - so I'm told. But how can that be possible? Everything imaginable is attracted by a bigger thing. So, why can't gravitation stop the expansion of the universe? I know the "Big Bang" theory, but is it possible that the expansion of the universe is caused by the attraction of a bigger object? | 2016/08/25 | [
"https://physics.stackexchange.com/questions/276351",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/45820/"
] | Suppose you throw a ball up into the air. You could ask how the ball manages to move upwards when gravity is pulling it down, and the answer is that it started with an upwards velocity. Gravity pulls on the ball and slows it down so it will eventually reach a maximum height and fall back, but the ball manages to move upwards against gravity because of its initial velocity.
Basically the same is true of the expansion of the universe. A moment after the Big Bang everything in the universe was expanding away from everything else with an extremely high velocity. In fact if we extrapolate back to time zero those velocities become infinite. In the several billion years following the Big Bang gravity was slowing the expansion, in basically the same way gravity slows the ball you threw upwards, but the gravity didn't stop the expansion - it only slowed it.
The obvious next question is how did the universe get to start off expanding with such high velocities, and the answer is that we don't know because we have no theory telling us what happened at the Big Bang.
There is a slight complication that I'll mention in case anyone is interested: dark energy acts as a sort of anti-gravity and makes the expansion faster not slower. This has only become an important effect in the last few billion years, but as a result of dark energy right now gravity isn't slowing the expansion at all - in fact it's making the expansion faster. | Something the other answers don't really delve into is this: **Space itself is what's expanding**
Let's think about a regular Newtonian Spacetime with zero expansion, borrowing Jim's example of a car on the road. You're sitting completely still, as is a friend you're following on a roadtrip, with about a hundred feet of distance between you. If I move towards them at a few feet per second, then my distance is going to decrease at the same rate. I'll also be approaching another car a few hundred feet ahead of them at the same speed, because again none of us are moving.
Now, if we were in a classical, flat, non-expanding spacetime that's more or less what we'd see. Galaxies would gravitationally attract, and eventually (Meaning over a literally infinite timeframe) everything would re-merge.
This is where things get bizzare, and well outside the scope of our daily experience. We're not on a road as we know it, **The road itself is growing. Space itself is expanding.**
Imagine that, somehow, every 10 feet of road is growing an extra foot every second. If I were standing still, I'd see my friend move away from me at about 10 ft/s for the first second. A car 500 feet away would move away at 50 ft/s, and a car a mile away would rocket off at **over 500 ft/s** If I started moving towards my friend at 20 ft/s, I'd only see him getting closer at a rate of 10 ft/s, and the car a mile away would still be speeding into the distance faster than I could catch up to it.
This is where the idea of the Observable Universe comes from. There are points in space that we can never see, because they're "expanding" away from us faster than the speed of light. |
2,798,089 | I would need to get tweets from my twitter account on my wordpress site. Okey, the basics i could do, but there is one special need. I would need to get only certain tweets. Tweets that have some #hashstag for example only tweets with hashtag #myss would show up on my wordpress site.
Is there ready made plugin for this? I have been googlein for hours but have found only basic/normal twitter plugins.
Also i would need to able style the feed to look same as my current site.
Cheers! | 2010/05/09 | [
"https://Stackoverflow.com/questions/2798089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336676/"
] | The twitter API is pretty good at doing this sort of thing.
You could use the Twitter Search API to construct a url like the following:
```
http://search.twitter.com/search.json?q=from:yourusername+AND+#hashtag
```
You could easily write some javascript to parse this.
```
$.getJSON('http://search.twitter.com/search.json?q=from:yourusername+AND+#hashtag&callback=?', function(data){
$.each(data, function(index, item){
$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p>' + relative_time(item.created_at) + '</p></div>');
});
});
```
You could quite easily package this into a wordpress plugin. | Go to <http://search.twitter.com/> and enter the hashtag you want. Then click on 'Feed for this query' in the top right hand corner to get a URL. Then add a normal RSS widget to your wordpress site adding the URL you got previously. That should work. |
2,798,089 | I would need to get tweets from my twitter account on my wordpress site. Okey, the basics i could do, but there is one special need. I would need to get only certain tweets. Tweets that have some #hashstag for example only tweets with hashtag #myss would show up on my wordpress site.
Is there ready made plugin for this? I have been googlein for hours but have found only basic/normal twitter plugins.
Also i would need to able style the feed to look same as my current site.
Cheers! | 2010/05/09 | [
"https://Stackoverflow.com/questions/2798089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336676/"
] | The twitter API is pretty good at doing this sort of thing.
You could use the Twitter Search API to construct a url like the following:
```
http://search.twitter.com/search.json?q=from:yourusername+AND+#hashtag
```
You could easily write some javascript to parse this.
```
$.getJSON('http://search.twitter.com/search.json?q=from:yourusername+AND+#hashtag&callback=?', function(data){
$.each(data, function(index, item){
$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p>' + relative_time(item.created_at) + '</p></div>');
});
});
```
You could quite easily package this into a wordpress plugin. | There is a plugin called :
**Twitter Hash Tag Widget** : A widget for displaying the most recent twitter status updates for a particular hash tag.
<http://sivel.net/2009/06/twitter-hash-tag-widget/>
and
**Twitter tools** :
Twitter Tools is a plugin that creates a complete integration between your WordPress blog and your Twitter account.
<http://wordpress.org/extend/plugins/twitter-tools>
and
**twitter blender** : Better than Twitter's own widgets - Tweet Blender is tag-aware and has support for multiple authors, lists, hashtags, and keywords all blended together. The plugin can show tweets from just one user or a list of users (as all other Twitter plugins do); however, it can also show tweets for a topic which you can define via Twitter hashtag or keyword. But there is more! It can also show tweets for multiple authors AND multiple lists AND multiple keywords AND multiple hashtags all blended together into a single stream.
<http://wordpress.org/extend/plugins/tweet-blender/>
Hope any of those help :) |
1,241,853 | I have written some code to experiment with opengl programming on Ubuntu, its been a little while but I used to have a reasonable understanding of C. Since c++ i'm told is the language of choice for games programming I am trying to develop with it.
This is my first real attempt at opengl with sdl and I have gotten to this far, it compiles and runs but my camera function doesn't seem to do anything. I know there is probably a lot better ways to do this sort of stuff but I wanted to get the basics before I moved on to more advanced stuff.
main.cpp
```
#include <iostream>
#include <cmath>
#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
int screen_width = 640;
int screen_height = 480;
const int screen_bpp = 32;
float rotqube = 0.9f;
float xpos = 0, ypos = 0, zpos = 0, xrot = 0, yrot = 0, angle=0.0;
float lastx, lasty;
SDL_Surface *screen = NULL; // create a default sdl_surface to render our opengl to
void camera (void) {
glRotatef(xrot,1.0,0.0,0.0); // x-axis (left and right)
glRotatef(yrot,0.0,1.0,0.0); // y-axis (up and down)
glTranslated(-xpos,-ypos,-zpos); // translate the screen to the position
SDL_GL_SwapBuffers();
}
int DrawCube(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f, 0.0f,-7.0f);
glRotatef(rotqube,0.0f,1.0f,0.0f);
glRotatef(rotqube,1.0f,1.0f,1.0f);
glBegin(GL_QUADS);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glColor3f(1.0f,0.5f,0.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor3f(1.0f,1.0f,0.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glColor3f(1.0f,0.0f,1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glEnd();
SDL_GL_SwapBuffers();
rotqube +=0.9f;
return true;
}
bool init_sdl(void)
{
if( SDL_Init( SDL_INIT_EVERYTHING ) != 0 )
{
return false;
}
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
// TODO: Add error check to this screen surface init
screen = SDL_SetVideoMode( screen_width, screen_height, screen_bpp, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE );
return true;
}
static void init_opengl()
{
float aspect = (float)screen_width / (float)screen_height;
glViewport(0, 0, screen_width, screen_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, aspect, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0, 0.0 ,0.0, 0);
glEnable(GL_DEPTH_TEST);
}
void heartbeat()
{
float xrotrad, yrotrad;
int diffx, diffy;
SDL_Event event;
while(1)
{
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
exit(0);
break;
case SDLK_w:
yrotrad = (yrot / 180 * 3.141592654f);
xrotrad = (xrot / 180 * 3.141592654f);
xpos += (float)sin(yrotrad);
zpos -= (float)cos(yrotrad);
ypos -= (float)sin(xrotrad);
std::cout << "w pressed" << std::endl;
break;
case SDLK_s:
yrotrad = (yrot / 180 * 3.141592654f);
xrotrad = (xrot / 180 * 3.141592654f);
xpos -= (float)sin(yrotrad);
zpos += (float)cos(yrotrad);
ypos += (float)sin(xrotrad);
break;
case SDLK_d:
yrotrad = (yrot / 180 * 3.141592654f);
xpos += (float)cos(yrotrad) * 0.2;
zpos += (float)sin(yrotrad) * 0.2;
break;
case SDLK_a:
yrotrad = (yrot / 180 * 3.141592654f);
xpos -= (float)cos(yrotrad) * 0.2;
zpos -= (float)sin(yrotrad) * 0.2;
break;
default:
break;
}
break;
case SDL_MOUSEMOTION:
diffx=event.motion.x-lastx; //check the difference between the current x and the last x position
diffy=event.motion.y-lasty; //check the difference between the current y and the last y position
lastx=event.motion.x; //set lastx to the current x position
lasty=event.motion.y; //set lasty to the current y position
xrot += (float)diffy; //set the xrot to xrot with the addition of the difference in the y position
yrot += (float)diffx; //set the xrot to yrot with the addition of the difference in the x position
break;
case SDL_QUIT:
exit(0);
break;
case SDL_VIDEORESIZE:
screen = SDL_SetVideoMode( event.resize.w, event.resize.h, screen_bpp, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE );
screen_width = event.resize.w;
screen_height = event.resize.h;
init_opengl();
std::cout << "Resized to width: " << event.resize.w << " height: " << event.resize.h << std::endl;
break;
default:
break;
}
}
DrawCube();
camera();
SDL_Delay( 50 );
}
}
int main(int argc, char* argv[])
{
if( init_sdl() != false )
{
std::cout << "SDL Init Successful" << std::endl;
}
init_opengl();
std::cout << "Hello World" << std::endl;
heartbeat(); // this is essentially the main loop
SDL_Quit();
return 0;
}
```
Makefile
```
all:
g++ -o test main.cpp -lSDL -lGL -lGLU
```
It compiles and runs, I guess I just need some help with doing the camera translation. Thanks | 2009/08/06 | [
"https://Stackoverflow.com/questions/1241853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/152122/"
] | Remove the glLoadIdentity() call from DrawCube(). Replace it with glPushMatrix() at the beginning and glPopMatrix() at the end. Now pressing 'w' does something. (I am not entirely sure what it is supposed to do.)
The problem is glLoadIdentity clears all the previous transformations set up with glTranslatef and the like. Detailed description: <http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushmatrix.html> | Try rendering the camera before drawing the cube. Right now the camera translation is working fine, but you're drawing the cube in the same position relative to the camera. If you draw the cube first, then move the camera, you should see the translation you were expecting. |
4,923,084 | I am working in an ISP company. We are developing a speed tester for our customers, but running into some issues with TCP speed testing.
One client had a total time duration on 102 seconds transferring 100 MB with a packet size of 8192. 100.000.000 / 8192 = 12.202 packets. If the client sends an ACK every other packet that seems like a lot of time just transmitting the ACKs. Say the client sends 6000 ACKs and the RTT is 15ms - that's 6000 \* 7.5 = 45.000ms = 45 seconds just for the ACKs?
If I use this calculation for Mbit/s:
```
(((sizeof_download_in_bytes / durationinseconds) /1000) /1000) * 8 = Mbp/s
```
I will get the result in Mbp/s, but then the higher the TTL is between the sender and the client the lower the Mbp/s speed will become.
To simulate that the user is closer to the server, would it be "legal" to remove the ACK response time in the final result on the Mbp/s? This would be like simulating the enduser is close to the server?
So I would display this calculation to the end user:
```
(((sizeof_download_in_bytes / (durationinseconds - 45sec)) /1000)/1000) * 8 = Mbp/s
```
Is that valid? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4923084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527992/"
] | **HTML5 is still a draft**. Firefox 3.6 doesn't completely support HTML5 yet.
And according to the [HTML4 spec](http://www.w3.org/TR/REC-html40/struct/global.html#edef-ADDRESS), `address` can only contain `inline` elements:
```
<!ELEMENT ADDRESS - - (%inline;)* -- information on author -->
<!ATTLIST ADDRESS
%attrs; -- %coreattrs, %i18n, %events --
>
```
This is why Firefox considers it invalid and your page breaks. | Add display block to CSS. And then, add the clear\_both div before closing the address.
This will fix **any** problems with block elements inside an inline ones.
Your CSS:
```
#header-container address {display: block; float: right; margin-top: 25px;}
.clear { clear: both; }
```
HTML:
```
<div id="header-container">
<address>
<ul>
<li>lorem ipsum</li>
<li>(xxx) xxx-xxxx</li>
</ul>
<div class="clear"></div>
</address>
</div>
``` |
4,923,084 | I am working in an ISP company. We are developing a speed tester for our customers, but running into some issues with TCP speed testing.
One client had a total time duration on 102 seconds transferring 100 MB with a packet size of 8192. 100.000.000 / 8192 = 12.202 packets. If the client sends an ACK every other packet that seems like a lot of time just transmitting the ACKs. Say the client sends 6000 ACKs and the RTT is 15ms - that's 6000 \* 7.5 = 45.000ms = 45 seconds just for the ACKs?
If I use this calculation for Mbit/s:
```
(((sizeof_download_in_bytes / durationinseconds) /1000) /1000) * 8 = Mbp/s
```
I will get the result in Mbp/s, but then the higher the TTL is between the sender and the client the lower the Mbp/s speed will become.
To simulate that the user is closer to the server, would it be "legal" to remove the ACK response time in the final result on the Mbp/s? This would be like simulating the enduser is close to the server?
So I would display this calculation to the end user:
```
(((sizeof_download_in_bytes / (durationinseconds - 45sec)) /1000)/1000) * 8 = Mbp/s
```
Is that valid? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4923084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527992/"
] | **HTML5 is still a draft**. Firefox 3.6 doesn't completely support HTML5 yet.
And according to the [HTML4 spec](http://www.w3.org/TR/REC-html40/struct/global.html#edef-ADDRESS), `address` can only contain `inline` elements:
```
<!ELEMENT ADDRESS - - (%inline;)* -- information on author -->
<!ATTLIST ADDRESS
%attrs; -- %coreattrs, %i18n, %events --
>
```
This is why Firefox considers it invalid and your page breaks. | An unordered list cannot be wrapped inside of a address tag. I checked using firebug and Firefox moves the close address tag before the unordered list. |
4,923,084 | I am working in an ISP company. We are developing a speed tester for our customers, but running into some issues with TCP speed testing.
One client had a total time duration on 102 seconds transferring 100 MB with a packet size of 8192. 100.000.000 / 8192 = 12.202 packets. If the client sends an ACK every other packet that seems like a lot of time just transmitting the ACKs. Say the client sends 6000 ACKs and the RTT is 15ms - that's 6000 \* 7.5 = 45.000ms = 45 seconds just for the ACKs?
If I use this calculation for Mbit/s:
```
(((sizeof_download_in_bytes / durationinseconds) /1000) /1000) * 8 = Mbp/s
```
I will get the result in Mbp/s, but then the higher the TTL is between the sender and the client the lower the Mbp/s speed will become.
To simulate that the user is closer to the server, would it be "legal" to remove the ACK response time in the final result on the Mbp/s? This would be like simulating the enduser is close to the server?
So I would display this calculation to the end user:
```
(((sizeof_download_in_bytes / (durationinseconds - 45sec)) /1000)/1000) * 8 = Mbp/s
```
Is that valid? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4923084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527992/"
] | An unordered list cannot be wrapped inside of a address tag. I checked using firebug and Firefox moves the close address tag before the unordered list. | Add display block to CSS. And then, add the clear\_both div before closing the address.
This will fix **any** problems with block elements inside an inline ones.
Your CSS:
```
#header-container address {display: block; float: right; margin-top: 25px;}
.clear { clear: both; }
```
HTML:
```
<div id="header-container">
<address>
<ul>
<li>lorem ipsum</li>
<li>(xxx) xxx-xxxx</li>
</ul>
<div class="clear"></div>
</address>
</div>
``` |
29,346,480 | I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
```
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
```
Any ideas?
Expected output is a simple 3X3 table with the values from the array | 2015/03/30 | [
"https://Stackoverflow.com/questions/29346480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775597/"
] | This should work for you:
(See that I added a `tr` at the start and end before and after the foreach loop. Also I changed the quotes to double quotes and made sure you append the text everywhere.)
```
<?php
$array = ['0','1','2','3','4','5','6'];
$table = "<table class='table'><tbody><tr>";
//^^^^ See here the start of the first row
foreach($array as $a => $v) {
$table .= "<td>$v</td>";
//^ ^ double quotes for the variables
if(($a+1) % 3 == 0)
$table .= "</tr><tr>";
}
$table .= "</tr></tbody></table>";
//^ ^^^^^ end the row
//| append the text and don't overwrite it at the end
echo $table;
?>
```
output:
```
<table class='table'>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
</tbody>
</table>
``` | Use this you may looking for this
```
<?php
echo('<table><tr>');
$i = 0;
foreach( $array as $product )
{
$i++;
echo '<td>'.$product .'</td>';
if($i % 3==0)
{
echo '</tr><tr>';
}
}
echo'</tr></table>';
?>
```
**Result Here:**
```
<table>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data4</td>
<td>data5</td>
<td>data6</td>
</tr>
</table>
``` |
29,346,480 | I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
```
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
```
Any ideas?
Expected output is a simple 3X3 table with the values from the array | 2015/03/30 | [
"https://Stackoverflow.com/questions/29346480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775597/"
] | Use this you may looking for this
```
<?php
echo('<table><tr>');
$i = 0;
foreach( $array as $product )
{
$i++;
echo '<td>'.$product .'</td>';
if($i % 3==0)
{
echo '</tr><tr>';
}
}
echo'</tr></table>';
?>
```
**Result Here:**
```
<table>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data4</td>
<td>data5</td>
<td>data6</td>
</tr>
</table>
``` | Here is an easy solution with incrementing that works with a dynamically generated table like the one in Magento product view page to help display product attributes in two table columns preceded by attribute label -> practically we have 4 table columns together with attribute labels. This is useful for products with multiple attributes that take a long page to display.
```
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
if($_additional = $this->getAdditionalData()): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="table table-bordered table-hover" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php $i = 1; ?>
<tr>
<?php foreach ($_additional as $_data): ?>
<?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) != '')) { ?>
<th style="width: 20%;"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data" style="width:20%;"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
<?php $i++; if($i > 1 && ($i & 1) ) echo "</tr><tr>";?>
<?php } ?>
<?php endforeach; ?>
</tr>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>
``` |
29,346,480 | I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
```
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
```
Any ideas?
Expected output is a simple 3X3 table with the values from the array | 2015/03/30 | [
"https://Stackoverflow.com/questions/29346480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775597/"
] | This should work for you:
(See that I added a `tr` at the start and end before and after the foreach loop. Also I changed the quotes to double quotes and made sure you append the text everywhere.)
```
<?php
$array = ['0','1','2','3','4','5','6'];
$table = "<table class='table'><tbody><tr>";
//^^^^ See here the start of the first row
foreach($array as $a => $v) {
$table .= "<td>$v</td>";
//^ ^ double quotes for the variables
if(($a+1) % 3 == 0)
$table .= "</tr><tr>";
}
$table .= "</tr></tbody></table>";
//^ ^^^^^ end the row
//| append the text and don't overwrite it at the end
echo $table;
?>
```
output:
```
<table class='table'>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
</tbody>
</table>
``` | Here is an easy solution with [`array_chunk()`](http://php.net/manual/en/function.array-chunk.php):
```
<?php
$array = array('0','1','2','3','4','5','6');
$d = array_chunk($array, 3);
$table = "<table border='1' class='table'><tbody>";
foreach($d as $v)
$table .= "<tr><td>" . implode("</td><td>", $v) . "</td></tr>";
$table .= "</tbody></table>";
echo $table;
?>
``` |
29,346,480 | I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
```
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
```
Any ideas?
Expected output is a simple 3X3 table with the values from the array | 2015/03/30 | [
"https://Stackoverflow.com/questions/29346480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775597/"
] | This should work for you:
(See that I added a `tr` at the start and end before and after the foreach loop. Also I changed the quotes to double quotes and made sure you append the text everywhere.)
```
<?php
$array = ['0','1','2','3','4','5','6'];
$table = "<table class='table'><tbody><tr>";
//^^^^ See here the start of the first row
foreach($array as $a => $v) {
$table .= "<td>$v</td>";
//^ ^ double quotes for the variables
if(($a+1) % 3 == 0)
$table .= "</tr><tr>";
}
$table .= "</tr></tbody></table>";
//^ ^^^^^ end the row
//| append the text and don't overwrite it at the end
echo $table;
?>
```
output:
```
<table class='table'>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
</tbody>
</table>
``` | Here is an easy solution with incrementing that works with a dynamically generated table like the one in Magento product view page to help display product attributes in two table columns preceded by attribute label -> practically we have 4 table columns together with attribute labels. This is useful for products with multiple attributes that take a long page to display.
```
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
if($_additional = $this->getAdditionalData()): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="table table-bordered table-hover" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php $i = 1; ?>
<tr>
<?php foreach ($_additional as $_data): ?>
<?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) != '')) { ?>
<th style="width: 20%;"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data" style="width:20%;"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
<?php $i++; if($i > 1 && ($i & 1) ) echo "</tr><tr>";?>
<?php } ?>
<?php endforeach; ?>
</tr>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>
``` |
29,346,480 | I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
```
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
```
Any ideas?
Expected output is a simple 3X3 table with the values from the array | 2015/03/30 | [
"https://Stackoverflow.com/questions/29346480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775597/"
] | Here is an easy solution with [`array_chunk()`](http://php.net/manual/en/function.array-chunk.php):
```
<?php
$array = array('0','1','2','3','4','5','6');
$d = array_chunk($array, 3);
$table = "<table border='1' class='table'><tbody>";
foreach($d as $v)
$table .= "<tr><td>" . implode("</td><td>", $v) . "</td></tr>";
$table .= "</tbody></table>";
echo $table;
?>
``` | Here is an easy solution with incrementing that works with a dynamically generated table like the one in Magento product view page to help display product attributes in two table columns preceded by attribute label -> practically we have 4 table columns together with attribute labels. This is useful for products with multiple attributes that take a long page to display.
```
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
if($_additional = $this->getAdditionalData()): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="table table-bordered table-hover" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php $i = 1; ?>
<tr>
<?php foreach ($_additional as $_data): ?>
<?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) != '')) { ?>
<th style="width: 20%;"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data" style="width:20%;"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
<?php $i++; if($i > 1 && ($i & 1) ) echo "</tr><tr>";?>
<?php } ?>
<?php endforeach; ?>
</tr>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>
``` |
70,053,288 | I have a **timeseries data** of **5864 ICU Patients** and my dataframe is like this. Each row is the ICU stay of respective patient at a particular hour.
| HR | SBP | DBP | ICULOS | Sepsis | P\_ID |
| --- | --- | --- | --- | --- | --- |
| 92 | 120 | 80 | 1 | 0 | 0 |
| 98 | 115 | 85 | 2 | 0 | 0 |
| 93 | 125 | 75 | 3 | 1 | 0 |
| 95 | 130 | 90 | 4 | 1 | 0 |
| 102 | 120 | 80 | 1 | 0 | 1 |
| 109 | 115 | 75 | 2 | 0 | 1 |
| 94 | 135 | 100 | 3 | 0 | 1 |
| 97 | 100 | 70 | 4 | 1 | 1 |
| 85 | 120 | 80 | 5 | 1 | 1 |
| 88 | 115 | 75 | 6 | 1 | 1 |
| 93 | 125 | 85 | 1 | 0 | 2 |
| 78 | 130 | 90 | 2 | 0 | 2 |
| 115 | 140 | 110 | 3 | 0 | 2 |
| 102 | 120 | 80 | 4 | 0 | 2 |
| 98 | 140 | 110 | 5 | 1 | 2 |
I want to select the ICULOS where Sepsis = 1 (first hour only) based on patient ID. Like in P\_ID = 0, Sepsis = 1 at ICULOS = 3. I did this on a single patient (the dataframe having data of only a single patient) using the code:
```
x = df[df['Sepsis'] == 1]["ICULOS"].values[0]
print("ICULOS at which Sepsis Label = 1 is:", x)
# Output
ICULOS at which Sepsis Label = 1 is: 46
```
If I want to check it for each P\_ID, I have to do this 5864 times. Can someone help me with the code using a loop? The loop will go to each P\_ID and then give the result of ICULOS where Sepsis = 1. Looking forward for help. | 2021/11/21 | [
"https://Stackoverflow.com/questions/70053288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I edited my suggestion.. hope I understood better what u looking for. | After you initial code, here's the suggestion:
n=3
init\_n=1
while len(l) > n+init\_n:
```
l.pop(n+init_n-1)
init_n = init_n + n -1
```
print (list) |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You're mixing types. It doesn't know how to compare a string (`test`) to a char (`str[4]`).
If you change test to a `char` that will work fine. Or reference the specific character within test you want to compare such as `if (test[0] == str[4])` it should compile and run.
However, as this is merely an example and not really the true question what you'll want to do is look at the [functionality](http://en.cppreference.com/w/cpp/string/basic_string) that the `std::string` class supplies | Also you need `"D"` to be a char value not a string value if you are comparing it like that.
```
std::string myString = "Hello World";
const char *myStringChars = myString.c_str();
```
You have to turn it into a char array before can access it. Unless you do.
```
str.at(i);
```
which you can also write as
`str[i]` <-- what you did.
Essentially, this all boils down to test needs to initialized like `char test = 'D';`
Final Output..
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
char test = 'D';
if (test == str[4]) { // This line causes NO problems
cout << test << endl;
}
return 0;
}
``` |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You need to convert str[4] (which is a char) to a string before you can compare it to another string. Here's a simple way to do this
```
if (test == string(1, str[4])) {
``` | You're mixing types. It doesn't know how to compare a string (`test`) to a char (`str[4]`).
If you change test to a `char` that will work fine. Or reference the specific character within test you want to compare such as `if (test[0] == str[4])` it should compile and run.
However, as this is merely an example and not really the true question what you'll want to do is look at the [functionality](http://en.cppreference.com/w/cpp/string/basic_string) that the `std::string` class supplies |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | `str[4]` is a `char` type, which will not compare with a `string`.
Compare apples with apples.
Use
```
test[0] == str[4]
```
instead. | I think you might be mixing python with c++. In c++ `'g'` refers to a single character `g` not a string of length 1. "g" refers to an array (string) which is 1 character long and looks like ['g']. So as you can see, if you compare a single character to an array of characters no matter if the array is a single character long, this operation is not defined.
This will work if define it yourself by building a class which is able to compare string of one character long to a single character. Or just overload the `==` operator for doing just that
Example:
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
bool operator == ( const string &lh, const char &rh) {
if (lh.length() == 1) return lh[0] == rh;
return 0;
}
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) {
cout << test << endl;
}
else cout << "Not a match\n";
return 0;
}
``` |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You're mixing types. It doesn't know how to compare a string (`test`) to a char (`str[4]`).
If you change test to a `char` that will work fine. Or reference the specific character within test you want to compare such as `if (test[0] == str[4])` it should compile and run.
However, as this is merely an example and not really the true question what you'll want to do is look at the [functionality](http://en.cppreference.com/w/cpp/string/basic_string) that the `std::string` class supplies | I think you might be mixing python with c++. In c++ `'g'` refers to a single character `g` not a string of length 1. "g" refers to an array (string) which is 1 character long and looks like ['g']. So as you can see, if you compare a single character to an array of characters no matter if the array is a single character long, this operation is not defined.
This will work if define it yourself by building a class which is able to compare string of one character long to a single character. Or just overload the `==` operator for doing just that
Example:
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
bool operator == ( const string &lh, const char &rh) {
if (lh.length() == 1) return lh[0] == rh;
return 0;
}
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) {
cout << test << endl;
}
else cout << "Not a match\n";
return 0;
}
``` |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | `str[4]` is a `char` type, which will not compare with a `string`.
Compare apples with apples.
Use
```
test[0] == str[4]
```
instead. | You're comparing a char to a std::string, this is not a valid comparison.
You're looking for std::string::find, as follows:
```
if( test.find( str[4] ) != std::string::npos ) cout << test << "\n";
```
Note that this will return true if test *contains* `str[4]`. |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You need to convert str[4] (which is a char) to a string before you can compare it to another string. Here's a simple way to do this
```
if (test == string(1, str[4])) {
``` | I think you might be mixing python with c++. In c++ `'g'` refers to a single character `g` not a string of length 1. "g" refers to an array (string) which is 1 character long and looks like ['g']. So as you can see, if you compare a single character to an array of characters no matter if the array is a single character long, this operation is not defined.
This will work if define it yourself by building a class which is able to compare string of one character long to a single character. Or just overload the `==` operator for doing just that
Example:
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
bool operator == ( const string &lh, const char &rh) {
if (lh.length() == 1) return lh[0] == rh;
return 0;
}
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) {
cout << test << endl;
}
else cout << "Not a match\n";
return 0;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.