qid
int64 | question
string | date
string | metadata
list | response_j
string | response_k
string |
|---|---|---|---|---|---|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
I want to specifically address the first question in a way that it hasn't been yet.
>
> Q 1. What is the difference between a bisexual and a pansexual?
>
>
>
*Bisexualism* works only in a context where gender is binary. It assumes that people are only one of two possible genders—and that if you are bisexual you are attracted to both. But gender neutrality eliminates this dichotomy altogether.
(Note, too, that the distinction we now make between *sex* and *gender* is something only relatively recent.)
There are people who positively identify as gender-neutral (or as a non-binary gender). They do not consider themselves to be either gender. And while some *may* identify with various components on a sliding scale or spectrum (with one gender at one end and another gender at the other end), others consider themselves to have no gender identity at all, and still others consider themselves to have an identity that is simply "outside" any such binary scale.
In other words, some people who are gender neutral reject not only two possible genders but also the idea of a defining spectrum *between* two genders. (At least with respect to themselves.)
From an interesting article called "[10 things you always wanted to know about being non-binary but were afraid to ask](http://www.cbc.ca/news/canada/prince-edward-island/pei-non-binary-gender-sexuality-rory-starkman-russell-louder-1.4495208)":
>
> If you're looking at gender on a spectrum from male to female, *non-binary could be anywhere outside of that spectrum* [emphasis mine] or in between the male and female.
>
>
>
So, coming back to *pansexualism*, it *may* be somewhat misleading to say that somebody who is pansexual is attracted to all people "regardless of where they fit on a spectrum" (unless you also include everybody who isn't on that spectrum). Instead, I would say that they are simply attracted to people period, regardless of gender identity or non-identity.
---
Here is some additional information, as pulled from comments.
Although Dictionary.com says that a *bissexual* is attracted *to people of various gender identities*, both Merriam-Webster and Oxford continue to explicitly use a binary definition for the word. At least traditionally, a bisexual is attracted to both men and women. But (by some definitions), they would not be attracted to somebody who doesn't identify as male or female.
Practically speaking, *bisexualism* might amount to the same thing as *pansexualism*. But still, there is a logical distinction between "I like all colours" and "colour is irrelevant."
The definition of pansexual provided in the question states (the emphasis is mine) that: "Pansexual people may refer to themselves as **gender-blind**, asserting that **gender and sex are not determining factors in their romantic or sexual attraction to others**."
Somebody who is colour blind is literally not influenced by the choice of those colours they can't distinguish—except intellectually. That's what's meant by "gender blind" when it comes to pansexuality. Bisexuals can differentiate between genders (although they are attracted to both); but pansexuals simply don't differentiate between them at all (aside from intellectually).
To reuse an analogy from a different answer, I like steak and I like pasta. But when I go to a restaurant that has both on the menu, I decide which of those I want to eat on that particular night—which one I'm more in the mood for. However, for somebody without taste buds (somebody who is "taste blind") the flavour of those two menu items will have no bearing on their choice. For them, based on taste alone, the two are indistinguishable, and they might as well be contemplating the same thing. They will make their decision based on other factors (price, calories, size, and so on).
Similarly, consider a bisexual who's presented with a choice between a man and a woman. While they are attracted to both, they might be feeling more *partial* to one gender. It likely won't be the only factor in their choice of partner, but it will be at least *a* factor.
For a pansexual, who is "gender blind," it won't be a factor at all. They won't feel any more *partial* to a particular gender than any other at any given time, simply because it's not part of their perception. They are simply unaware of gender in any way—aside from intellectually. For them, their choice in partner is only (and always) about all of the non-gender factors.
---
As for the second question, this culture, and the terminology behind it, is so new that language and attitudes haven't yet had time to "shake out" into a cohesive consensus yet. That there is no agreement comes down to the timing of adoption.
(It was only in 2017 that both *The Chicago Manual of Style* and the *Associated Press Stylebook* acknowledged the use of *they* and *their* (and even *themself*) as an acceptable form of gender-neutral third-person pronoun if required—but *in particular* when used in the context of people who use it as part of their identify as having a non-binary gender.)
|
* Bisexuality *sensu lato* (in the broad sense) means that one is sexually attracted to both males and females; it makes no distinction as to whether or not one is sexually attracted to persons who are neither male nor female.
+ Bisexuality *sensu stricto* (in the narrow sense) means that one is sexually attracted to males and females, but *not* to non-male non-female persons.
+ Pansexuality means that one is sexually attracted to persons of all genders.
If gender is regarded as a spectrum, with more possible values than just MALE and FEMALE, a pansexual person would be bisexual *senso lato*, due to being sexually attracted to both males and females, but would not be bisexual *senso stricto*, due to also being attracted to non-male non-females.
If gender is regarded as strictly binary, with the only possible values being MALE and FEMALE, the distinction between the two subcategories of bisexuality *sensu lato* disappears, and bisexuality and pansexuality become synonymous.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
I want to specifically address the first question in a way that it hasn't been yet.
>
> Q 1. What is the difference between a bisexual and a pansexual?
>
>
>
*Bisexualism* works only in a context where gender is binary. It assumes that people are only one of two possible genders—and that if you are bisexual you are attracted to both. But gender neutrality eliminates this dichotomy altogether.
(Note, too, that the distinction we now make between *sex* and *gender* is something only relatively recent.)
There are people who positively identify as gender-neutral (or as a non-binary gender). They do not consider themselves to be either gender. And while some *may* identify with various components on a sliding scale or spectrum (with one gender at one end and another gender at the other end), others consider themselves to have no gender identity at all, and still others consider themselves to have an identity that is simply "outside" any such binary scale.
In other words, some people who are gender neutral reject not only two possible genders but also the idea of a defining spectrum *between* two genders. (At least with respect to themselves.)
From an interesting article called "[10 things you always wanted to know about being non-binary but were afraid to ask](http://www.cbc.ca/news/canada/prince-edward-island/pei-non-binary-gender-sexuality-rory-starkman-russell-louder-1.4495208)":
>
> If you're looking at gender on a spectrum from male to female, *non-binary could be anywhere outside of that spectrum* [emphasis mine] or in between the male and female.
>
>
>
So, coming back to *pansexualism*, it *may* be somewhat misleading to say that somebody who is pansexual is attracted to all people "regardless of where they fit on a spectrum" (unless you also include everybody who isn't on that spectrum). Instead, I would say that they are simply attracted to people period, regardless of gender identity or non-identity.
---
Here is some additional information, as pulled from comments.
Although Dictionary.com says that a *bissexual* is attracted *to people of various gender identities*, both Merriam-Webster and Oxford continue to explicitly use a binary definition for the word. At least traditionally, a bisexual is attracted to both men and women. But (by some definitions), they would not be attracted to somebody who doesn't identify as male or female.
Practically speaking, *bisexualism* might amount to the same thing as *pansexualism*. But still, there is a logical distinction between "I like all colours" and "colour is irrelevant."
The definition of pansexual provided in the question states (the emphasis is mine) that: "Pansexual people may refer to themselves as **gender-blind**, asserting that **gender and sex are not determining factors in their romantic or sexual attraction to others**."
Somebody who is colour blind is literally not influenced by the choice of those colours they can't distinguish—except intellectually. That's what's meant by "gender blind" when it comes to pansexuality. Bisexuals can differentiate between genders (although they are attracted to both); but pansexuals simply don't differentiate between them at all (aside from intellectually).
To reuse an analogy from a different answer, I like steak and I like pasta. But when I go to a restaurant that has both on the menu, I decide which of those I want to eat on that particular night—which one I'm more in the mood for. However, for somebody without taste buds (somebody who is "taste blind") the flavour of those two menu items will have no bearing on their choice. For them, based on taste alone, the two are indistinguishable, and they might as well be contemplating the same thing. They will make their decision based on other factors (price, calories, size, and so on).
Similarly, consider a bisexual who's presented with a choice between a man and a woman. While they are attracted to both, they might be feeling more *partial* to one gender. It likely won't be the only factor in their choice of partner, but it will be at least *a* factor.
For a pansexual, who is "gender blind," it won't be a factor at all. They won't feel any more *partial* to a particular gender than any other at any given time, simply because it's not part of their perception. They are simply unaware of gender in any way—aside from intellectually. For them, their choice in partner is only (and always) about all of the non-gender factors.
---
As for the second question, this culture, and the terminology behind it, is so new that language and attitudes haven't yet had time to "shake out" into a cohesive consensus yet. That there is no agreement comes down to the timing of adoption.
(It was only in 2017 that both *The Chicago Manual of Style* and the *Associated Press Stylebook* acknowledged the use of *they* and *their* (and even *themself*) as an acceptable form of gender-neutral third-person pronoun if required—but *in particular* when used in the context of people who use it as part of their identify as having a non-binary gender.)
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
>
> Q2. Why is there no agreement in the LGTBQ community for a single, simple term to express this gender and sexual preference?
>
>
>
A2. Because the LGTBQ is not a single speech community, that's why.
A speech community -- a bunch of people who talk (mostly) with one another -- is where agreements on single terms take place subliminally, and they have already taken place in the various real speech communities that constitute the membership of a brand-new sociopolitical merger so diverse that we need a five-letter acronym for it.
All over the world there are local L,G,T,B, and Q speech communities (sometimes not formally united, or simply not socially connected, into LGTBQ. Yet.) And they have been there for a long time. Many speak English. They have their own speech terms and their own meanings to go with them and their own histories and mythologies. These things don't blend together coherently very fast, especially under social pressure.
So it's unlikely that there **are** -- or even could be -- any single, simple terms so early. At this stage of development the norm is evanescent pansemantic trans/meaning-fluid terms.
|
Regarding question 1:
I think it's a matter of carefully reading the definitions. Bisexual means to be attracted to both men and women. Pansexual means to be attracted to people regardless of sex or gender identity.
To illustrate the difference, let's use food (because it's more relatable). Suppose you like pizza and pasta specifically then you could say you like both of those foods (possibly for different reasons). You could also like pizza and pasta **because** they are Italian food, you don't care about their difference, the mere fact that it's Italian does it for you.
The first example could be compared to bisexuality, they like both men and woman, possibly for different reasons. The term pansexual emphasises that they like both without emphasis on the gender. Think of the statement 'I like all Italian food', if you consider pizza and pasta Italian, then you like both of the specific examples. Having said that, the first is a subset of the latter. All pansexuals are also bisexual, but not all bisexuals have to be pansexuals.
Regarding question 2:
You already mentioned the term community, which is a good start for an answer. The community, in this case, is not organised like a government with one view point. To compare it with politics: take conservatives in the UK, they have mostly the same view points and are pressured to follow the party line.
Now look at the broader community, all conservatives in the world, they you could identify many sub-communities (the Conservative Party in the UK, the Republicans in the US, and so on for all the different countries, perhaps even multiple communities for a single country). As an outsider, two conservatives are just two conservatives, but on closer inspection they might turn out to have widely varying views.
The same goes for the LGBTQ community (or any other group of people defined by one thing: men, women, Americans, politicians, environmentalists, liberals, children, the elderly). In fact, I think you'll have difficulty finding any subset of people defined by one thing who almost unanimously agree on anything (why that is might be better suited for psychology.se, biology.se, or philosophy.se but even then you might not get all of them to agree on one answer ;) ).
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
>
> Q2. Why is there no agreement in the LGTBQ community for a single, simple term to express this gender and sexual preference?
>
>
>
A2. Because the LGTBQ is not a single speech community, that's why.
A speech community -- a bunch of people who talk (mostly) with one another -- is where agreements on single terms take place subliminally, and they have already taken place in the various real speech communities that constitute the membership of a brand-new sociopolitical merger so diverse that we need a five-letter acronym for it.
All over the world there are local L,G,T,B, and Q speech communities (sometimes not formally united, or simply not socially connected, into LGTBQ. Yet.) And they have been there for a long time. Many speak English. They have their own speech terms and their own meanings to go with them and their own histories and mythologies. These things don't blend together coherently very fast, especially under social pressure.
So it's unlikely that there **are** -- or even could be -- any single, simple terms so early. At this stage of development the norm is evanescent pansemantic trans/meaning-fluid terms.
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
The other answers are well-taken. To attempt a tl;dr:
>
> **Q1.** What *is* the difference between a bisexual and a pansexual?
>
>
>
The people? **Probably nothing**. But the difference between the ***terms*** '[bisexual](http://www.oed.com/view/Entry/19448)' and '[pansexual](http://www.oed.com/view/Entry/136944)' is that the former **implicitly assumes** two genders ('binary gender') or attraction to only two genders while the latter implies that there are more (possibly many more) than 'male' and 'female'. People who identify as pansexual may not have issues with bisexuals *per se* but probably consider their own terminology *more inclusive* of the [genderqueer](http://www.oed.com/view/Entry/77468?redirectedFrom=genderqueer#eid237081402).
>
> **Q2.** Why is there no agreement in the LGTBQ community for a single, simple term to express this gender and sexual preference?
>
>
>
**1st**, because people disagree about language choices *all the time* for no good reason at all. All the moreso when so many neologisms are dealing so closely with identity, sexuality, and politics. **2nd**, because 'the LGTBQ community' is *an expression*, not an actual gang that has regular conferences with a steering committee to hash out things in the interim. **3rd**, because those terms, especially as self-applied, are not precisely overlapping and do not imply a new set third gender but an openness to either conceiving of more than two or personally ignoring them, whatever and however many they are.
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
Regarding question 1:
I think it's a matter of carefully reading the definitions. Bisexual means to be attracted to both men and women. Pansexual means to be attracted to people regardless of sex or gender identity.
To illustrate the difference, let's use food (because it's more relatable). Suppose you like pizza and pasta specifically then you could say you like both of those foods (possibly for different reasons). You could also like pizza and pasta **because** they are Italian food, you don't care about their difference, the mere fact that it's Italian does it for you.
The first example could be compared to bisexuality, they like both men and woman, possibly for different reasons. The term pansexual emphasises that they like both without emphasis on the gender. Think of the statement 'I like all Italian food', if you consider pizza and pasta Italian, then you like both of the specific examples. Having said that, the first is a subset of the latter. All pansexuals are also bisexual, but not all bisexuals have to be pansexuals.
Regarding question 2:
You already mentioned the term community, which is a good start for an answer. The community, in this case, is not organised like a government with one view point. To compare it with politics: take conservatives in the UK, they have mostly the same view points and are pressured to follow the party line.
Now look at the broader community, all conservatives in the world, they you could identify many sub-communities (the Conservative Party in the UK, the Republicans in the US, and so on for all the different countries, perhaps even multiple communities for a single country). As an outsider, two conservatives are just two conservatives, but on closer inspection they might turn out to have widely varying views.
The same goes for the LGBTQ community (or any other group of people defined by one thing: men, women, Americans, politicians, environmentalists, liberals, children, the elderly). In fact, I think you'll have difficulty finding any subset of people defined by one thing who almost unanimously agree on anything (why that is might be better suited for psychology.se, biology.se, or philosophy.se but even then you might not get all of them to agree on one answer ;) ).
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
* Bisexuality *sensu lato* (in the broad sense) means that one is sexually attracted to both males and females; it makes no distinction as to whether or not one is sexually attracted to persons who are neither male nor female.
+ Bisexuality *sensu stricto* (in the narrow sense) means that one is sexually attracted to males and females, but *not* to non-male non-female persons.
+ Pansexuality means that one is sexually attracted to persons of all genders.
If gender is regarded as a spectrum, with more possible values than just MALE and FEMALE, a pansexual person would be bisexual *senso lato*, due to being sexually attracted to both males and females, but would not be bisexual *senso stricto*, due to also being attracted to non-male non-females.
If gender is regarded as strictly binary, with the only possible values being MALE and FEMALE, the distinction between the two subcategories of bisexuality *sensu lato* disappears, and bisexuality and pansexuality become synonymous.
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
46,159,310
|
I'm trying to format the footer of my app, and there are 3 things I want along the footer, all hyperlinks that I'd like on the same line.
```
<p><a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></p>
```
I'd like the About and Contact hyperlinks to align on the right side of the footer, like this.
[](https://i.stack.imgur.com/UTnvY.png)
But the code I wrote produces this:
[](https://i.stack.imgur.com/Ed53e.png)
I tried float and text-align but I may have done it incorrectly.
|
2017/09/11
|
[
"https://Stackoverflow.com/questions/46159310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7800355/"
] |
Just add a class and float it right with some padding:
<https://jsfiddle.net/cx5m40wu/>
```
<p><a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="Contact" class="alignRight">Contact</a>
<a asp-area="" asp-controller="Home" asp-action="About" class="alignRight">About</a></p>
.alignRight{
float: right;
padding-left: 15px;
}
```
|
I would recommend a different approach for the markup.
Use an `<ul>` (unordered list) inside a `<footer>` tag. Then, use `<li>` (list items) for each `<a>` anchor tag. This will be better for semantics and accessibility.
After having a proper HTML markup, you can proceed to style it with any method you like:
**Flexbox (recommended):**
```css
/* Unordered list */
.footer {
padding: 0;
margin: 0;
list-style-type: none;
display: flex;
}
/* List item */
.footer__item {
padding: 0 .5em;
}
/* Select the second item from last to first in case you add more items */
.footer__item:nth-last-child(2) {
margin-left: auto;
}
```
```html
<footer>
<ul class="footer">
<li class="footer__item">
<a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
</li>
</ul>
</footer>
```
**CSS Grid:**
```css
/* Unordered list */
.footer {
padding: 0;
margin: 0;
list-style-type: none;
display: grid;
grid-gap: 0 .5em;
grid-template-columns: repeat(3, auto);
}
/* Select the second item from last to first */
.footer__item:nth-last-child(2) {
margin-left: auto;
}
```
```html
<footer>
<ul class="footer">
<li class="footer__item">
<a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
</li>
</ul>
</footer>
```
**Floats:**
```css
/* Unordered lists */
.footer,
.footer__section {
padding: 0;
margin: 0;
list-style-type: none;
}
/* List item */
.footer__item {
float: left;
padding: 0 .5em;
}
/* Nested unordered list */
.footer__section {
float: right;
}
```
```html
<footer>
<ul class="footer">
<li class="footer__item">
<a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
</li>
<!-- Requires extra markup -->
<ul class="footer__section">
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
</li>
</ul>
</ul>
</footer>
```
|
46,159,310
|
I'm trying to format the footer of my app, and there are 3 things I want along the footer, all hyperlinks that I'd like on the same line.
```
<p><a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></p>
```
I'd like the About and Contact hyperlinks to align on the right side of the footer, like this.
[](https://i.stack.imgur.com/UTnvY.png)
But the code I wrote produces this:
[](https://i.stack.imgur.com/Ed53e.png)
I tried float and text-align but I may have done it incorrectly.
|
2017/09/11
|
[
"https://Stackoverflow.com/questions/46159310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7800355/"
] |
Just add a class and float it right with some padding:
<https://jsfiddle.net/cx5m40wu/>
```
<p><a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="Contact" class="alignRight">Contact</a>
<a asp-area="" asp-controller="Home" asp-action="About" class="alignRight">About</a></p>
.alignRight{
float: right;
padding-left: 15px;
}
```
|
Flexbox can do that:
```css
p {
display: flex;
}
p a:first-of-type {
margin-right: auto;
}
```
```html
<p><a href="mailto:[email protected]">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></p>
```
|
20,897,236
|
So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
```
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<a href="images/Tulip_large.jpg"><img src="images/Tulip_small.jpg" alt="Tulips"></a>
<a href="images/Colourful_Tulip_large.jpg"><img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips"></a>
<a href="images/Swan_large.jpg"><img src="images/Swan_small.jpg" alt="Swan on Lake"></a>
<a href="images/Red_Tulip_large.jpg"><img src="images/Red_Tulip_small.jpg" alt="Red Tulips"></a>
<a href="images/Sakura_Tree_large.jpg"><img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees"></a>
<a href="http://www.youtube.com/embed/1oHWvFrpocY?autoplay=1"><img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video"> </a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/ofr5EE9GsUs?autoplay=1"><img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video"></a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/9bZkp7q19f0?autoplay=1"><img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video"></a>
</div>
```
|
2014/01/03
|
[
"https://Stackoverflow.com/questions/20897236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152558/"
] |
Change the class attribute to id or add the id attribute `id="html5gallery"`
```
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
```
**EDIT:**
Try this to append image
```
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
```
|
I've never used the instagram API before, but I think this is what you want to achieve (code below). I've included both a Vanilla Javascript method as well as a jQuery method (so you can pick and use whichever one you prefer - vanilla is faster of course)
```
(function ($, window) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
// Define the gallery variable outside the for loop (performance)
// Vanilla JS
var galleryHTML = document.getElementById("html5gallery");
// jQuery
var $galleryHTML = $('#html5gallery');
// Moved the gallery outside of the for loop (performance, again)
var gallery = document.getElementById('gallery');
var insta = $('.insta');
// or var insta = document.getElementsByClassName('insta')[0] for vanilla JS
// create a function to do the fancy ajax
var fetchInstagram = function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
for (var i = 0; i < numDisplay; i++) {
// I don't think you need the onload function here
// img.onload = function() {
// document.getElementById('gallery').appendChild(img);
// };
// Not sure what this is, but I don't think you need it (for what you want to do)
// $(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
// Create the new image object
var newImage = document.createElement('img');
newImage.src = data.data[i].images.low_resolution.url;
// Insert the images into html5gallery
// Vanilla Javascript Way
// galleryHTML.appendChild(newImage);
// jQuery Way
// var $newImage = $(newImage);
// $galleryHTML.append($newImage);
}
}
});
};
// Making the function available in window for global use
window.fetchInstagram = fetchInstagram;
})(jQuery, window);
// Initiate the function
fetchInstagram();
// You can bind the function to other stuff like.. if you click a button
// $('#load-more').on('click', fetchInstagram);
```
I was able to get the 4 images to load in a div with the id of html5gallery on my end. Hope this helps!
|
20,897,236
|
So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
```
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<a href="images/Tulip_large.jpg"><img src="images/Tulip_small.jpg" alt="Tulips"></a>
<a href="images/Colourful_Tulip_large.jpg"><img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips"></a>
<a href="images/Swan_large.jpg"><img src="images/Swan_small.jpg" alt="Swan on Lake"></a>
<a href="images/Red_Tulip_large.jpg"><img src="images/Red_Tulip_small.jpg" alt="Red Tulips"></a>
<a href="images/Sakura_Tree_large.jpg"><img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees"></a>
<a href="http://www.youtube.com/embed/1oHWvFrpocY?autoplay=1"><img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video"> </a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/ofr5EE9GsUs?autoplay=1"><img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video"></a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/9bZkp7q19f0?autoplay=1"><img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video"></a>
</div>
```
|
2014/01/03
|
[
"https://Stackoverflow.com/questions/20897236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152558/"
] |
Change the class attribute to id or add the id attribute `id="html5gallery"`
```
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
```
**EDIT:**
Try this to append image
```
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
```
|
If the human eye can only see 24fps or 30fps or more when playing a game or watching tv, I believe a programer can use less DIVs in HTML within the screen size, with a Javascript array of 3 million colors for a couple of DIVs and cheat it's position(because of our human eyes), based in a timer event with a bunch of frames per second than the ones I mentioned, example 1 millisecond. In my opinion this is something which I would like to test, if it's the question that drives us let the answer be our destination.
This is the fiddle so far: [DEMO](http://jsfiddle.net/jobson111/h6FPX/)
```
<html>
<head>
<title></title>
<style>#placeDiv{position:absolute;left:0px;width:100px;height:100px;}
#placeDiv1{position:absolute;left:100px;width:100px;height:100px;}
#placeDiv2{position:absolute;left:200px;width:100px;height:100px;}
#b1{position:absolute;top:100px;left:0px}
#b2{position:absolute;top:100px;left:80px}
#b3{position:absolute;top:100px;left:170px}
#b4{position:absolute;top:100px;left:270px}
#b5{position:absolute;top:100px;left:320px}
</style>
</head>
<body>
<div id = "placeDiv">ok</div><div id = "placeDiv1">ok</div><div id = "placeDiv2">ok</div>
<button id="b1" onclick="forward()">Forward</button>
<button id="b2" onclick="backward()">Backward</button>
<button id="b3" onclick="skip2()">skip2</button>
<button id="b4" onclick="automatic()">auto</button>
<button id="b5" onclick="stop()">stop</button>
<script>
var myArray = ["black","yellow","green","red","blue","blue","black","gray"];
var myArray1 = ["yellow","blue","green","red","green","blue","black","gray"];
var myArray2 = ["yellow","blue","green","red","green","blue","black","gray"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
}; skip2=function(){
if(i == myArray.length-4)
{i+=2;alert("This is the iterator "+i)}else if(i==7){i=0}else{i=i+1;};
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;i=myArray1.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
//
}
var m=null;
automatic=function(){
clearInterval(m)
m = setInterval(function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
},1);
function b(x,y){
var a =setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if (x==100){d();clearInterval(a);}},10);
function d(){var z = setInterval(function(){document.getElementById("placeDiv").style.left=x--+"px";if (x==0){c();clearInterval(z);}},10);}
function c(){var g = setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if(x==100){d();clearInterval(g)}},10)};
//Aqui uma copia.
var v =setInterval(function(){document.getElementById("placeDiv").style.top=y+++"px";if (y==100){h();clearInterval(v);}},10);
function h(){var l = setInterval(function( {document.getElementById("placeDiv").style.top=y--+"px";if (y==0){ok();clearInterval(l);}},10);}
function ok(){var ja = setInterval(function( {document.getElementById("placeDiv").style.top=y+++"px";if(y==100 {h();clearInterval(ja)}},10)};
}
b(0,0);
stop=function(){clearInterval(m)};
};
</script>
</body>
</html>
```
|
248,161
|
Let $z\_1 , z\_2 $ be two complex numbers that satisfy:
$\dfrac{z\_2 } {\bar{z\_1}}= \frac{3}{8} \big(\cos(75^{\circ})+i\sin(75^{\circ})\big) $ ,
$z\_1 z\_2 ^2 = \frac{1}{3} \big(\cos(120^{\circ}) + i\sin(120^{\circ}) \big) $ .
How can I determine with of the following can be a possible value for $ \sqrt{z\_1} $ ?
(a) $ \frac{2}{\sqrt{3}} \mbox{cis}(135^{\circ}) $
(b) $ \frac{2}{3} \mbox{cis}(155^{\circ})$
(c) $ \frac{2}{\sqrt{3}} \mbox{cis}(195^{\circ}) $
(d) $ \frac{2}{\sqrt{3}} \mbox{cis}(175^{\circ}) $
(e) $ \frac{2}{3} \mbox{cis}(215^{\circ})$
thanks !!!
|
2012/11/30
|
[
"https://math.stackexchange.com/questions/248161",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/50436/"
] |
Assuming that each week is independent, we know that if $N$ is the number of employees taken on in a particular week, then $N$ has distribution:
$P(N=k) = e^{-0.1} \frac{0.1^k}{k!}$
So that,
$p:=P(N=0)=e^{-0.1}$,
which I'm calling $p$. Now, assuming we have an unlimited number of weeks, how can we not take on employees for exactly $Y$ weeks, no more no less.? Well we have to not take on employees for each week, a total of $Y$ weeks, but then take on at least one employee on the $Y+1$ week. The probability that we have 0 employees after $Y$ weeks is simply:
$P(\mbox{no employees after }Y\mbox{ weeks})=P(N=0)^Y=p^Y$
and the probability that we take on at least one employee on the $Y+1$ week is $1-P(N=0)=1-p$, so
$P(Y=n)=p^n(1-p)$
which is a geometric random variable, so that
$E(Y) = p/(1-p)$
|
Alex has answered part of the question.
The probability that more than one new employee is hired in a given week is $1$ minus the probability that only $0$ or $1$ new employees are hired. Thus it is
$$
1- \frac{0.1^0 e^{-0.1}}{0!} - \frac{0.1^1 e^{-0.1}}{1!} = 1 - e^{-0.1} - 0.1e^{-0.1}.
$$
Call this number $p$. Then we're looking for the probability of $1$ success in $50$ trials with probability $p$ of success on each trial --- thus a binomial distribution. The probability is
$$
\binom{50}{1} p^1 (1-p)^{50-1}.
$$
|
2,484,538
|
Let $A$ and $B$ from $M\_n(\mathbb{R})$ with $AB=BA$ and $\det(A+B) \geq 0$
Prove that $ \forall n \in \mathbb{N^{\*}} $, $\det (A^n + B^n) \geq 0 $
---
I tried to use induction but I got stuck.
|
2017/10/22
|
[
"https://math.stackexchange.com/questions/2484538",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/201437/"
] |
HINT:
You could use complex numbers. Consider the factorization
$$(X^n + 1) = \prod\_{\omega^n +1 = 0}( X- \omega)$$
The roots of the equation $X^n+1 = 0$ are complex, distinct, and conjugate in pairs, if $n$ is even, or $-1$, and $\frac{n-1}{2}$ pairs of conjugate roots, if $n$ is odd.
Since $A$, $B$ commute, we can write the equality in $M\_n(\mathbb{C})$
$$A^n + B^n = \prod\_{\omega^n + 1 = 0} (A - \omega B)$$
For $n$ even we get
$$A^n + B^n = \prod\_{\omega^n + 1= 0, \Re \omega >0}( A - \omega B) (A - \bar \omega B)$$ while for $n$ odd we get
$$A^n + B^n = (A+B) \cdot \prod\_{\omega^n + 1= 0, \Re \omega >0}( A - \omega B) (A - \bar \omega B)$$
Now take determinants and notice that
$$\det(A- \omega B) \det (A- \bar \omega B) = |\det(A- \omega B)|^2 \ge 0$$
|
Ok, I really like the answer by orangeskid.
However, I want to understand the solution outlined by Giuseppe Negro.
As he already noted, commuting diagonalizable matrices are simultaneously diagonalizable. So let us assume that $A=diag(a\_1, a\_2, \ldots a\_n)$ and $B=diag(b\_1, b\_2, \ldots b\_n)$. Then $$\det(A+B)=\prod\_{i=1}^n (a\_i+b\_i)$$ and $$\det(A^k+B^k)=\prod\_{i=1}^n (a\_i^k+b\_i^k)$$
So we have to prove that $\prod\_{i=1}^n (a\_i+b\_i) \geq0 $ implies $\prod\_{i=1}^n (a\_i^k+b\_i^k) \geq 0$.
If $n$ is even this is true for any $a\_i$ and $b\_i$ even without the assumption since any even power is non-negative.
If $n$ is odd then consider two cases. If $a\_i+b\_i =0$ for some k, then $a\_i^k+b\_i^k=0$ as well, so the implication is true. Let us consider case when $a\_i+b\_i \neq 0$ for any $i$. It is suffice to prove that $a\_i+b\_i$ have the same sign as $a\_i^k+b\_i^k$. If $a\_i$ and $b\_i$ have the same sign it is clear. If they have different signs then the sign of a sum is determined by maximum absolute value of a summands.
**Ok, how should we continue to get full solution?**
I have some very vague ideas about density, Zariski topology, and the fact that value of continuous (and thus polynomial) function is determined by its values on a dense subset, but I do not see if it is a good path.
First of all, I can prove that diagonalisable matrixes are dense it $M\_n(\mathbb{C})$, but I can not do it for $M\_n(\mathbb{R})$. Is it even true for $M\_n(\mathbb{R})$?
Second, we have the inequality and not the polynomial identity.
So please help me to finish the solution, I hope it will be useful for learning community.
Thanks a lot!!!
**Update**
I am able to prove that diagonalisable matrixes are **not** dense it $M\_n(\mathbb{R})$, so now this approach does not look promising, so please post your ideas!
|
878,022
|
I have the following data structure:
```
typedef vector< vector<int> > MxInt2d;
typedef vector< vector<double> > MxDouble2d;
class QSweep{
public:
....
static MxDouble2d myPoints_;
MxInt2d myEdges_;
MxInt2d sweepEvents;
class order{
public:
bool operator() (const vector<int>& edge1, const vector<int>& edge2){
return (myPoints_[edge1[0]][0]<myPoints_[edge2[0]][0])||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]<myPoints_[edge2[0]][1])
||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]==myPoints_[edge2[0]][1]&&
getSlope(myPoints_[edge1[0]][0],myPoints_[edge1[0][1],
myPoints_[edge1[1]][0],myPoints_[edge1[1]][1])
<
getSlope(myPoints_[edge2[0][0],myPoints_[edge2[0][1],
myPoints_[edge2[1]][0],myPoints_[edge2[1]][1]));
}
};
static double getSlope(double a, double b, double c, double d);
static double computeDet(double a, double b, double c, double d, double x, double y);
```
};
I use the functor for order() when defining the constructor in the following way:
```
QSweep::QSweep(const MxDouble2d& myPoints, const MxInt2d& myEdges){
....
//code here for initializing myPoints_, myEdges_
sort(myEdges_.begin(),myEdges_.end(),order());
}
```
In this way my data myEdges\_ are arranged when initialized using the functor order().
Now I want to arrange the data sweepEvents (which has the same type as myEdges\_ using the predefined data type from C++ vector) using a totally different criteria, that is I do not want to use the function getSlope(...) but the function computeDet(...) for sweepEvents.
So I was thinking I still need other functor for redefining the < of sort() for the vector data type right? So I would have to write a new functor order1() in which I use the data computed with computeDet(...) and then I call the sort on my sweepEvents data types:
```
sort(sweepEvents.begin(),sweepEvents.end(),order1());
```
I am not sure if this is the good solution? can I redefine in several ways < if I use different names for the functor?
Is someone has some suggestions I would be really grateful.
Thank you in advance,
madalina
No the two functors does not use any common code.
I have written the second functor insede the QSweep class as this:
```
class orderDet{
public:
bool operator() (const vector<int>& edgeSW1, const vector<int>& edgeSW2
,const vector<int>& edgeC){
return
(
computeDet(myPoints_[edgeSW1[0]],myPoints_[edgeSW1[1]],myPoints_[edgeC[0]])
<
computeDet(myPoints_[edgeSW2[0]],myPoints_[edgeSW2[1]],myPoints_[edgeC[0]])
);
}}
```
and I called it like:
```
sort(sweepEvents.begin(), sweepEvents.end(), orderDet());
```
But I got the following compilation error:
```
error: no match for call to '(QSweepComplete::orderDet) (std::vector<int,
std::allocator<int> >&, std::vector<int, std::allocator<int> >&)'
./QSweepComplete.h:68: note: candidates are: bool
QSweepComplete::orderDet::operator()(const std::vector<int, std::allocator<int>>&,
const std::vector<int, std::allocator<int> >&, const std::vector<int,
std::allocator<int> >&)
```
I am guessing the parameter do not match, as the third parameter of orderDet(...., edgeC) is not part of sweepEvents list as the others are but is part of the variable myEdges\_...
Maybe one can give me some suggestions on how to implement this functor?
thank you in advance.
best wishes,
madalina
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82475/"
] |
If you have 2 different criteria for sorting then you should have 2 different functors.
Give them meaningful names such as:
OrderBySlopes and OrderByXYZ
If the 2 functors use some common code, you can refactor this out. i.e. into a base class
|
What [Glen](https://stackoverflow.com/questions/878022/several-functors-for-redefining-order-for-sort-function-of-vector/878046#878046) said.
If you really really insist on having one function do double duty, you can rely on having different parameter types to overload two versions of operator().
|
878,022
|
I have the following data structure:
```
typedef vector< vector<int> > MxInt2d;
typedef vector< vector<double> > MxDouble2d;
class QSweep{
public:
....
static MxDouble2d myPoints_;
MxInt2d myEdges_;
MxInt2d sweepEvents;
class order{
public:
bool operator() (const vector<int>& edge1, const vector<int>& edge2){
return (myPoints_[edge1[0]][0]<myPoints_[edge2[0]][0])||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]<myPoints_[edge2[0]][1])
||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]==myPoints_[edge2[0]][1]&&
getSlope(myPoints_[edge1[0]][0],myPoints_[edge1[0][1],
myPoints_[edge1[1]][0],myPoints_[edge1[1]][1])
<
getSlope(myPoints_[edge2[0][0],myPoints_[edge2[0][1],
myPoints_[edge2[1]][0],myPoints_[edge2[1]][1]));
}
};
static double getSlope(double a, double b, double c, double d);
static double computeDet(double a, double b, double c, double d, double x, double y);
```
};
I use the functor for order() when defining the constructor in the following way:
```
QSweep::QSweep(const MxDouble2d& myPoints, const MxInt2d& myEdges){
....
//code here for initializing myPoints_, myEdges_
sort(myEdges_.begin(),myEdges_.end(),order());
}
```
In this way my data myEdges\_ are arranged when initialized using the functor order().
Now I want to arrange the data sweepEvents (which has the same type as myEdges\_ using the predefined data type from C++ vector) using a totally different criteria, that is I do not want to use the function getSlope(...) but the function computeDet(...) for sweepEvents.
So I was thinking I still need other functor for redefining the < of sort() for the vector data type right? So I would have to write a new functor order1() in which I use the data computed with computeDet(...) and then I call the sort on my sweepEvents data types:
```
sort(sweepEvents.begin(),sweepEvents.end(),order1());
```
I am not sure if this is the good solution? can I redefine in several ways < if I use different names for the functor?
Is someone has some suggestions I would be really grateful.
Thank you in advance,
madalina
No the two functors does not use any common code.
I have written the second functor insede the QSweep class as this:
```
class orderDet{
public:
bool operator() (const vector<int>& edgeSW1, const vector<int>& edgeSW2
,const vector<int>& edgeC){
return
(
computeDet(myPoints_[edgeSW1[0]],myPoints_[edgeSW1[1]],myPoints_[edgeC[0]])
<
computeDet(myPoints_[edgeSW2[0]],myPoints_[edgeSW2[1]],myPoints_[edgeC[0]])
);
}}
```
and I called it like:
```
sort(sweepEvents.begin(), sweepEvents.end(), orderDet());
```
But I got the following compilation error:
```
error: no match for call to '(QSweepComplete::orderDet) (std::vector<int,
std::allocator<int> >&, std::vector<int, std::allocator<int> >&)'
./QSweepComplete.h:68: note: candidates are: bool
QSweepComplete::orderDet::operator()(const std::vector<int, std::allocator<int>>&,
const std::vector<int, std::allocator<int> >&, const std::vector<int,
std::allocator<int> >&)
```
I am guessing the parameter do not match, as the third parameter of orderDet(...., edgeC) is not part of sweepEvents list as the others are but is part of the variable myEdges\_...
Maybe one can give me some suggestions on how to implement this functor?
thank you in advance.
best wishes,
madalina
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82475/"
] |
If you have 2 different criteria for sorting then you should have 2 different functors.
Give them meaningful names such as:
OrderBySlopes and OrderByXYZ
If the 2 functors use some common code, you can refactor this out. i.e. into a base class
|
Your `orderDet::operator()` takes three arguments. The `std::sort` wants only two to compare two values.
A solution may be to add the edges vector as a member of your functor:
```
struct orderDet {
const vector<int>& edges;
orderDet( const vector<int>& edges ):edges(edges){};
bool operator()( const vector<int>& v1, const vector<int>& v2 ) const {
....
}
};
```
By the way, if you want people to understand your code when they read it, I rather think you should use a typedef for your inner vector than for the outer one.
Next to that, it's better to define a struct containing a 'first' and 'second' point, than a very generic vector which you use only the first two points of. It will make your code more readable, too.
Regards.
|
49,020,629
|
I have:
```
a = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
b = [['-'] * 3] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
a == b #=> true
```
Seems correct.
```
a[0][0] = 'X'
a # => [["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
a == b # => false
```
What? Why does `b[0][0] = 'X'` change values in three places?
I also found it doesn't work this way:
```
b = [%w[- - -]] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
```
|
2018/02/28
|
[
"https://Stackoverflow.com/questions/49020629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236353/"
] |
This:
```
[object]*3
```
will create an array with 3 references to the same object so changing one of them changes all of them like this:
```
a = [[1]]*3 #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [2], [2]]
```
If you wish to create an array of length 3 with 3 different objects, do this:
```
a = 3.times.map {[1]} #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [1], [1]]
```
|
I found it has to be done this way:
```
irb(main):001:0> b = Array.new(3) { Array.new(3) { '-' } }
=> [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
irb(main):002:0> b[0][0] = 'X'
=> "X"
irb(main):003:0> b
=> [["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
```
|
49,020,629
|
I have:
```
a = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
b = [['-'] * 3] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
a == b #=> true
```
Seems correct.
```
a[0][0] = 'X'
a # => [["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
a == b # => false
```
What? Why does `b[0][0] = 'X'` change values in three places?
I also found it doesn't work this way:
```
b = [%w[- - -]] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
```
|
2018/02/28
|
[
"https://Stackoverflow.com/questions/49020629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236353/"
] |
This:
```
[object]*3
```
will create an array with 3 references to the same object so changing one of them changes all of them like this:
```
a = [[1]]*3 #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [2], [2]]
```
If you wish to create an array of length 3 with 3 different objects, do this:
```
a = 3.times.map {[1]} #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [1], [1]]
```
|
The first initialization you created 3 arrays nested in 1.
```
a = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
# [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
# ARRAY a ARRAY b ARRAY c
```
The second initialization you created 1 array, and then pointed the same array 3 times.
```
b = [['-'] * 3] * 3
# [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
# ARRAY x ARRAY x ARRAY x
```
Thinking in this way if you change b[0][0] is going to alter only one array, however you can have the impression that is changing more arrays because it's being referenced many times.
You can check it by yourself printing the addresses of them.
```
puts a[0].object_id # 47369457807480
puts a[1].object_id # 47369457807320
puts a[2].object_id # 47369457807200
puts b[0].object_id # 47369457807070
puts b[1].object_id # 47369457807070
puts b[2].object_id # 47369457807070
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
In addition to [@YuriiKyrylchuk](https://stackoverflow.com/users/2793494/yurii-kyrylchuk)'s answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to `MyClass.Companion` from Java. Example:
```
class MyClass {
companion object {
val x: Int = 0
}
}
```
And in Java:
```
MyClass.Companion.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
If your `SingleKotlin` object has a single private constructor without parameters, you can use `object` instead:
```
object SingleKotlin {
// some members of SingleKotlin
val x = 42
}
```
Then in Java you reference it through the `INSTANCE` static field:
```
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
You need to call the method from Java like this:
`AppUIUtils.Companion.yourMethod()`
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
In additional to Ilya answer you can use @JvmStatic annotation
```
object SingleKotlin {
// some members of SingleKotlin
@JvmStatic val x = 42
}
```
Then in Java
```
SingleKotlin.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
In addition to [@YuriiKyrylchuk](https://stackoverflow.com/users/2793494/yurii-kyrylchuk)'s answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to `MyClass.Companion` from Java. Example:
```
class MyClass {
companion object {
val x: Int = 0
}
}
```
And in Java:
```
MyClass.Companion.getX();
```
|
You need to call the method from Java like this:
`AppUIUtils.Companion.yourMethod()`
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
In addition to [@YuriiKyrylchuk](https://stackoverflow.com/users/2793494/yurii-kyrylchuk)'s answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to `MyClass.Companion` from Java. Example:
```
class MyClass {
companion object {
val x: Int = 0
}
}
```
And in Java:
```
MyClass.Companion.getX();
```
|
In additional to Ilya answer you can use @JvmStatic annotation
```
object SingleKotlin {
// some members of SingleKotlin
@JvmStatic val x = 42
}
```
Then in Java
```
SingleKotlin.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
If your `SingleKotlin` object has a single private constructor without parameters, you can use `object` instead:
```
object SingleKotlin {
// some members of SingleKotlin
val x = 42
}
```
Then in Java you reference it through the `INSTANCE` static field:
```
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
```
|
You need to call the method from Java like this:
`AppUIUtils.Companion.yourMethod()`
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
If your `SingleKotlin` object has a single private constructor without parameters, you can use `object` instead:
```
object SingleKotlin {
// some members of SingleKotlin
val x = 42
}
```
Then in Java you reference it through the `INSTANCE` static field:
```
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
```
|
In additional to Ilya answer you can use @JvmStatic annotation
```
object SingleKotlin {
// some members of SingleKotlin
@JvmStatic val x = 42
}
```
Then in Java
```
SingleKotlin.getX();
```
|
19,321,047
|
I am using this query:
```
SELECT ts as "TimeStamp",
stat as "Status"
FROM myTable
WHERE stat = 'O'
AND source = 'Source1'
AND ts BETWEEN TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND
TO_TIMESTAMP('2013-10-06','yyyy-mm-dd')
```
And also tried:
```
SELECT ts as "TimeStamp",
stat as "Status"
FROM myTable
WHERE stat = 'O'
AND source = 'Source1'
AND ts >= TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND ts <
TO_TIMESTAMP('2013-10-06','yyyy-mm-dd')
```
It returns 0 records, but if I do
```
SELECT ts as "TimeStamp",
stat as "Status"
FROM myTable
WHERE stat = 'O'
```
I can clearly identify 5 records. Apparently the `TO_TIMESTAMP` is not working properly I am hoping someone might be able to help identify the proper fix
**Edit: To clarify, I only want the timeframe for 10/5 not including 10/6**
Sorry pasted wrong results
Also the field is of type TIMESTAMP(6)
|
2013/10/11
|
[
"https://Stackoverflow.com/questions/19321047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342249/"
] |
Because the TO time stamp has time even though you're not specifying. So it is selecting only up to the very beginning of the lat day. Either specify time 23:59:59 and subseconds as required, or do less than the next day.
```
...
AND ts >= TO_TIMESTAMP('2013-10-05','yyyy-mm-dd')
AND ts < TO_TIMESTAMP('2013-10-07','yyyy-mm-dd')
```
|
Try:
AND ts BETWEEN TO\_DATE('2013-10-05','YYYY-MM-DD') AND
TO\_DATE('2013-10-06','YYYY-MM-DD')
And mind that it will get you results from the 10-05 at 00:00:00 to the 10-06 at 00:00:00 If you don't specify the HH MI SS mask.
Date masks are case sensitivve and TO\_DATE will work better.
|
55,785,574
|
I want to assign the total number of rows to a variable named **"@row\_count"**.
```
DECLARE @row_count int
SET @row_count = SELECT COUNT(*) FROM information
```
I know. I'm doing **wrong**. But I haven't found anything on how to do it.
---
I want to do something like that:
```
CREATE PROC add_person
(
@id tinyint,
@name nvarchar(max),
@surname nvarchar(max),
@salary int,
@job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(@id,@name,@surname,@salary,@job)
END
DECLARE @row_count nvarchar(max)
SET @row_count = SELECT COUNT(*) FROM information
BEGIN TRAN
add_person 34,'asdf','asdf',3000,'asdf'
IF @row_count > 33
ROLLBACK TRAN
ELSE
COMMIT TRAN
GO;
```
**My goal:** to prevent the addition of new people if the number of people exceeds thirty-four.
|
2019/04/21
|
[
"https://Stackoverflow.com/questions/55785574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
It's not possible to blur other apps in the background.
<https://www.electronjs.org/docs/api/frameless-window#limitations>
>
> The blur filter only applies to the web page, so there is no way to
> apply blur effect to the content below the window (i.e. other
> applications open on the user's system).
>
>
>
|
Electron does not allow you to blur on anything running behind it. It only allows you to blur the content on your webpage/app. Anything in your css styling will only be applied to the foreground contents. I know because I too have tried and failed.
|
55,785,574
|
I want to assign the total number of rows to a variable named **"@row\_count"**.
```
DECLARE @row_count int
SET @row_count = SELECT COUNT(*) FROM information
```
I know. I'm doing **wrong**. But I haven't found anything on how to do it.
---
I want to do something like that:
```
CREATE PROC add_person
(
@id tinyint,
@name nvarchar(max),
@surname nvarchar(max),
@salary int,
@job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(@id,@name,@surname,@salary,@job)
END
DECLARE @row_count nvarchar(max)
SET @row_count = SELECT COUNT(*) FROM information
BEGIN TRAN
add_person 34,'asdf','asdf',3000,'asdf'
IF @row_count > 33
ROLLBACK TRAN
ELSE
COMMIT TRAN
GO;
```
**My goal:** to prevent the addition of new people if the number of people exceeds thirty-four.
|
2019/04/21
|
[
"https://Stackoverflow.com/questions/55785574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
electron-acrylic-window
=======================
Actually, it is possible, with a little bit of magic. I have no idea why nobody pointed that out, but there exists a small utility called [electron-acrylic-window](https://github.com/Seo-Rii/electron-acrylic-window), which allows you to do exactly that. You can choose between the acrylic ("frosted") and blur effects, as well as change the color of the window and the opacity.
Under the hood, it uses [node-gyp](https://github.com/nodejs/node-gyp) and low-level C++ code to render the page however you like. It's pretty easy to implement in Javascript.
The major drawback is that anything that is remotely transparent (and not above anything with a solid color) will be rendered as totally transparent.
Sample usage
------------
`index.js`
```js
const { BrowserWindow } = require('electron-acrylic-window');
// import { BrowserWindow } from 'electron-acrylic-window';
win = new BrowserWindow({
...,
frame: false,
vibrancy: {
theme: 'light', // (default) or 'dark' or '#rrggbbaa'
effect: 'acrylic', // (default) or 'blur'
disableOnBlur: true, // (default)
}
});
// alternatively use these to
// dynamically change vibrancy
win.setVibrancy([options])
// or
setVibrancy(win, [options])
```
`style.css`
```css
body {
background-color: transparent;
}
.watev {
background-color: black;
}
```
|
It's not possible to blur other apps in the background.
<https://www.electronjs.org/docs/api/frameless-window#limitations>
>
> The blur filter only applies to the web page, so there is no way to
> apply blur effect to the content below the window (i.e. other
> applications open on the user's system).
>
>
>
|
55,785,574
|
I want to assign the total number of rows to a variable named **"@row\_count"**.
```
DECLARE @row_count int
SET @row_count = SELECT COUNT(*) FROM information
```
I know. I'm doing **wrong**. But I haven't found anything on how to do it.
---
I want to do something like that:
```
CREATE PROC add_person
(
@id tinyint,
@name nvarchar(max),
@surname nvarchar(max),
@salary int,
@job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(@id,@name,@surname,@salary,@job)
END
DECLARE @row_count nvarchar(max)
SET @row_count = SELECT COUNT(*) FROM information
BEGIN TRAN
add_person 34,'asdf','asdf',3000,'asdf'
IF @row_count > 33
ROLLBACK TRAN
ELSE
COMMIT TRAN
GO;
```
**My goal:** to prevent the addition of new people if the number of people exceeds thirty-four.
|
2019/04/21
|
[
"https://Stackoverflow.com/questions/55785574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
electron-acrylic-window
=======================
Actually, it is possible, with a little bit of magic. I have no idea why nobody pointed that out, but there exists a small utility called [electron-acrylic-window](https://github.com/Seo-Rii/electron-acrylic-window), which allows you to do exactly that. You can choose between the acrylic ("frosted") and blur effects, as well as change the color of the window and the opacity.
Under the hood, it uses [node-gyp](https://github.com/nodejs/node-gyp) and low-level C++ code to render the page however you like. It's pretty easy to implement in Javascript.
The major drawback is that anything that is remotely transparent (and not above anything with a solid color) will be rendered as totally transparent.
Sample usage
------------
`index.js`
```js
const { BrowserWindow } = require('electron-acrylic-window');
// import { BrowserWindow } from 'electron-acrylic-window';
win = new BrowserWindow({
...,
frame: false,
vibrancy: {
theme: 'light', // (default) or 'dark' or '#rrggbbaa'
effect: 'acrylic', // (default) or 'blur'
disableOnBlur: true, // (default)
}
});
// alternatively use these to
// dynamically change vibrancy
win.setVibrancy([options])
// or
setVibrancy(win, [options])
```
`style.css`
```css
body {
background-color: transparent;
}
.watev {
background-color: black;
}
```
|
Electron does not allow you to blur on anything running behind it. It only allows you to blur the content on your webpage/app. Anything in your css styling will only be applied to the foreground contents. I know because I too have tried and failed.
|
11,826,556
|
I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:
```
$('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";}
);
```
I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: [http://jsfiddle.net](http://jsfiddle.net/2VBSX/1/)
|
2012/08/06
|
[
"https://Stackoverflow.com/questions/11826556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647909/"
] |
This one took me a very long time to figure out, but I think the best you can do is give the elements a second to load into the DOM, and then run your function: <http://jsfiddle.net/2VBSX/5/>
```
$('div.newscontainer').embedly({
key:':e0a98aba95ef11e09dcd4040d3dc5c07'
}).hide();
setTimeout(function() {
$('div.newscontainer').show().find('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
);
}, 1000);
```
|
Jquery's HTML doesn't accept a function as argument, but only plain HTML (a string).
To do what you wanto to do, use `.each()` :)
**Correction:** as pointed out by the commenter below, my code is correct but .html() **does** indeed accept a function as argument, in the form `$(...).html(function(index, oldhtml));`, making possible to access directly the html part. (Thanks to @Raminson for pointing it out)
Prior to @Raminson's observation my code was:
```
$('.description').each(
function(i,e){
$(e).html(reduce($(e).html()));}
);
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
With the correction, the first part becomes (still using the `reduce()` function):
```
$(".description").html(function(i,s) { return reduce(s); });
```
|
11,826,556
|
I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:
```
$('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";}
);
```
I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: [http://jsfiddle.net](http://jsfiddle.net/2VBSX/1/)
|
2012/08/06
|
[
"https://Stackoverflow.com/questions/11826556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647909/"
] |
Jquery's HTML doesn't accept a function as argument, but only plain HTML (a string).
To do what you wanto to do, use `.each()` :)
**Correction:** as pointed out by the commenter below, my code is correct but .html() **does** indeed accept a function as argument, in the form `$(...).html(function(index, oldhtml));`, making possible to access directly the html part. (Thanks to @Raminson for pointing it out)
Prior to @Raminson's observation my code was:
```
$('.description').each(
function(i,e){
$(e).html(reduce($(e).html()));}
);
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
With the correction, the first part becomes (still using the `reduce()` function):
```
$(".description").html(function(i,s) { return reduce(s); });
```
|
So, my other answer is not valid because the OP didn't mention that all the elements were created on the fly, so they cannot be matched in the classical way.
If the modifications are attached to a suitable event (click, for example), then it would be easy to use delegates with `.on()`, as they are valid also for new elements inserted in the DOM.
But alas this is not the case, we must operate on the element's creation.
One solution would be @ChrisClower's one (a timer polling the page regularly for new elements).
Another solution would be to use the LiveQuery plugin: <http://docs.jquery.com/Plugins/livequery>
Then all would be simple:
```
$(".description").livequery(function() { $(e).html(reduce($(e).html())); });
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
|
11,826,556
|
I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:
```
$('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";}
);
```
I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: [http://jsfiddle.net](http://jsfiddle.net/2VBSX/1/)
|
2012/08/06
|
[
"https://Stackoverflow.com/questions/11826556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647909/"
] |
This one took me a very long time to figure out, but I think the best you can do is give the elements a second to load into the DOM, and then run your function: <http://jsfiddle.net/2VBSX/5/>
```
$('div.newscontainer').embedly({
key:':e0a98aba95ef11e09dcd4040d3dc5c07'
}).hide();
setTimeout(function() {
$('div.newscontainer').show().find('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
);
}, 1000);
```
|
So, my other answer is not valid because the OP didn't mention that all the elements were created on the fly, so they cannot be matched in the classical way.
If the modifications are attached to a suitable event (click, for example), then it would be easy to use delegates with `.on()`, as they are valid also for new elements inserted in the DOM.
But alas this is not the case, we must operate on the element's creation.
One solution would be @ChrisClower's one (a timer polling the page regularly for new elements).
Another solution would be to use the LiveQuery plugin: <http://docs.jquery.com/Plugins/livequery>
Then all would be simple:
```
$(".description").livequery(function() { $(e).html(reduce($(e).html())); });
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
Use this code:
```
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");
```
And the result would be:
```
ArslanFolder 20_01_2013 _ _ _
```
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
|
Try this :
```
replaceAll("[\\W]", "_");
```
It will replace all non alphanumeric characters with underscore
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
I used one of this:
```
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
```
See this link:
[Replace special characters](https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string)
|
Try this :
```
replaceAll("[\\W]", "_");
```
It will replace all non alphanumeric characters with underscore
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
Use this code:
```
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");
```
And the result would be:
```
ArslanFolder 20_01_2013 _ _ _
```
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
|
I used one of this:
```
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
```
See this link:
[Replace special characters](https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string)
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
Use this code:
```
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");
```
And the result would be:
```
ArslanFolder 20_01_2013 _ _ _
```
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
|
**This is correct solution:**
```
String result = inputString.replaceAll("[\\\\|?\u0000*<\":>+\\[\\]/']", "_");
```
Kent answer is good, but he isnt include characters `NUL` and `\`.
Also, this is a secure solution for replacing/renaming text of user-input file names, for example.
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
I used one of this:
```
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
```
See this link:
[Replace special characters](https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string)
|
**This is correct solution:**
```
String result = inputString.replaceAll("[\\\\|?\u0000*<\":>+\\[\\]/']", "_");
```
Kent answer is good, but he isnt include characters `NUL` and `\`.
Also, this is a secure solution for replacing/renaming text of user-input file names, for example.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
Dynamically allocated:
```
int * pointerArray = new int[10];
```
[BTW, this is a pointer to an array of 10 ints, NOT a pointer array]
Statically allocated (possibly on the stack):
```
int array[10];
```
Otherwise they are the same.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
On the one hand:
```
int ar[10];
```
is using memory allocated on the stack. You can think of it also locally available and while it is possible to pass a pointer / reference to otehr functions, the memory will be freed as soon as it goes out of scope (in your example at the end of the main method but that's usually not the case).
On the other hand:
```
int ar* = new int[10];
```
allocates the memory for the array on the heap. It is available until your whole program exits or it is deleted using
```
delete[] ar;
```
note, that for delete you need the "[]" if and only if the corresponding new has had them, too.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
There is a difference but not in the area that you point to. `*pointerArray` will point to the beginning of a block of memory of size 10 bytes. So will `array`. The only difference will be where it is stored in memory. `pointerArray` is dynamically assigned memory (at `run-time`) and hence will go on the heap, while `array[10]` will be allocated at `compile-time` and will go to the stack.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
Dynamically allocated:
```
int * pointerArray = new int[10];
```
[BTW, this is a pointer to an array of 10 ints, NOT a pointer array]
Statically allocated (possibly on the stack):
```
int array[10];
```
Otherwise they are the same.
|
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
First, I'd look for some other place to learn C++. The page you cite is
very confusing, and has little to do with the way one actually programs
in C++. In C++, most of the time, you'd use `std::vector` for an array,
not the complex solutions proposed on the page you cite. In practice,
you never use `operator new[]` (an array `new`).
In fact, `std::vector` is in some ways more like `ArrayList` than simple
arrays in Java; unlike an array in Java, you can simply grow the vector
by inserting elements into it, preferrably at the end. And it supports
iterators, although C++ iterators are considerably different than Java
iterators. On the other hand, you can access it using the `[]`
operator, like a normal array.
The arrays described on the page you cite are usually called C style
arrays. In C++, their use is mostly limited to objects with static
lifetime, although they do occasionally appear in classes. In any case, they are never allocated dynamically.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
First, I'd look for some other place to learn C++. The page you cite is
very confusing, and has little to do with the way one actually programs
in C++. In C++, most of the time, you'd use `std::vector` for an array,
not the complex solutions proposed on the page you cite. In practice,
you never use `operator new[]` (an array `new`).
In fact, `std::vector` is in some ways more like `ArrayList` than simple
arrays in Java; unlike an array in Java, you can simply grow the vector
by inserting elements into it, preferrably at the end. And it supports
iterators, although C++ iterators are considerably different than Java
iterators. On the other hand, you can access it using the `[]`
operator, like a normal array.
The arrays described on the page you cite are usually called C style
arrays. In C++, their use is mostly limited to objects with static
lifetime, although they do occasionally appear in classes. In any case, they are never allocated dynamically.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
It is true that you can get most of array functionality by using a pointer to its first element. But compiler knows that a static array is composed of several elements and the most notable difference is the result of the `sizeof` operator.
`sizeof(pointerArray) = sizeof int*`
`sizeof(array) = 10 * sizeof int`
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
The problem with understanding C/C++ arrays when coming from Java is that C/C++ distinguishes between the array variable and the memory used to store the array contents. Both concepts are important and distinct. In Java, you really just have a reference to an object that is an array.
You also need to understand that C/C++ has two ways of allocating memory. Memory can be allocated on the help or the stack. Java doesn't have this distinction.
In C and C++, an array variable is a pointer to the first element of the array. An array variable can exist on the heap or the stack, and so can the memory that contains its contents. And they can be difference. Your examples are `int` arrays, so you can consider the array variable to be an `int*`.
There are two differences between `int *pointerArray = new int[10];` and `int array[10];`:
The first difference is that the memory that contains the contents of the first array is allocated on the *heap*. The second array is more tricky. If `array` is a local variable in a function then its contents are allocated on the stack, but if it is a member variable of a class then its contents are allocated wherever the containing object is allocated (heap or stack).
The second difference is that, as you've realised, the first array is dynamic: its size can be determined at run-time. The second array is fixed: the compiler must be able to determine its size at compile time.
|
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
|
10,710,566
|
How to match different instances of the same word.
Eg: if the string is synergy. How to match it with synergizes, synergism, synergically, synergistic.
I could write the following:
```
while(<IN>)
{
chomp $_;
my $line= $_;
$word="Synergy";
if($line=~m/$word(\w+)/i)
{
$line=~s/$word/<Effect>$word<\/Effect>/ig;
}
}
```
|
2012/05/22
|
[
"https://Stackoverflow.com/questions/10710566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226696/"
] |
What you probably want to do is called stemming.
However, for this to work, you have to stem all the words in the text plus the one you search for. Hopefully all of your listed words result in the same stem. I haven't tested it yet.
```
use Lingua::Stem;
my $stemmer = Lingua::Stem->new( -locale => 'EN-UK' );
# first convert text to list of words
my @words;
while(<IN>) {
push @words, split(/\b/, $_); # you can do better here
}
# now stem all words.
my $stemmed_words = $stemmer->stem(@words);
# results in an array ref of stems in the same order as the words have been.
# now stem your search
my $stemmed_search = $stemmer->stem($word);
# and do the search from above inside stemmed array.
```
Now it depends on what you want. If you want to exchange all those words with something, you have to get the indexes of the matched (stemmed) words and do the replacement at the same positions inside your text.
|
You're going to want to use regular expressions. It is unclear what exactly the criteria you want to match, but in your example all the words start with "synergi" so `if($string =~ \bsynergi\w*\b)` would find all lines containing "synergi" anywhere in them.
|
10,710,566
|
How to match different instances of the same word.
Eg: if the string is synergy. How to match it with synergizes, synergism, synergically, synergistic.
I could write the following:
```
while(<IN>)
{
chomp $_;
my $line= $_;
$word="Synergy";
if($line=~m/$word(\w+)/i)
{
$line=~s/$word/<Effect>$word<\/Effect>/ig;
}
}
```
|
2012/05/22
|
[
"https://Stackoverflow.com/questions/10710566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226696/"
] |
What you probably want to do is called stemming.
However, for this to work, you have to stem all the words in the text plus the one you search for. Hopefully all of your listed words result in the same stem. I haven't tested it yet.
```
use Lingua::Stem;
my $stemmer = Lingua::Stem->new( -locale => 'EN-UK' );
# first convert text to list of words
my @words;
while(<IN>) {
push @words, split(/\b/, $_); # you can do better here
}
# now stem all words.
my $stemmed_words = $stemmer->stem(@words);
# results in an array ref of stems in the same order as the words have been.
# now stem your search
my $stemmed_search = $stemmer->stem($word);
# and do the search from above inside stemmed array.
```
Now it depends on what you want. If you want to exchange all those words with something, you have to get the indexes of the matched (stemmed) words and do the replacement at the same positions inside your text.
|
You might want to check out Text::Soundex. For example,
```
use Text::Soundex;
# The following all return S562
print soundex("synergizes"), "\n";
print soundex("synergism"), "\n";
print soundex("synergically"), "\n";
print soundex("synergistic"), "\n";
```
Further reading: [Perldoc Text::Soundex](http://perldoc.perl.org/Text/Soundex.html)
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Others have mentioned File::Find, which is the way I'd go, but you asked for an iterator, which File::Find isn't (nor is File::Find::Rule). You might want to look at [File::Next](http://search.cpan.org/dist/File-Next/) or [File::Find::Object](http://search.cpan.org/dist/File-Find-Object/), which do have an iterative interfaces. Mark Jason Dominus goes over building your own in chapter 4.2.2 of [Higher Order Perl](http://hop.perl.plover.com/book/).
|
My preferred method is to use the File::Find module as so:
```
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
```
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
This sounds like a job for [File::Find::Rule](http://search.cpan.org/perldoc?File::Find::Rule):
```
#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Causes built-ins like open to succeed or die.
# You can 'use Fatal qw(open)' if autodie is not installed.
use File::Find::Rule;
use Getopt::Std;
use constant SECONDS_IN_DAY => 24 * 60 * 60;
our %option = (
m => 1, # -m switch: days ago modified, defaults to 1
o => undef, # -o switch: output file, defaults to STDOUT
);
getopts('m:o:', \%option);
# If we haven't been given directories to search, default to the
# current working directory.
if (not @ARGV) {
@ARGV = ( '.' );
}
print STDERR "Finding files changed in the last $option{m} day(s)\n";
# Convert our time in days into a timestamp in seconds from the epoch.
my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};
# Now find all the regular files, which have been modified in the last
# $option{m} days, looking in all the locations specified in
# @ARGV (our remaining command line arguments).
my @files = File::Find::Rule->file()
->mtime(">= $last_modified_timestamp")
->in(@ARGV);
# $out_fh will store the filehandle where we send the file list.
# It defaults to STDOUT.
my $out_fh = \*STDOUT;
if ($option{o}) {
open($out_fh, '>', $option{o});
}
# Print our results.
print {$out_fh} join("\n", @files), "\n";
```
|
[File::Find](http://search.cpan.org/~rgarcia/perl-5.10.0/lib/File/Find.pm) is the right way to solve this problem. There is no use in reimplementing stuff that already exists in other modules, but reimplementing something that is in a standard module should really be discouraged.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
I write a subroutine that reads a directory with `readdir`, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use `utime` or `stat`). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
<http://www.cs.cf.ac.uk/Dave/PERL/node70.html>
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Others have mentioned File::Find, which is the way I'd go, but you asked for an iterator, which File::Find isn't (nor is File::Find::Rule). You might want to look at [File::Next](http://search.cpan.org/dist/File-Next/) or [File::Find::Object](http://search.cpan.org/dist/File-Find-Object/), which do have an iterative interfaces. Mark Jason Dominus goes over building your own in chapter 4.2.2 of [Higher Order Perl](http://hop.perl.plover.com/book/).
|
I write a subroutine that reads a directory with `readdir`, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use `utime` or `stat`). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
<http://www.cs.cf.ac.uk/Dave/PERL/node70.html>
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
My preferred method is to use the File::Find module as so:
```
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
```
|
I write a subroutine that reads a directory with `readdir`, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use `utime` or `stat`). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
<http://www.cs.cf.ac.uk/Dave/PERL/node70.html>
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
I wrote [File::Find::Closures](http://search.cpan.org/dist/File-Find-Closures) as a set of closures that you can use with File::Find so you don't have to write your own. There's a couple of mtime functions that should handle
```
use File::Find;
use File::Find::Closures qw(:all);
my( $wanted, $list_reporter ) = find_by_modified_after( time - 86400 );
#my( $wanted, $list_reporter ) = find_by_modified_before( time - 86400 );
File::Find::find( $wanted, @directories );
my @modified = $list_reporter->();
```
You don't really need to use the module because I mostly designed it as a way that you could look at the code and steal the parts that you wanted. In this case it's a little trickier because all the subroutines that deal with stat depend on a second subroutine. You'll quickly get the idea from the code though.
Good luck,
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
This sounds like a job for [File::Find::Rule](http://search.cpan.org/perldoc?File::Find::Rule):
```
#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Causes built-ins like open to succeed or die.
# You can 'use Fatal qw(open)' if autodie is not installed.
use File::Find::Rule;
use Getopt::Std;
use constant SECONDS_IN_DAY => 24 * 60 * 60;
our %option = (
m => 1, # -m switch: days ago modified, defaults to 1
o => undef, # -o switch: output file, defaults to STDOUT
);
getopts('m:o:', \%option);
# If we haven't been given directories to search, default to the
# current working directory.
if (not @ARGV) {
@ARGV = ( '.' );
}
print STDERR "Finding files changed in the last $option{m} day(s)\n";
# Convert our time in days into a timestamp in seconds from the epoch.
my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};
# Now find all the regular files, which have been modified in the last
# $option{m} days, looking in all the locations specified in
# @ARGV (our remaining command line arguments).
my @files = File::Find::Rule->file()
->mtime(">= $last_modified_timestamp")
->in(@ARGV);
# $out_fh will store the filehandle where we send the file list.
# It defaults to STDOUT.
my $out_fh = \*STDOUT;
if ($option{o}) {
open($out_fh, '>', $option{o});
}
# Print our results.
print {$out_fh} join("\n", @files), "\n";
```
|
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
My preferred method is to use the File::Find module as so:
```
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
```
|
Using standard modules is indeed a good idea but out of interest here is my back to basic approach using no external modules. I know code syntax here might not be everyone's cup of tea.
It could be improved to use less memory via providing an iterator access (input list could temporarily be on hold once it reaches a certain size) and conditional check can be expanded via callback ref.
```
sub mfind {
my %done;
sub find {
my $last_mod = shift;
my $path = shift;
#determine physical link if symlink
$path = readlink($path) || $path;
#return if already processed
return if $done{$path} > 1;
#mark path as processed
$done{$path}++;
#DFS recursion
return grep{$_} @_
? ( find($last_mod, $path), find($last_mod, @_) )
: -d $path
? find($last_mod, glob("$path/*") )
: -f $path && (stat($path))[9] >= $last_mod
? $path : undef;
}
return find(@_);
}
print join "\n", mfind(time - 1 * 86400, "some path");
```
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
There's my [File::Finder](http://search.cpan.org/perldoc/File::Finder), as already mentioned, but there's also my iterator-as-a-tied-hash solution from [Finding Files Incrementally (Linux Magazine)](http://www.stonehenge.com/merlyn/LinuxMag/col30.html).
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
There's my [File::Finder](http://search.cpan.org/perldoc/File::Finder), as already mentioned, but there's also my iterator-as-a-tied-hash solution from [Finding Files Incrementally (Linux Magazine)](http://www.stonehenge.com/merlyn/LinuxMag/col30.html).
|
I'm riskying to get downvoted, but IMHO 'ls' (with appropriate params) command does it in a best known performant way. In this case it might be quite good solution to pipe 'ls' from perl code through shell, returning results to an array or hash.
Edit: It could also be 'find' used, as proposed in comments.
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 657