qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
6,907,423 | I have a module called 'admin' in my application, which is accessible at /mysite/admin. To improve the site security I want to change this URL to something more difficult to guess to the normal users and only the site admin will know.
I tried urlManager rules but couldn't get the desired result, for example:
```
'admin-panel'=>'admin/default/index',
'admin-panel/login'=>'admin/default/login'
```
But this will only work for those two URLs.
So the only thing I can think of now is to rename the actual module. The module name is referenced a lot throughout the app so that it is too difficult to do. anyone have any other suggestions? | 2011/08/02 | [
"https://Stackoverflow.com/questions/6907423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238784/"
] | ```
rules=>array(
'admin-panel' =>'admin',
'admin-panel/<_c:\w+>/<_a:\w+>/<id:\d+>' =>'admin/<_c>/<_a>/<id>',
'admin-panel/<_c:\w+>/<_a:\w+>' =>'admin/<_c>/<_a>',
'admin-panel/<_c:\w+>' =>'admin/<_c>',
)
```
But it's just alias - your admin module still will be available by /admin/ URL. Actually you must check access for users, don't try to hide your admin panel. | try adding:
```
'admin-panel'=>'admin',
'admin-panel/<controller:\w+>'=>'admin/<controller>',
'admin-panel/<controller:\w+>/<action:\w+>'=>'admin/<controller>/<action>',
``` |
6,907,423 | I have a module called 'admin' in my application, which is accessible at /mysite/admin. To improve the site security I want to change this URL to something more difficult to guess to the normal users and only the site admin will know.
I tried urlManager rules but couldn't get the desired result, for example:
```
'admin-panel'=>'admin/default/index',
'admin-panel/login'=>'admin/default/login'
```
But this will only work for those two URLs.
So the only thing I can think of now is to rename the actual module. The module name is referenced a lot throughout the app so that it is too difficult to do. anyone have any other suggestions? | 2011/08/02 | [
"https://Stackoverflow.com/questions/6907423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238784/"
] | ```
rules=>array(
'admin-panel' =>'admin',
'admin-panel/<_c:\w+>/<_a:\w+>/<id:\d+>' =>'admin/<_c>/<_a>/<id>',
'admin-panel/<_c:\w+>/<_a:\w+>' =>'admin/<_c>/<_a>',
'admin-panel/<_c:\w+>' =>'admin/<_c>',
)
```
But it's just alias - your admin module still will be available by /admin/ URL. Actually you must check access for users, don't try to hide your admin panel. | ```
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'module/<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',
'module/<m:\w+>/<c:\w+>/<a:\w+>'=>'<m>/<c>/<a>',
)
),
``` |
3,011,125 | As the title says, is it valid to insert the power of the cosine to its angle?
Edit : Is it valid when x is very small ? | 2018/11/24 | [
"https://math.stackexchange.com/questions/3011125",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/612589/"
] | For $x = \pi^{3/4}$, $\cos^{3}(x^{4/3}) = \cos^{3}(\pi) = -1$. However, $\cos(\pi^{4})\neq -1$, since $\pi^{4}$ can't be a rational multiple of $\pi$ (since $\pi$ is a transcendental number!). | Although
$$
(x^{4/3})^3 = x^4,
$$
one does not have
$$
[f(x^{4/3})]^3=f(x^4)
$$
in general.
[](https://i.stack.imgur.com/dbq4L.png)
>
> For your added question "Is it valid when $x$ is very small?":
>
>
>
I assume that you mean when $|x|$ is very small.
No. If these two functions are identical near $x=0$, then they must have the same Taylor expansion. But it is not difficult to see by comparing a few terms that they don't have the same Taylor expansion near $x=0$. |
710,157 | I'm making a hardware project that will run a GNU/Linux OS, and I have a question.(edit: it's ARM based)
How EXACTLY does the Linux kernel know what type of hardware is connected to the CPU, I mean how hoes it know that yeah this a a RAM and that is a drive ...etc.
ESPECIALLY for network interfaces, if the system has multiple Ethernet NICs and multiple WiFi transceivers how does it know which is which and how does it know how they are connected hardware-wise (maybe they are connected with multiplexer, maybe with I2C , SPI ...etc). | 2022/07/17 | [
"https://unix.stackexchange.com/questions/710157",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/243639/"
] | All this very low level work will of course depend on… the [architecture](https://en.wikipedia.org/wiki/List_of_Linux-supported_computer_architectures).
For the most common (x86/IBM PC) the BIOS will help a lot for a good start. If you get one, look at your bootlog, it will start querying the BIOS :
>
> BIOS-provided physical RAM map:
>
>
>
further down, you might notice something like :
>
> BIOS-e820: [mem 0x00000000cff80000-0x00000000cff8dfff] ACPI data
>
>
>
which are tables provided by the BIOS on which the OS can rely in order to obtain additional infos about peripherals… (BIOSes are often known to be more or less broken on this)
On the other end you get ARM SoCs with each vendor supporting peripherals its own way (and most often as closed-source) and who, of course, never agreed on whatever BIOS equivalent. This situation led to some famous quotes from Linus Torvald :
>
> I hope the SoC ARM designers die in an incredibly painful accident.
> […] Gaah, Guys this whole ARM thing is a fucking pain in the ass.
>
>
>
If your project is based on that sort of hardware… well… Good luck! You might well have to bruteforce on memory ranges. (Write and consider what happens)
---
Then come less architecture dependent information data. Those about devices standing on standard buses :
For **ISA** devices (nowadays mostly serial / parallel ports) you'll need to rely on some trial and error method reading a very limited number of *usual* port addresses to consider what it looks like.
For devices plugged into **PCI** buses, the [PCI configuration space](https://en.wikipedia.org/wiki/PCI_configuration_space) is a standard which enables the implementation of standard (arch independent) methods for enumerating and initializing.
---
In any case, if your hardware cannot rely on standardized methods for probing you will be on your own to answer your question as @[telcoM](https://unix.stackexchange.com/users/258991/telcom) suggests it :
>
> On ARM, the standard seems to be that the designers (or
> reverse-engineers, as the case may be) of the hardware must describe
> it in the form of [device tree data](https://www.kernel.org/doc/html/latest/devicetree/usage-model.html), which is then loaded by the
> hardware-specific bootloader along with the kernel file and possibly
> initramfs file. So if your hardware project uses an architecture that
> does not include a standardized, autoprobeable main bus like PCI or
> PCIe, then yes, you, the hardware designer will have to provide that
> information for the Linux kernel.
>
>
> | The x86 architecture describes standard PC components (interfaces including PCI, PCI-E, RAM, etc.) which the Linux kernel enumerates part of the boot process. Some buses allow to attach/detach devices on the fly, e.g. USB or SATA. Your question is not Linux/Unix specific.
* [https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/13\_IOSystems.html](https://www.cs.uic.edu/%7Ejbell/CourseNotes/OperatingSystems/13_IOSystems.html)
* <https://stackoverflow.com/questions/32634196/at-boot-time-how-os-determines-all-the-hardware> |
1,191,372 | I am currently using the formula below to have a cell say 0 if the numeric value is less than 8. If the numeric value in that cell is greater than 8, i would like the value to show in the cell and subtract it by 8.
=SUMIF(B3,">8")-8
It works if the value is greater than 8 perfectly, but when it is less than 8 it gives me a negative value, which is what I do not want. I only want it to subtract 8 if B3 is greater than 8, or show zero if it is not greater than 8. | 2017/03/22 | [
"https://superuser.com/questions/1191372",
"https://superuser.com",
"https://superuser.com/users/710089/"
] | Use if to set whether you return 0 or the value less 8:
```
=IF(B3<8,0,B3-8)
```
[](https://i.stack.imgur.com/mBQV9.png)
Or you can use MAX:
```
=MAX(B3-8,0)
```
[](https://i.stack.imgur.com/dbnmD.png) | I would keep it simple: `=MAX(0, A1-8)`
When `a1-8` is less than 0, it returns 0 (by definition.) Otherwise it returns `a1-8`.
For example
```
In Output
-1 0
8 0
9 1
10 2
11 3
12 4
13 5
``` |
3,905,749 | 1.Let f ∈ S3 be a permutation which is not the identity. Prove that there exists g ∈ S3
such that fg ≠ gf.
2.Let n ≥ 3, and let f ∈ Sn be a permutation which is not the identity. Prove that
there exists g ∈ Sn such that fg ≠ gf.
Hey guys I am completely stuck in these two questions I'm really not sure where to start with solving it, can anyone please give me a hint? Any helps would be appreciated!
Update: Thanks everyone for giving me hint and helping me with that question. I have attempted to work on the first question and here is what I've got:
Since f ∈ S3 and it is not identity. This can conclude that there would be 5 permutations in f and 6 permutations for g as g ∈ S3.
We then test the permutations by multiple one f permutation to all g permutations. For example we take f = (321) and we multiple it with all g permutations available.
We would then be able to prove fg ≠ gf in most sets except the one where g is identity and the one that g has the same permutation as f.
Then, we can take this set to conclude that fg ≠ gf in f ∈ S3 and f is not identity and g ∈ S3 except when g is identity and the one that g has the same permutation as f.
Would this be correct at all? | 2020/11/13 | [
"https://math.stackexchange.com/questions/3905749",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/835595/"
] | I'll try to formally trace your solution. First you apply the trick $y'(x)=p(y(x))$ with the dot indicating the $y$ derivative. This gives correctly equation (II). Next you set $\dot p(y)=u$ and compute $y$ as a function of $u$, $y=v(u)$, giving the combined equation $y(x)=v(\dot p(y(x)))$, that is, $v$ is the inverse function to $u$. This transforms (II) into
$$
p(v(u))=2v(u)u+\frac12\ln(u)
$$
and taking the $u$ derivative
\begin{align}
\dot p(v(u))v'(u)=2v'(u)u+2v(u)+\frac1{2u}
&\implies 0=v'(u)+\frac{2v(u)}{u}+\frac1{2u^2}\tag{IIIa}
\\
&\implies 0=[u^2v'(u)+2uv(u)]+\frac12
\\
&\implies C=u^2v(u)+\frac{u}2\tag{IIIb}
\end{align}
and thus
$$
p(v(u))=2\left(\frac{C}u-\frac12\right)+\frac12\ln(u)
$$
At this point you may note that there is a different power in the denominator as $uv(u)=\frac Cu-\frac12$.
Though the connection may be weak, there is still dependence between $x$ and $u$. You can not set $u$ constant in the $x$-integration of $y'(x)=p(y(x))$. Rather you would attempt to get $x$ also as a function $x=w(u)$, so that from $y(w(u))=v(u)$ one gets the equation
$y'(w)w'(u)=p(v(u))w'(u)=v'(u)$ where $v'(u)$ is known from (III), giving
$$
x=\int w'(u)du=\int\frac{v'(u)}{p(v(u))}du=\int\frac{-\frac{2C}{u^3}+\frac1{2u^2}}{2\frac{C}u-1+\frac12\ln(u)}du
$$
which does not give the impression of an easy solution. | Differentiating $p=2y\dot p+\log\sqrt{\dot p}$ gives $\dot p=2\dot p+2y\ddot p+\ddot p/(2\dot p)$ so $(1+4yq)\dot q=-2q^2$ where $q=\dot p$. As this is exact, the general solution is $c=f(y)$ where $f\_q=1+4yq$ and $f\_y=2q^2$. Thus $f(y)=d+q+2yq^2$ so $q=(-1\pm\sqrt{1+Cy})/4y$ and substituting back into $p=y'$ yields $x=\int\frac{dy}{\int q(y)\,dy}$. |
280,351 | Some animals have different words for the animal and for the meat - *cow/beef*, *pig/pork*. Some animals just use the same word without any compound - *fish*, *quail*.
But some animals use compounds of the form [animal] *meat*, while others use [animal] *flesh*. I looked at the Wiktionary entry on *[flesh](https://en.wiktionary.org/wiki/flesh)*, and it didn't really explain when to use *flesh* rather than *meat*, and why it is the case.
We talk about "human flesh" not "human meat", and can use either "horse flesh" or "horse meat", and we use *meat* not *flesh* for kangaroos, dogs, whales or dolphins, all of whom tend to be "friends not food" to most English-speakers.
Is the difference that *flesh* used to be more common than it is nowadays, and *human flesh* and *horse flesh* entered English earlier than the other phrases? Wiktionary mentioned some uses of *flesh* as archaic.
(I'm aware that *meat* used to be used for all food, and that *flesh* can be used for the body of living animals, but I assume neither fact is relevant here.)
(A similar question was asked at [What is the difference between "meat" and "flesh"?](https://english.stackexchange.com/questions/119699/what-is-the-difference-between-meat-and-flesh) , but it was closed as general reference) | 2015/10/15 | [
"https://english.stackexchange.com/questions/280351",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/1420/"
] | I suspect the main reason why *flesh* is not commonly associated with animals' carcasses stems from a sense of aversion, and sanctity.
Consider the expression, *[flesh and blood](http://idioms.thefreedictionary.com/flesh+and+blood)*, which is used in connection with our children, (*‘She is my own flesh and blood’*) our family, and our fellow beings. “We are only *flesh and blood*”, means we are only human, we are imperfect; but until very recently, Christians were taught that *man* was made in the image of God. This allowed them a greater status than the animals that roamed freely on land or in air. Our *flesh* deserved greater staus than that of mere beasts.
It was necessary to remind Christians that Man was unique; distinct from any land, sea or air creature.
>
> **All flesh is not the same flesh**: but there is one kind of flesh of men, another flesh of beasts, another of fishes, and another of birds.
>
> King James Bible: 1 Corinthians 15:39
>
>
>
Furthermore, Eve was made from the flesh of Adam:
>
> And Adam said, This is now bone of my bones, and **flesh of my flesh**: she shall be called Woman, because she was taken out of Man.
>
> King James Bible: Genesis 2:23
>
>
>
And when a couple married the expression *one flesh* was used to convey the intimate union between two human beings.
>
> And they twain shall be one flesh: so then they are no more twain, but **one flesh.**
>
> KJB: Mark 10:8
>
>
>
In the New Testament, The King James Version contains the above mentioned idiom
>
> And Jesus answered and said unto him, Blessed art thou, Simon Barjona: for **flesh and blood** hath not revealed it unto thee, but my Father which is in heaven.
>
>
>
In Jeremiah 19:9 the following horrific revelation was made
>
> And I will cause them **to eat the flesh of their sons** and **the flesh of their daughters**, and they shall eat every one the flesh of his friend in the siege and straitness, wherewith their enemies, and they that seek their lives, shall straiten them.
>
>
>
The horror is all the more heightened because to eat the *flesh* of a dead human child is not comparable to the *meat* of a dead cow, sheep, or pig.
The distinction between *flesh* and *meat* has been instilled in us for over six hundred years. If we look at the etymology of ‘meat’ we find
>
> Old English *mete* "food, item of food" (paired with drink), from Proto-Germanic \*mati (cognates: Old Frisian *mete*, Old Saxon *meti*, Old Norse *matr*, Old High German *maz*, Gothic *mats* "food," Middle Dutch, Dutch *metworst*, German Mettwurst "type of sausage"), from PIE *mad-i-*, from root \*mad- "moist, wet," also with reference to food qualities, (cognates: Sanskrit *medas-* "fat" (n.), Old Irish *mat* "pig;").
>
> **Narrower sense of "flesh used as food"** is first attested **c. 1300**; similar sense evolution in French *viande* "meat," originally "food." In Middle English, vegetables still could be called *grene-mete* (15c.) […]
>
> [Etymonline](http://www.etymonline.com/index.php?term=meat&allowed_in_frame=0)
>
>
>
---
Colin Fine in the comments asks:
>
> But three hundred years ago, there wasn't a word in English which meant what meat means now: the only word for "animal's flesh for eating" was "flesh", So how can you claim that the distinction between meat and flesh goes back two thousand years?
>
>
>
I admit, I didn't know the term *[flesh](http://dictionary.reference.com/browse/flesh)* was older than *meat*; the former is before 900 while *meat* meaning ‘flesh that we eat’ is from 1300; and that meaning is older than three hundred years.
It is safe to say that by [Early modern English](http://public.oed.com/aspects-of-english/english-in-time/early-modern-english-an-overview/), the distinction had been established. The above quotations are from the [King James Bible](http://www.phrases.org.uk/meanings/bible-phrases-sayings.html), first printed in 1611-1612, and I believe the division between ‘human flesh’ meaning soft human tissue and ‘meat’ was reinforced by those renowned passages.
---
The OP claims that English uses the term *flesh* in compound words referring only to certain animals, e.g. *horse flesh*, but not with other domestic or equally as intelligent animals such as dogs or dolphins. If we look at the [Ngram](https://books.google.com/ngrams/graph?content=horsemeat%2Chorseflesh%2C+horse-flesh&year_start=1700&year_end=2000&corpus=18&smoothing=3&share=&direct_url=t1%3B%2Chorsemeat%3B%2Cc0%3B.t1%3B%2Chorseflesh%3B%2Cc0%3B.t1%3B%2Chorse%20-%20flesh%3B%2Cc0#t1%3B%2Chorsemeat%3B%2Cc1%3B.t1%3B%2Chorseflesh%3B%2Cc1%3B.t1%3B%2Chorse%20-%20flesh%3B%2Cc1) of the British English corpus, which is arguably older than its American English counterpart; we see that the compounds *horseflesh* and its hyphenated variant, *horse-flesh*, were the far more common than *horsemeat* (blue line) or *horse-meat*.
[](https://i.stack.imgur.com/hjtyW.png)
Examples:
* “It seems, however, that as recently as 1817, there was a quantity of **horse-flesh** sold for human food in Paris” (*Essays on Physiology and Hygiene*, 1838)
* “Many authors are quoted with regard to the wholesomeness of horse-flesh, whose opinions differ. One says, "that of those who eat **the flesh of diseased horses**, nine out often die; it should be roasted and eaten with ginger and pork."”
(*The Chinese Repository*, 1839)
* “... and, divesting the mind of the inferiority of **horse-flesh** over **cow or bullock-flesh**, the food of hounds, both in its nature and cooking of it, is such as man might not only reject, if necessity compelled him to have recourse to it, […] It is a common expression, that “any thing will do for the dogs,” but hounds, to be in condition, must have every thing good of its kind, and also well cooked. [...] and **well-boiled horse-flesh**, quite free from taint. [...] When taken out of the boiler, it forms a substance resembling coarse rice pudding; and when the fresh flesh, which is shredded, and the broth in which it is boiled, are added to it in the trough, and very well mixed, it forms the best and highest food that can be given to hounds.”
(*The Horse and The Hound*, 1842)
* “Since the siege of Copenhagen in 1807, **horse flesh** has regularly been sold by the butchers in that capital for general consumption.”
(*Monthly Retrospect of the Medical Sciences*, 1848)
Overwhelmingly, the meaning of horseflesh (the equivalent of today's *horse-meat*, and *horse-beef*) is that of food for human or animal consumption.
The shift from *horseflesh* meaning meat=food, to the *live* animal's flesh began after the 1970s, and it appears its popularity as a source of food has been decreasing ever since.
* “She really was a slick little piece of horse flesh except for her occasional kicking spell.” […] “He had one mare, **a splendid piece of horse flesh**, who had raised him twenty-seven head, besides giving him years of hard work.”
(Mister, You Got Yourself a Horse: Tales of Old-Time Horse Trading, 1981)
* “At that time **I was not a very good judge of horseflesh. The horse appeared sound and gentle**, and, as the owner assured me, had no bad habits. The man wanted a large price for the horse, but finally agreed to accept a much smaller sum, ...”
(*The Conjure Woman, and Other Conjure Tales*)
* **Good Judge of Horseflesh**:
”**A man with good taste in women**. A buyer, trader, breeder, or racer of horses who is a good judge of horseflesh is able to size up the potential value of a horse just by looking at it or watching it perform. A bachelor is a good judge of horseflesh if he consistently escorts beautiful women or manages to convince the most beautiful one to be his bride. Granted, the woman is being equated with horseflesh; but at the wedding, it is the man who becomes the *groom*.”
(*Speaking of Animals: A Dictionary of Animal Metaphors*, 1995)
Finally, one long excerpt from a book entitled *Unmentionable Cuisine*
*Horsemeat*
------------
>
> If asked to explain their personal aversions to eating horsemeat, a few Americans might say something about the taste of the meat not comparing favorably with beef. **Many others would mention the “nobility” of the horse and therefore its unsuitability for food**. Perhaps a few people would relate their horsemeat prejudice to the lingering effects of **prohibitions by the Catholic Church that were intended to break the horsemeat-eating habits originally associated with horse worship** by the ancestors of many of us.
>
> […]
>
> In pre-Christian times, horsemeat eating in northern Europe figured prominently in Teutonic religious ceremonies, particularly those associated with the worship of the god Odin. So much so, in fact, that in A.D. 732 Pope Gregory III began a concerted effort to stop this pagan practice, […] The Angles of England were among those peoples who regarded the horse too holy an animal to eat routinely, reserving it for communion meals, and some believe that this prohibition has carried over into the strong prejudices in England today against eating horsemeat.
> [...]
>
> Horsemeat is called *chevaline* in France and often, like pork, is sold in separate butcher shops. From time to time there has have been strong movements to increase the use of horsemeat in French cuisine, for it can be prepared essentially as one would beef. […] during the beef shortage in 1973 and because of high beef prices since, quite a bit of newspaper publicity has been given to butcher shops doing a land-office business in horsemeat […] **In 1972 the U.S. federal veterinary services passed the meat of 68,000 horses as suitable for human consumption.**
>
>
>
*[Unmentionable Cuisine](https://books.google.it/books?id=SiBntk9jGmoC&pg=PA157&dq=%22horse%20meat%22&hl=en&sa=X&ved=0CEkQ6AEwBmoVChMIq9WPuYHbyAIVS74UCh0qBgqu#v=onepage&q=%22horse%20meat%22&f=false)* By Calvin W. Schwabe (1979, and fourth printing 1996)
Note, that not once does the author use the compound horseflesh in the entire chapter, horsemeat refers to the carcass of the animal in question. | Language is ever evolving though so making arguments based solely on older definitions and usage doesn't account for all of the morphology of the word, since there are examples in modern usage. I would agree with OP that those are common phrases that I've heard as a native English speaker. Another commenter included the phrase "bags of meat" in reference to humans, which I have heard used in a sarcastic or existential way specifically by young people. I am further confused by another usage for meat "you need to put some meat on your bones."
The "meat" of the question is, is the term meat becoming used slightly more often to mean non edible flesh? I would argue yes, though only in certain contexts where there cannot be confusion about edibility/ intention about consumption.
Yes, the above example is used in an old children's story by a cannibal planning to eat children, however as a modern English speaker I most often hear that phrase from my brother's coach who wants him to grow muscle, etc. I would argue that in modern usage, the phrase does not allude to consumption, even if that does have to do with the origins. Curious to hear other people's thoughts on this! Please let me know if I should call someone about my brother's coach... |
280,351 | Some animals have different words for the animal and for the meat - *cow/beef*, *pig/pork*. Some animals just use the same word without any compound - *fish*, *quail*.
But some animals use compounds of the form [animal] *meat*, while others use [animal] *flesh*. I looked at the Wiktionary entry on *[flesh](https://en.wiktionary.org/wiki/flesh)*, and it didn't really explain when to use *flesh* rather than *meat*, and why it is the case.
We talk about "human flesh" not "human meat", and can use either "horse flesh" or "horse meat", and we use *meat* not *flesh* for kangaroos, dogs, whales or dolphins, all of whom tend to be "friends not food" to most English-speakers.
Is the difference that *flesh* used to be more common than it is nowadays, and *human flesh* and *horse flesh* entered English earlier than the other phrases? Wiktionary mentioned some uses of *flesh* as archaic.
(I'm aware that *meat* used to be used for all food, and that *flesh* can be used for the body of living animals, but I assume neither fact is relevant here.)
(A similar question was asked at [What is the difference between "meat" and "flesh"?](https://english.stackexchange.com/questions/119699/what-is-the-difference-between-meat-and-flesh) , but it was closed as general reference) | 2015/10/15 | [
"https://english.stackexchange.com/questions/280351",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/1420/"
] | "Meat" is "flesh" that one would consider eating.
>
> We talk about "human flesh" not "human meat"
>
>
>
*because we don't eat humans.*
>
> we use *meat* not *flesh* for kangaroos, dogs, whales or dolphins, all of whom tend to be "friends not food" to most English-speakers.
>
>
>
I'm not sure who "we" is but as a native English speaker, I would only use "meat" if the conversation included the concept of somebody eating it. If a fellow native speaker used the word, I would interpret that to mean s/he is invoking the concept that it could be eaten.
I would also use "flesh" for the relevant parts of a creature that is still alive, unless the intended meaning to be conveyed includes the concept of killing and eating it (e.g. a discussion about hunting).
Paired with "dish," the [result in Google Ngram viewer](https://books.google.com/ngrams/graph?content=meat%20dish%2Cflesh%20dish&case_insensitive=on&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t4%3B%2Cmeat%20dish%3B%2Cc0%3B%2Cs0%3B%3Bmeat%20dish%3B%2Cc0%3B%3BMeat%20Dish%3B%2Cc0%3B%3BMeat%20dish%3B%2Cc0%3B%3BMEAT%20DISH%3B%2Cc0) is striking (pairing with "flesh" isn't even found). | Language is ever evolving though so making arguments based solely on older definitions and usage doesn't account for all of the morphology of the word, since there are examples in modern usage. I would agree with OP that those are common phrases that I've heard as a native English speaker. Another commenter included the phrase "bags of meat" in reference to humans, which I have heard used in a sarcastic or existential way specifically by young people. I am further confused by another usage for meat "you need to put some meat on your bones."
The "meat" of the question is, is the term meat becoming used slightly more often to mean non edible flesh? I would argue yes, though only in certain contexts where there cannot be confusion about edibility/ intention about consumption.
Yes, the above example is used in an old children's story by a cannibal planning to eat children, however as a modern English speaker I most often hear that phrase from my brother's coach who wants him to grow muscle, etc. I would argue that in modern usage, the phrase does not allude to consumption, even if that does have to do with the origins. Curious to hear other people's thoughts on this! Please let me know if I should call someone about my brother's coach... |
347,158 | We are having integration with the Salesforce from the Mulesoft. Now, as Salesforce is planning to roll-out MFA for all apps. Will it affect our API integration? | 2021/06/17 | [
"https://salesforce.stackexchange.com/questions/347158",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/87961/"
] | Salesforce Functions is not GA. Until the feature becomes GA or you obtain access to a preview program and follow any applicable setup instructions, you won't be able to use that command or follow steps in demo videos.
Clarification: I don't know whether there are any preview programs available at the time of this writing. The situation may have changed if you're reading this answer in the future. Discuss your interest in this feature with your Account Executive. | To apply for the Beta, you need to sign up via <https://sfdc.co/functions-beta>
Once you have been approved, and have access to the feature in your dev hub, you need to follow the steps from the documentation:
[Configure Orgs for Functions](https://developer.salesforce.com/docs/platform/functions/guide/config-org.html#enable-functions-on-dev-hub-orgs):
1. Enable Functions on Dev Hub Orgs
2. Create Compute Environment for Org
3. Enable the Functions feature in your scratch org definition file.
and follow the steps outlined in : [Deploy a Function](https://developer.salesforce.com/docs/platform/functions/guide/deploy#connect-salesforce-functions-to-your-org) |
123,118 | I have installed two magento on my local server.*I added product from my first magento installation its added fine but it also display in second magento installation*. **Why does this happen? Any one have same issue?**
[](https://i.stack.imgur.com/b7BQr.png)
[](https://i.stack.imgur.com/BBhwn.png)
Display product in cart in second image it is not exists in my second magento. | 2016/06/28 | [
"https://magento.stackexchange.com/questions/123118",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/28492/"
] | According to your URLs, **my guess is that your two Magento installations share the cookies and/or sessions.**
As they use the same base URLs, the cookies from the second install are being shared with the second installation.
I suggest you **avoid using the same URLs for two different installations and setup proper different hosts for each installation.** | You are using same URL for 2 sites. So the cookies will be shared.
You should create different Url for each site.
Example:
Site 1: magento2.mcs.com
Site2 : magento202.mcs.com
You can reference this document for create virtual host:
<https://httpd.apache.org/docs/current/vhosts/examples.html> |
77,782 | I have two tables, for simplicity table1, with id as Primary key, and a field name, and table2 with the same. Each table has quite a few records, but during a complicated form process, the user is presented with every record from table1, but depending on their choice in the form (done by radio, with id as the value) they may not have every result from table2 listed on the next part of the form. This is based on a 3rd table, table3, with id as primary key, table1\_id, table2\_id as records, which lists "invalid combinations" from table1 / table2.
So, I'm trying to generate the sql for showing table2, which needs to NOT have any records that match the choice from table1, that are listed in table3.
Subquery Table3, with a where statement of the choice made on table1, and use that as a NOT NULL Left join on table2? Every time I try to write the SQL I mess something up. | 2014/09/26 | [
"https://dba.stackexchange.com/questions/77782",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/48249/"
] | There are many ways to do this. Most common are with a `LEFT JOIN` / `IS NULL` check, `NOT IN` or `NOT EXISTS` subquery. Here's a solution with the 3rd option:
```
SELECT t2.id, t2.name
FROM table2 AS t2
WHERE NOT EXISTS
( SELECT *
FROM table3 AS t3
WHERE t3.table1_id = @t1_id -- the t1.id value (choice) that you want to check
AND t3.table2_id = t2.id
) ;
``` | Check this post out from a similar request to find records NOT IN another table.
[MySQL “NOT IN” query](https://stackoverflow.com/questions/1519272/mysql-not-in-query)
```
SELECT * FROM Table2 WHERE Table2.principal NOT IN (SELECT principal FROM table1)
```
Hope that helps! |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | Use this:
```
array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);
```
this will merge the arrays into one, then removes all duplicates
Tested [Here](http://sandbox.onlinephpfunctions.com/code/223f20bd509f1550af717fe7340403674d4a74a9)
It outputs:
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` | I think this will work just fine
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "<pre>";print_r($n_array);echo "</pre>";die;
```
Output is
```
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
[5] => six
[6] => seven
)
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | Use this:
```
array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);
```
this will merge the arrays into one, then removes all duplicates
Tested [Here](http://sandbox.onlinephpfunctions.com/code/223f20bd509f1550af717fe7340403674d4a74a9)
It outputs:
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` | use array\_merge then, array\_unique
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r(array_unique (array_merge($arr1,$arr2,$arr3)));
```
Result
```
Array ( [0] => one [1] => two [2] => three [4] => four [6] => five [7] => six [8] => seven )
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | Use this:
```
array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);
```
this will merge the arrays into one, then removes all duplicates
Tested [Here](http://sandbox.onlinephpfunctions.com/code/223f20bd509f1550af717fe7340403674d4a74a9)
It outputs:
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` | >
> **Just Do That.. use `array_uniqe`**
>
>
> Demo: <https://eval.in/827705>
>
>
>
```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3)));
?>
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | Use this:
```
array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR);
```
this will merge the arrays into one, then removes all duplicates
Tested [Here](http://sandbox.onlinephpfunctions.com/code/223f20bd509f1550af717fe7340403674d4a74a9)
It outputs:
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` | ```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$merge_arr = array_merge($arr1,$arr2,$arr3);
$unique_arr = array_unique($merge_arr);
echo '<pre>';
print_r($unique_arr);
echo '</pre>';
?>
```
Output
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | I think this will work just fine
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "<pre>";print_r($n_array);echo "</pre>";die;
```
Output is
```
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
[5] => six
[6] => seven
)
``` | use array\_merge then, array\_unique
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r(array_unique (array_merge($arr1,$arr2,$arr3)));
```
Result
```
Array ( [0] => one [1] => two [2] => three [4] => four [6] => five [7] => six [8] => seven )
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | I think this will work just fine
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "<pre>";print_r($n_array);echo "</pre>";die;
```
Output is
```
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
[5] => six
[6] => seven
)
``` | >
> **Just Do That.. use `array_uniqe`**
>
>
> Demo: <https://eval.in/827705>
>
>
>
```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3)));
?>
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | I think this will work just fine
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "<pre>";print_r($n_array);echo "</pre>";die;
```
Output is
```
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
[5] => six
[6] => seven
)
``` | ```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$merge_arr = array_merge($arr1,$arr2,$arr3);
$unique_arr = array_unique($merge_arr);
echo '<pre>';
print_r($unique_arr);
echo '</pre>';
?>
```
Output
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | >
> **Just Do That.. use `array_uniqe`**
>
>
> Demo: <https://eval.in/827705>
>
>
>
```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3)));
?>
``` | use array\_merge then, array\_unique
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r(array_unique (array_merge($arr1,$arr2,$arr3)));
```
Result
```
Array ( [0] => one [1] => two [2] => three [4] => four [6] => five [7] => six [8] => seven )
``` |
44,917,042 | I have these three arrays:
```
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
```
And this is expected result:
```
/* Array
(
[0] => one
[1] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)
```
---
[Here](https://3v4l.org/fdvtf) is my solution which doesn't work as expected:
```
print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
(
[0] => one
[1] => two
[2] => three
[3] => seven
)
```
How can I do that? | 2017/07/05 | [
"https://Stackoverflow.com/questions/44917042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | >
> **Just Do That.. use `array_uniqe`**
>
>
> Demo: <https://eval.in/827705>
>
>
>
```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3)));
?>
``` | ```
<?php
$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$merge_arr = array_merge($arr1,$arr2,$arr3);
$unique_arr = array_unique($merge_arr);
echo '<pre>';
print_r($unique_arr);
echo '</pre>';
?>
```
Output
```
Array
(
[0] => one
[1] => two
[2] => three
[4] => four
[6] => five
[7] => six
[8] => seven
)
``` |
59,937,931 | Okay, So I've done a fair bit of research on this particular topic previously, and I'm aware that it is a feature that the Flutter devs have not yet implemented to function automatically (setting the light and dark themes to change dynamically checking upon opening the app) but I know it IS possible. I don't want my users to need to make this choice, and I know I'm close, but I'm missing something important. I'll explain:
```
final Brightness brightnessValue = MediaQuery.of(context).platformBrightness;
bool isDark = brightnessValue == Brightness.dark;
```
Those two lines of code SHOULD pass through a boolean (dark theme true or false) into my code. Those lines of code ARE running, but they throw an error.
MediaQuery.of() called with a context that does not contain a MediaQuery. No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.). The context used was:
MyApp
see also:
<https://flutter.dev/docs/testing/errors>
Now I've seen some people implement this line of code and it works for them, so I know it's not a syntax thing. And I actually AM placing this line of code underneath a widgets app like they ask, (as far as I understand these things, so I'm stymied.
Pertinent Code:
```
CupertinoThemeData currentTheme;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final Brightness brightnessValue = MediaQuery.of(context).platformBrightness;
bool isDark = brightnessValue == Brightness.dark;
<CODE TO SELECT THEME DEPENDING ON PHONE'S THEME. Setting parameters of currentTheme>
return CupertinoApp(
<CODE FOR APP>
),
}
}
```
Now I WOULD put it inside the CupertinoApp Widget, but that doesn't work either, as you can't really make a function-call inside there, and I NEED to pass a theme into there, as that effects the entirety of the programs theming.
In essence, it looks like a chicken and the egg scenario, where I can't set the theme until I have the media-query, and I can't do the media-query until I've already set the theme, which negates the entire purpose of the query.
Any ideas? | 2020/01/27 | [
"https://Stackoverflow.com/questions/59937931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12627794/"
] | After banging my head against a brick wall for a few hours, finally figured it out (For anyone else having a similar issue).
The trick is that yes, you do in fact need to place the code that selects the theme inside the line
```
return CupertinoApp( <Here> )
```
You can do this through:
```
builder: (BuildContext context, Widget child) {
final Brightness brightnessValue = MediaQuery.of(context).platformBrightness;
bool isDark = brightnessValue == Brightness.dark;
// All your code to set your two themes, light and dark can go here.
}
```
In this way, instead of the chicken&egg scenario I was imagining, you are setting the theme state at the moment you need it.
Hope this helps someone. | Placing a DefaultTextStyle widget somewhere near the top of the widget tree is a good workaround. Just remember it needs to be one level lower than the CupertinoApp, or else it cannot find the inherited theme using its build context.
```
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoApp(
home: Builder(
builder: (BuildContext context) {
return DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: MyHomePage(),
);
},
),
);
}
}
```
This way, any default Text will automatically resolve to white or black, depending on the platform brightness settings.
Sample result:
[](https://i.stack.imgur.com/tKyKC.png) |
17,191,070 | I have an application with multiple view controllers. I created categories to change colors of each element (UIButton, UILabel, UIView etc).
Everything is going fine for all elements but one. I can't find out how to change the tint of the UINavigationBar of a reusableView (header) in a CollectionView.
I managed to change the color of other UINavigation bars that are not in a collectionView.
What I am supposed to do? Any idea? | 2013/06/19 | [
"https://Stackoverflow.com/questions/17191070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915800/"
] | Within your click handler, check if the number of elements with the class **line** is less than 10.
```
if ($('.line').length < 10) {
//execute code
}else{
alert('Only 10 allowed');
return false;
}
```
[Fiddle](http://jsfiddle.net/24zD9/) | Here I used the .length method from jQuery.
```
var container = $('.copies'),
value_src = $('#current');
$('.copy_form')
.on('click', '.add', function(){
if ($('.accepted').length < 10)
{
var value = value_src.val();
var html = '<div class="line">' +
'<input class="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
}
else
{
alert("Only 10 allowed");
}
})
.on('click', '.remove', function(){
$(this).parents('.line').remove();
});
```
[Fiddle](http://jsfiddle.net/9sX6X/20/) |
17,191,070 | I have an application with multiple view controllers. I created categories to change colors of each element (UIButton, UILabel, UIView etc).
Everything is going fine for all elements but one. I can't find out how to change the tint of the UINavigationBar of a reusableView (header) in a CollectionView.
I managed to change the color of other UINavigation bars that are not in a collectionView.
What I am supposed to do? Any idea? | 2013/06/19 | [
"https://Stackoverflow.com/questions/17191070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915800/"
] | Rather than embedding 'magic numbers' in your code (see: [What is a magic number, and why is it bad?](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad)), define a maxFields variable and maintain a count throughout, checking against that value each time another one tries to be added.
This allows your code to be more portable and reusable by someone else, or by you for another use case, when say you want 20 fields.
It also reads more like English (current field is less than max fields) which leads to self documentation.
<http://jsfiddle.net/9sX6X/21/>
```
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.copy_form').on('click', '.add', function () {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input class="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
currentFields--;
});
```
From Wikipedia:
>
> The term magic number also refers to the bad programming practice of
> using numbers directly in source code without explanation. In most
> cases this makes programs harder to read, understand, and maintain.
> Although most guides make an exception for the numbers zero and one,
> it is a good idea to define all other numbers in code as named
> constants.
>
>
> | Here I used the .length method from jQuery.
```
var container = $('.copies'),
value_src = $('#current');
$('.copy_form')
.on('click', '.add', function(){
if ($('.accepted').length < 10)
{
var value = value_src.val();
var html = '<div class="line">' +
'<input class="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
}
else
{
alert("Only 10 allowed");
}
})
.on('click', '.remove', function(){
$(this).parents('.line').remove();
});
```
[Fiddle](http://jsfiddle.net/9sX6X/20/) |
816,964 | I'd be needing to connect to several AWS EC2 instances and putty works fine with the keys, but it's just one at a time. I also tried Remmina, however it keeps asking SSH private keyphrase what it shouldn't. Any other suggestion? | 2016/08/26 | [
"https://askubuntu.com/questions/816964",
"https://askubuntu.com",
"https://askubuntu.com/users/539828/"
] | I've observed the same issue, but it's only noticeable when playing a graphically intensive game or watching a youtube video in my browser. In these cases, the game/video freezes in place for about half a second upon changing focus, and then resumes as normal. With sloppy focus, if I move the mouse rapidly between 2 windows, I can keep the video frozen on the same frame almost indefinitely.
Disabling the Ubuntu Unity Plugin does completely remove the lag, but of course that's not a real fix as it leaves you with a half-functional GUI.
So far the only solution I am aware of is switching to a non-Unity desktop environment. I'm partial to openbox, though there are plenty of choices here. | Probably the same issue as [CPU spikes and performance problems changing window focus in Unity/Ubuntu 16.04.2](https://askubuntu.com/questions/890888/cpu-spikes-and-performance-problems-changing-window-focus-in-unity-ubuntu-16-04).
I'm also seeing this on 16.04 with i5-4460 and a GTX 960 on a 32bit system (don't ask!) I don't see it with nouveau drivers but I do with the NVidia proprietary ones (all I've tested up to 381.13.)
Although not a proper solution, restarting unity by using `unity --replace` seems to work around the issue for that session. (You might need to try it again if it doesn't work first time.)
This could be related to [bugs.launchpad.net/ubuntu/+source/unity/+bug/1300892](http://bugs.launchpad.net/ubuntu/+source/unity/+bug/1300892). If you think that bug affects you then please do click "This bug affects me" at the top so that the maintainers get a good reflection of how many people this bug impacts as this is currently triaged as a low priority bug.
**EDIT: It seems that adding the command `/usr/bin/unity --replace` command to "Startup Applications" does work okay as a kludgy but less temporary workaround. :)** |
11,826,806 | I am trying to import an OSGI blueprint XML file in to another OSGi blueprint XML file.
e.g.:
blueprint1.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<blueprint ....>
<bean id="myBean1" class="com.company.Class1"/>
<bean id="myBean2" class="com.company.Class2"/>
</blueprint>
</xml>
```
blueprint2.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<blueprint ....>
<!-- DOES NOT WORK -->
<import resource="blueprint1.xml" />
</blueprint>
```
The `<import>` works for spring but not for blueprint.
Does anybody know a way of doing this in OSGi blueprint XML files? | 2012/08/06 | [
"https://Stackoverflow.com/questions/11826806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896805/"
] | Apparently, Spring like imports are not currently possible in blueprint.
However, if the files are in the same OSGi bundle then they are in the same context and can be used from other blueprint files.
Also, see here: <http://fusesource.com/forums/message.jspa?messageID=15091#15091> | If you're using Gemini Blueprint (formerly Spring DM) you can simply tell it to load both files, and basically treat them as if they were one big file:
>
> In the absence of the Spring-Context header the extender expects every
> ".xml" file in the META-INF/spring folder to be a valid Spring
> configuration file [...].
>
>
>
It also treats any xml files in `/OSGI-INF` in the same way. |
461,030 | Some websites, notably Github, started using special downloadable fonts and various little pictures are broken when font downloading is disabled.
How to statically install just GitHub's font into Firefox without enabling font downloading from web? | 2012/08/13 | [
"https://superuser.com/questions/461030",
"https://superuser.com",
"https://superuser.com/users/27264/"
] | Browsers may cache font resources (`.woff` etc.), but usually don’t support a permanent install. If the font license allows it, you could fetch the file ([fontinfo addon](https://addons.mozilla.org/en/firefox/addon/fontinfo/) may help), convert it to a format your OS supports (usually `.ttf`/`.otf`, several tools and services available) and install it locally, but you may have to add rules to your user stylesheet if the site authors didn’t anticipate anyone would have the font installed on their system (`local()` in `src` descriptor of `@font-face` rule). For many FOSS fonts, you’ll be able to find an up-to-date copy in several font formats on the respective homepage/repository, e.g. [Octicons](https://octicons.github.com) for Github, so no need for converting the WOFF yourself. | It is *possible* that the following will work:
* Download <https://github.global.ssl.fastly.net/assets/octicons-42317b4656db563d0370825b447f9df85a9f4bd5.woff>
* Save it to, eg., `C:\Windows\Fonts`
Then again, it might not work. If it doesn't, try renaming it to `octicons.woff`.
I haven't tried this: it might do all sorts of disastrous things. I personally can't understand why you block CSS fonts.
(This is installing to Windows, not Firefox.) |
3,589,863 | In Stanford Encyclopedia of Philosophy they say that (for a formal system F) by the Diagonalization Lemma a sentence G can be constructed: $F \vdash G\_F$ $\leftrightarrow$ $\lnot Prov(⌈G\_F⌉)$. This sentence G basically says that F proves $G\_F$ iff the Goedelnumber of $G\_F$ is not provable.
If I assume G then I can totally follow them on why neither $G\_F$ nor $\lnot G\_F$ is not provable, but my problem is this: why do I have to assume G, what if I just assume ~G? Then the whole problem resolves and everything seems fine because ~G $ \equiv$ $(F \vdash G\_F$ $\land$ $Prov(⌈G\_F⌉))$ $\lor$ $ (\lnot Prov(⌈G\_F⌉) \land F\nvdash G\_F)$. | 2020/03/22 | [
"https://math.stackexchange.com/questions/3589863",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | You misunderstood: $G$ is not the biconditional $(F \vdash G\_F) \leftrightarrow (\lnot Prov(⌈G\_F⌉))$. Rather, $G$ is the *metalogical* claim that the biconditional $G\_F$ $\leftrightarrow$ $\lnot Prov(⌈G\_F⌉)$ (which is a logical claim) can be proven in $F$. And that metalogical claim we write as $F \vdash G\_F \leftrightarrow \lnot Prov(⌈G\_F⌉)$ (think of it as $F \vdash (G\_F \leftrightarrow \lnot Prov(⌈G\_F⌉))$
Moreover, it is not claim $G$ that is what is typically referred to as the 'Godel sentence', but rather $G\_F$. That is, Godel's proof shows that relative to any 'strong enough' (strong enough to prove elementary arithmetical truths basically), consistent, and recursive formal system $F$, there must be some sentence $G\_F$ such that $F \vdash G\_F$ $\leftrightarrow$ $\lnot Prov(⌈G\_F⌉)$ is the case. When you now assume that $G\_F$ is false, you get a problem, because then, given the truth of the biconditional (it's true since $F$ derives it), it would have to be true that $G\_F$ is provable, and thus true, which contradicts the assumption that is was false. So, it must be true. And, given that same biconditional, not provable.
The truth of $G$ itself is not under discussion. Godel's proof that $G$ has to be the case. | The diagonal lemma isn't used to construct what you call $G$, but rather $G\_F$. Really, we should ignore $G$ altogether and just focus on what's going on "inside $F$."
* EDIT: actually, it's even worse than that! [The article](https://plato.stanford.edu/entries/goedel-incompleteness/#FirIncTheCom) uses $G$ ambiguously to refer to both the *sentence* $G\_F\leftrightarrow Prov\_F(\underline{\ulcorner G\_F\urcorner})$ (note that the article also omits the numeralization here!) and the *sequent* $F\vdash G\_F\leftrightarrow Prov\_F(\underline{\ulcorner G\_F\urcorner})$ (look at the first appearance of $(G)$). I'm normally a fan of SEP, but in my opinion this is a situation where this kind of minor sloppiness is a really bad idea.
---
To start with, let's state the diagonal lemma precisely. For $F$ an "appropriate" system the diagonal lemma says the following:
>
> For every formula $\varphi$ there is some sentence $\theta$ such that $$F\vdash\theta\leftrightarrow\varphi(\underline{\ulcorner\theta\urcorner}).$$
>
>
>
Here "$\ulcorner\psi\urcorner$" is the Godel number of a sentence $\psi$ and "$\underline{n}$" is the numeral corresponding to $n\in\mathbb{N}$. So the diagonal lemma is really doing two things: given a formula $\varphi$, it produces a particular sentence **and** a particular $F$-proof.
This may seem rather mysterious until you read the proof of the diagonal lemma in detail to see how the desired sentence $\theta$ and $F$-proof of $\theta\leftrightarrow\varphi(\underline{\ulcorner\theta\urcorner})$ are constructed from a given $\varphi$. It's quite concrete, but tedious and often opaque at first glance.
In the incompleteness theorem, then, we apply the diagonal lemma with $\neg Prov$ as our $\varphi$. (Well, at first - we later use [Rosser's trick](https://en.wikipedia.org/wiki/Rosser%27s_trick) to get a different choice of $\varphi$ that works even better.)
---
A couple quick comments:
* "Produces" is a good word to use above: the diagonal lemma is totally constructive.
* Meanwhile, the diagonal lemma doesn't tell us that $\theta$ **literally is** $\varphi(\underline{\ulcorner\theta\urcorner})$, but merely that $\theta$ and $\varphi(\underline{\ulcorner\theta\urcorner})$ are $F$-equivalent. That said, see [here](https://mathoverflow.net/questions/83155/can-we-find-strong-fixed-points-in-the-fixed-point-lemma-of-g%C3%B6dels-incompletene). |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Maybe that one? It searches by `zip` first. Then if no records found the second part of `union all` searches by acc\_number.
```
;with _raw as (
select
name, city, zip, acc_number
from mytable
where zip ='01111'
union all
select
name, city, zip, acc_number
from mytable
where acc_number = '00007'
)
select top 1
*
from _raw
``` | How about this:
```
select name, city, zip, acc_number
from mytable
where zip ='01111'
or acc_number = '00007'
```
I am not sure if I have understood your question correctly, but this will search based on the zip being '01111' (and ignoring the acc\_number), or searching based on the acc\_number being '00007', and ignoring the zip.
If I have misunderstood then please let me know. |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Since you mentioned that you are already filtering out the parameter to check if it is `zip` or `acc_number` your query should be
```
declare @Zip int = 07652;
declare @acc_number int;
select top 1
name, city, zip, acc_number from mytable
where
1 = case when isnull(@zip,0)!=0 and zip = @Zip then 1 else 0 end
or
1 = case when isnull(@zip,0)=0 and acc_number = @acc_number then 1 else 0 end
``` | How about this:
```
select name, city, zip, acc_number
from mytable
where zip ='01111'
or acc_number = '00007'
```
I am not sure if I have understood your question correctly, but this will search based on the zip being '01111' (and ignoring the acc\_number), or searching based on the acc\_number being '00007', and ignoring the zip.
If I have misunderstood then please let me know. |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Maybe that one? It searches by `zip` first. Then if no records found the second part of `union all` searches by acc\_number.
```
;with _raw as (
select
name, city, zip, acc_number
from mytable
where zip ='01111'
union all
select
name, city, zip, acc_number
from mytable
where acc_number = '00007'
)
select top 1
*
from _raw
``` | Something like this? Your question is not 100% clear
```
select name, city, zip, acc_number
case when zip ='01111' then 'Match'
else when acc_number acc_number = '00007' then 'Match'
else 'Not match' end as nodata
from mytable
``` |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Since you mentioned that you are already filtering out the parameter to check if it is `zip` or `acc_number` your query should be
```
declare @Zip int = 07652;
declare @acc_number int;
select top 1
name, city, zip, acc_number from mytable
where
1 = case when isnull(@zip,0)!=0 and zip = @Zip then 1 else 0 end
or
1 = case when isnull(@zip,0)=0 and acc_number = @acc_number then 1 else 0 end
``` | Something like this? Your question is not 100% clear
```
select name, city, zip, acc_number
case when zip ='01111' then 'Match'
else when acc_number acc_number = '00007' then 'Match'
else 'Not match' end as nodata
from mytable
``` |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Maybe that one? It searches by `zip` first. Then if no records found the second part of `union all` searches by acc\_number.
```
;with _raw as (
select
name, city, zip, acc_number
from mytable
where zip ='01111'
union all
select
name, city, zip, acc_number
from mytable
where acc_number = '00007'
)
select top 1
*
from _raw
``` | You just need a conditional where clause. What this allows you to do is pass in values for either, both, or neither parameters. If both parameters are passed in the results that are returned are based off both conditions. That is, where the account number is what you passed in **AND** the zip code is passed in. If you only pass in one parameter, only that one is used to limit results. If you leave them both `NULL`, all records are returned.
```
declare @zip varchar(16), @acc_number varchar(16)
set @zip = null
set @acc_number = '00007'
if @zip is not null set @acc_number = null
select
name,
city,
zip,
acc_number
from
mytable
where
(zip = @zip or @zip is null)
and
(acc_number = @acc_number or @acc_number is null)
``` |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Since you mentioned that you are already filtering out the parameter to check if it is `zip` or `acc_number` your query should be
```
declare @Zip int = 07652;
declare @acc_number int;
select top 1
name, city, zip, acc_number from mytable
where
1 = case when isnull(@zip,0)!=0 and zip = @Zip then 1 else 0 end
or
1 = case when isnull(@zip,0)=0 and acc_number = @acc_number then 1 else 0 end
``` | You just need a conditional where clause. What this allows you to do is pass in values for either, both, or neither parameters. If both parameters are passed in the results that are returned are based off both conditions. That is, where the account number is what you passed in **AND** the zip code is passed in. If you only pass in one parameter, only that one is used to limit results. If you leave them both `NULL`, all records are returned.
```
declare @zip varchar(16), @acc_number varchar(16)
set @zip = null
set @acc_number = '00007'
if @zip is not null set @acc_number = null
select
name,
city,
zip,
acc_number
from
mytable
where
(zip = @zip or @zip is null)
and
(acc_number = @acc_number or @acc_number is null)
``` |
44,461,449 | the program can accept two inputs to search by, using zip code or account number. Trying to make the SQL work with either one, I am using sql server.
```
select name, city, zip, acc_number
case when zip then zip ='01111'
when acc_number then acc_number = '00007'
else NULL end as nodata
from mytable
```
I am probably misunderstanding the case logic, I am trying to say, if zip has value use zip's value and do the search and ignore acc\_number and when zip is not true use the value in acc\_number, else return NULL.
Thanks for looking! | 2017/06/09 | [
"https://Stackoverflow.com/questions/44461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844930/"
] | Maybe that one? It searches by `zip` first. Then if no records found the second part of `union all` searches by acc\_number.
```
;with _raw as (
select
name, city, zip, acc_number
from mytable
where zip ='01111'
union all
select
name, city, zip, acc_number
from mytable
where acc_number = '00007'
)
select top 1
*
from _raw
``` | Since you mentioned that you are already filtering out the parameter to check if it is `zip` or `acc_number` your query should be
```
declare @Zip int = 07652;
declare @acc_number int;
select top 1
name, city, zip, acc_number from mytable
where
1 = case when isnull(@zip,0)!=0 and zip = @Zip then 1 else 0 end
or
1 = case when isnull(@zip,0)=0 and acc_number = @acc_number then 1 else 0 end
``` |
23,780,029 | I have a long css document that has px values that I need to convert to % values.
I am looking for a quick solution without having to change each value one by one.
Was wondering is there any JS code for automatically converting those values on the fly when the page loads?
So for example
Page container has a max width of 1000px, the news-div is 300px. So I would need to the JS to do the maths and convert the news-div value to 30%
Does something like this even exist?
Thanks | 2014/05/21 | [
"https://Stackoverflow.com/questions/23780029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3660176/"
] | Using nokogiri in this place seems a litte oversized. You can do this with plain ruby:
```
require 'net/http'
xml_content = Net::HTTP.get(URI.parse('http://www.heureka.cz/direct/xml-export/shops/heureka-sekce.xml'))
data = Hash.from_xml(xml_content)
```
Then your able to access the data as a hash object. | If we indent your XML you will see the problem:
```
<HEUREKA>
<CATEGORY>
<CATEGORY_ID>971</CATEGORY_ID>
<CATEGORY_NAME>Auto-moto</CATEGORY_NAME>
<CATEGORY>
<CATEGORY_ID>881</CATEGORY_ID>
<CATEGORY_NAME>Alkohol testery</CATEGORY_NAME>
<CATEGORY_FULLNAME>Heureka.cz | Auto-moto | Alkohol testery</CATEGORY_FULLNAME>
</CATEGORY>
</CATEGORY>
</HEUREKA>
```
The second category node is *inside* the first category node, so it also its child. Because of this `children.css('CATEGORY_NAME').inner_text` will return both names concatenated (`Auto-motoAlkohol testery`) for the first node, and the last one will have the expected data - (`Alkohol testery`).
Fix your XML:
```
<HEUREKA>
<CATEGORY>
<CATEGORY_ID>971</CATEGORY_ID>
<CATEGORY_NAME>Auto-moto</CATEGORY_NAME>
</CATEGORY>
<CATEGORY>
<CATEGORY_ID>881</CATEGORY_ID>
<CATEGORY_NAME>Alkohol testery</CATEGORY_NAME>
<CATEGORY_FULLNAME>Heureka.cz | Auto-moto | Alkohol testery</CATEGORY_FULLNAME>
</CATEGORY>
</HEUREKA>
```
And try again...
---
**Update**
If you can't change the XML, you can use `XPATH` instead of `CSS`, as its default behavior is to find the *immediate* children, rather than all the children (deep children):
```
def heurekacat
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::XML(open("http://www.heureka.cz/direct/xml-export/shops/heureka-sekce.xml"))
doc.css("CATEGORY").each do |node|
record = HeurekaCat.where("name" => children.xpath('CATEGORY_NAME').inner_text).first_or_initialize
record.category=node.xpath('CATEGORY_FULLNAME').inner_text
record.name=node.xpath('CATEGORY_NAME').inner_text
record.save
end
end
``` |
23,780,029 | I have a long css document that has px values that I need to convert to % values.
I am looking for a quick solution without having to change each value one by one.
Was wondering is there any JS code for automatically converting those values on the fly when the page loads?
So for example
Page container has a max width of 1000px, the news-div is 300px. So I would need to the JS to do the maths and convert the news-div value to 30%
Does something like this even exist?
Thanks | 2014/05/21 | [
"https://Stackoverflow.com/questions/23780029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3660176/"
] | If we indent your XML you will see the problem:
```
<HEUREKA>
<CATEGORY>
<CATEGORY_ID>971</CATEGORY_ID>
<CATEGORY_NAME>Auto-moto</CATEGORY_NAME>
<CATEGORY>
<CATEGORY_ID>881</CATEGORY_ID>
<CATEGORY_NAME>Alkohol testery</CATEGORY_NAME>
<CATEGORY_FULLNAME>Heureka.cz | Auto-moto | Alkohol testery</CATEGORY_FULLNAME>
</CATEGORY>
</CATEGORY>
</HEUREKA>
```
The second category node is *inside* the first category node, so it also its child. Because of this `children.css('CATEGORY_NAME').inner_text` will return both names concatenated (`Auto-motoAlkohol testery`) for the first node, and the last one will have the expected data - (`Alkohol testery`).
Fix your XML:
```
<HEUREKA>
<CATEGORY>
<CATEGORY_ID>971</CATEGORY_ID>
<CATEGORY_NAME>Auto-moto</CATEGORY_NAME>
</CATEGORY>
<CATEGORY>
<CATEGORY_ID>881</CATEGORY_ID>
<CATEGORY_NAME>Alkohol testery</CATEGORY_NAME>
<CATEGORY_FULLNAME>Heureka.cz | Auto-moto | Alkohol testery</CATEGORY_FULLNAME>
</CATEGORY>
</HEUREKA>
```
And try again...
---
**Update**
If you can't change the XML, you can use `XPATH` instead of `CSS`, as its default behavior is to find the *immediate* children, rather than all the children (deep children):
```
def heurekacat
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::XML(open("http://www.heureka.cz/direct/xml-export/shops/heureka-sekce.xml"))
doc.css("CATEGORY").each do |node|
record = HeurekaCat.where("name" => children.xpath('CATEGORY_NAME').inner_text).first_or_initialize
record.category=node.xpath('CATEGORY_FULLNAME').inner_text
record.name=node.xpath('CATEGORY_NAME').inner_text
record.save
end
end
``` | Simply change one line:
```
doc.css("CATEGORY").each do |node|
```
to the following:
```
doc.css("CATEGORY:has(CATEGORY_FULLNAME)").each do |node|
```
This selects only `CATEGORY` elements containing a `CATEGORY_FULLNAME` subelement.
As an alternative, the equivalent XPath:
```
doc.xpath("//CATEGORY[CATEGORY_FULLNAME]").each do |node|
``` |
23,780,029 | I have a long css document that has px values that I need to convert to % values.
I am looking for a quick solution without having to change each value one by one.
Was wondering is there any JS code for automatically converting those values on the fly when the page loads?
So for example
Page container has a max width of 1000px, the news-div is 300px. So I would need to the JS to do the maths and convert the news-div value to 30%
Does something like this even exist?
Thanks | 2014/05/21 | [
"https://Stackoverflow.com/questions/23780029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3660176/"
] | Using nokogiri in this place seems a litte oversized. You can do this with plain ruby:
```
require 'net/http'
xml_content = Net::HTTP.get(URI.parse('http://www.heureka.cz/direct/xml-export/shops/heureka-sekce.xml'))
data = Hash.from_xml(xml_content)
```
Then your able to access the data as a hash object. | Simply change one line:
```
doc.css("CATEGORY").each do |node|
```
to the following:
```
doc.css("CATEGORY:has(CATEGORY_FULLNAME)").each do |node|
```
This selects only `CATEGORY` elements containing a `CATEGORY_FULLNAME` subelement.
As an alternative, the equivalent XPath:
```
doc.xpath("//CATEGORY[CATEGORY_FULLNAME]").each do |node|
``` |
1,599,787 | a. My C# program will load a dll (which is dynamic), for now let's take a.dll (similarly my program will load more dll like b.dll, c.dll, etc....).
b. My program will invoke a method "Onstart" inside a.dll (it's constant for all the dll).
I am able to achieve the above 2 cases by reflection mechanism.
The problem is
a. If my a.dll have any reference say xx.dll or yy.dll, then when I try to Invoke
OnStart method of a.dll from my program. I am getting "could not load dll or one of its dependency".
See the code snippet
```
Assembly assm = Assembly.LoadFrom(@"C:\Balaji\Test\a.dll");
foreach (Type tp in assm.GetTypes())
{
if (tp.IsClass)
{
MethodInfo mi = tp.GetMethod("OnStart");
if (mi != null)
{
object obj = Activator.CreateInstance(tp);
mi.Invoke(obj,null);
break;
}
}
}
```
typically i am getting error on the line "object obj = Activator.CreateInstance(tp);" this is because a.dll has reference of xx.dll, but in my program i don't have the reference of xx.dll. Also, I cannot have the reference of xx.dll in my program because a.dll is a external assembly and can have any reference on it's own.
Kinldy help!!! | 2009/10/21 | [
"https://Stackoverflow.com/questions/1599787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193219/"
] | Have a look at this: <http://bytes.com/topic/c-sharp/answers/232691-how-dynamically-load-assembly-w-dependencies>. Basically, in the AssemblyResolve event, you need to load the referenced assemblies manually.
```
private Assembly AssemblyResolveHandler(object sender,ResolveEventArgs e)
{
try
{
string[] assemblyDetail = e.Name.Split(',');
string assemblyBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly assembly = Assembly.LoadFrom(assemblyBasePath + @"\" + assemblyDetail[0] + ".dll");
return assembly;
}
catch (Exception ex)
{
throw new ApplicationException("Failed resolving assembly", ex);
}
}
```
Not the best code, but should give you a general idea, I hope.
I do, however, agree that plugin-dlls should be packaged for complete, dependancy-less use. If they are allowed to load assemblies you don't have control over, then who knows what might happen. | Perhaps the second DLL reference isn't available to your application?
Make sure the second DLL is in the same directory as the first DLL or that the application is configured to look in a directory that does have the second DLL. |
1,599,787 | a. My C# program will load a dll (which is dynamic), for now let's take a.dll (similarly my program will load more dll like b.dll, c.dll, etc....).
b. My program will invoke a method "Onstart" inside a.dll (it's constant for all the dll).
I am able to achieve the above 2 cases by reflection mechanism.
The problem is
a. If my a.dll have any reference say xx.dll or yy.dll, then when I try to Invoke
OnStart method of a.dll from my program. I am getting "could not load dll or one of its dependency".
See the code snippet
```
Assembly assm = Assembly.LoadFrom(@"C:\Balaji\Test\a.dll");
foreach (Type tp in assm.GetTypes())
{
if (tp.IsClass)
{
MethodInfo mi = tp.GetMethod("OnStart");
if (mi != null)
{
object obj = Activator.CreateInstance(tp);
mi.Invoke(obj,null);
break;
}
}
}
```
typically i am getting error on the line "object obj = Activator.CreateInstance(tp);" this is because a.dll has reference of xx.dll, but in my program i don't have the reference of xx.dll. Also, I cannot have the reference of xx.dll in my program because a.dll is a external assembly and can have any reference on it's own.
Kinldy help!!! | 2009/10/21 | [
"https://Stackoverflow.com/questions/1599787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193219/"
] | Have a look at this: <http://bytes.com/topic/c-sharp/answers/232691-how-dynamically-load-assembly-w-dependencies>. Basically, in the AssemblyResolve event, you need to load the referenced assemblies manually.
```
private Assembly AssemblyResolveHandler(object sender,ResolveEventArgs e)
{
try
{
string[] assemblyDetail = e.Name.Split(',');
string assemblyBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly assembly = Assembly.LoadFrom(assemblyBasePath + @"\" + assemblyDetail[0] + ".dll");
return assembly;
}
catch (Exception ex)
{
throw new ApplicationException("Failed resolving assembly", ex);
}
}
```
Not the best code, but should give you a general idea, I hope.
I do, however, agree that plugin-dlls should be packaged for complete, dependancy-less use. If they are allowed to load assemblies you don't have control over, then who knows what might happen. | I think, it needs more explanation. Let me explain....
a. My C# program will load a dll (which is dynamic), for now let's take a.dll (similarly more dll like b.dll, c.dll, etc....).
b. My program will invoke a method "Onstart" (it's constant for all the dll) inside a.dll.
I am able to achieve the above 2 cases by reflection mechanism.
The problem is
a. If my a.dll have any reference say xx.dll or yy.dll, then when I try to Invoke
OnStart method of a.dll from my progra. I am getting "could not load dll or one of its dependency".
===================================================================================================
See the code snippet
```
Assembly assm = Assembly.LoadFrom(@"C:\Balaji\Test\a.dll");
foreach (Type tp in assm.GetTypes())
{
if (tp.IsClass)
{
MethodInfo mi = tp.GetMethod("OnStart");
if (mi != null)
{
object obj = Activator.CreateInstance(tp);
mi.Invoke(obj,null);
break;
}
}
}
```
Typically I am getting error on the line "object obj = Activator.CreateInstance(tp);"
this is because a.dll has reference of xx.dll, but I cannot have the same.
Also, I cannot have the reference of xx.dll in my program, because a.dll is dynamic and can have any reference on it's own. |
1,599,787 | a. My C# program will load a dll (which is dynamic), for now let's take a.dll (similarly my program will load more dll like b.dll, c.dll, etc....).
b. My program will invoke a method "Onstart" inside a.dll (it's constant for all the dll).
I am able to achieve the above 2 cases by reflection mechanism.
The problem is
a. If my a.dll have any reference say xx.dll or yy.dll, then when I try to Invoke
OnStart method of a.dll from my program. I am getting "could not load dll or one of its dependency".
See the code snippet
```
Assembly assm = Assembly.LoadFrom(@"C:\Balaji\Test\a.dll");
foreach (Type tp in assm.GetTypes())
{
if (tp.IsClass)
{
MethodInfo mi = tp.GetMethod("OnStart");
if (mi != null)
{
object obj = Activator.CreateInstance(tp);
mi.Invoke(obj,null);
break;
}
}
}
```
typically i am getting error on the line "object obj = Activator.CreateInstance(tp);" this is because a.dll has reference of xx.dll, but in my program i don't have the reference of xx.dll. Also, I cannot have the reference of xx.dll in my program because a.dll is a external assembly and can have any reference on it's own.
Kinldy help!!! | 2009/10/21 | [
"https://Stackoverflow.com/questions/1599787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193219/"
] | Have a look at this: <http://bytes.com/topic/c-sharp/answers/232691-how-dynamically-load-assembly-w-dependencies>. Basically, in the AssemblyResolve event, you need to load the referenced assemblies manually.
```
private Assembly AssemblyResolveHandler(object sender,ResolveEventArgs e)
{
try
{
string[] assemblyDetail = e.Name.Split(',');
string assemblyBasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly assembly = Assembly.LoadFrom(assemblyBasePath + @"\" + assemblyDetail[0] + ".dll");
return assembly;
}
catch (Exception ex)
{
throw new ApplicationException("Failed resolving assembly", ex);
}
}
```
Not the best code, but should give you a general idea, I hope.
I do, however, agree that plugin-dlls should be packaged for complete, dependancy-less use. If they are allowed to load assemblies you don't have control over, then who knows what might happen. | I think you can not do anything other than adding all references which are used .
ps : usually an external assembly should be complete for use (or the package will contain all needed assemblies so you can add them) |
2,577,040 | My question is inspired by [Functional puzzle: find $f(2)$](https://math.stackexchange.com/questions/2577003/functional-puzzle-find-f2)
A function $f\colon \mathbb{R}\to\mathbb{R}$ satisfies
$$f(x)=xf(x^2-3)-x$$
for all $x$. For which $x$ is the value of $f(x)$ known?
I know values of $f(x)$ for $x\in\{0,\pm1,\pm2\}$.
**Edit:** As @StevenStadnicki observed, a domain may be smaller than reals, so every suggestion how large it can be is also interesting. | 2017/12/22 | [
"https://math.stackexchange.com/questions/2577040",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/72361/"
] | This question is actually less well-formed than you think it is. First of all, there's the question of what 'for all $x$ means', because that isn't actually enough to specify a domain. For all $x\in\mathbb{Z}$? For all $x$ in $\mathbb{R}$? A function isn't a function unless you specify the domain *and* the range, and this question actually does neither.
But beyond that, you say *a* function, and that's actually another issue; we don't know if any such $f$ exists, and we don't know whether just one $f$ exists.
In the case where the domain of $f()$ is $\mathbb{Z}$, in particular, it seems clear that there are many such functions: since $x^2-3$ as a function is one-to-one from $n\gt 2$ to (but not onto) $\mathbb{N}$, any 'forced' value of $f()$ in this region is forced by only one previous value, and there are no further dependencies; $f(6)$ is defined by $f(3)$, $f(13)$ is defined by $f(4)$, etc. Any value of $f()$ that's not forced by virtue of having an argument of the form $n^2-3$ is completely free and can be taken to be anything whatsoever. Since 'most' (infinitely many) integers are not of the form $n^2-3$, this gives infinite degrees of freedom; there are either $2^\omega$ or $2^\mathfrak{c}$ such functions, depending on whether your range is $\mathbb{Q}$ or $\mathbb{R}$.
The case where the domain of $f()$ is $\mathbb{R}$ is rather more interesting; now $f()$ is one-to-one for $x\gt x\_0$, where $x\_0$ is the (largest) solution of $x\_0^2-3 = x\_0$; this turns out (by a quick quadratic theorem application) to be $x\_0=\frac12(1+\sqrt{13})\approx 2.3$. So in principle (see below!) we can pick any (half-open) interval $[x, x^2-3)$ for $x\gt x\_0$, choose an *arbitrary* $f()$ on this range, and then 'replicate' it up and down using the functional equation to get values of $f(x)$ for $x\in(x\_0,\infty)$. You can even get continuity on this domain by requiring that $\lim\_{t\to (x^2-3)^-}f(t)$ satisfy the functional equation. The oddness of $f()$ can then be used to reflect it over to $x\in(-\infty, -x\_0)$.
The catch with the above argument is that the 'excitement' in the middle can actually ripple outwards; in particular, for values of $x$ very near zero, we get values of $x^2-3$ near $-3$ and thus get a functional equation for $f()$ near $x=-3$ - or again, by reflection, near $x=3$. So not every arbitrary function will 'reflect down' to a valid one. Instead, it would take a careful analysis of the behavior of intervals under the mapping $x\mapsto x^2-3$ (and even moreso, the behavior under the inverse mapping) to determine 'whether 'fundamental regions' exist which can be replicated around. I suspect the structure would turn out to be somewhat Cantor-like, but it's hard for me to directly 'see' the relevant intervals at the moment. | If you know $x=0$ then you know $x^2-3=0\implies x=\pm\sqrt 3$ because:
$f(\pm \sqrt 3)=\pm \sqrt 3f(0)-\pm \sqrt 3$
Now you can solve for $x^2-3=\pm\sqrt3$ with the same logic, and so on.
With this you can create few sets of answers, with those you may can work to more sets(I didn't try to find the values for those sets so idk if you can do further calculations) |
56,029,423 | I'm working on a android app that will display gemstones. Putting thumbnails in drawable-XXSIZE is not a problem, but how can I continue this with expansion files?
If I create folders such as: drawable-ldpi, drawable-mdpi etc. and put everything in a zip (I can only have 2 expansion files) will I be able to download only what I need? (I'm guessing no...)
So how can I make sure the tablet user will get big image for full screen such as 1920px (worst case scenario) and for mobile phone alot smaller.
What is the best approach for this kind of applications?
Should I just put it on my own server and make my own image management?
I would like to just put it in a bundle and the end user have an app that is as small as possible without loosing quality | 2019/05/07 | [
"https://Stackoverflow.com/questions/56029423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As a note, this only happens when you run the entire code snippit as a single statement (i.e. as a script from the ISE, or copying an pasting the entire code snippit). If, instead, you run each statement line individually from the PowerShell console, you will get the expected results.
As @PetSerAl says, the issue is related to formatting See my answer here for more details: [Running Line by Line Produces Odd Result Compared to Running Lines as a Single Line with Semicolons](https://stackoverflow.com/a/55854591/2150063)
Running:
```
PS C:\> $Data = @()
>> foreach($i in 1..10) {
>> $Data += New-Object PSObject -Property @{
>> Money = 10
>> }
>> }
>>
>> echo "-----Data-----"
>> $Data
>>
>> echo "-----Measure-----"
>> $Data | Measure -Sum -Property "Money"
```
Outputs:
```
-----Data-----
Money
-----
10
10
10
10
10
10
10
10
10
10
-----Measure-----
```
When you chain the commands into one, the **First** object will determine the output format for the entire line. So looking at the types we get:
```
PS C:\> $Data.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\> ($Data | Measure -Sum -Property "Money").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False GenericMeasureInfo Microsoft.PowerShell.Commands.MeasureInfo
```
In this example, the first object `$Data` is of type `Object[]`, and so it will try to format everything else in the `Object[]` format. Since the second command outputs an object of type `GenericMeasureInfo` it cannot be formatted in the same way. Since the two formats are incompatible, the Measure object information is dropped and not outputted.
When you comment out the first `$Data` statement, then the Measure object is the only thing outputted, and yes, you see a properly formatted Measure object.
Now, let's flip it around:
```
PS C:\Temp> $Data = @()
>> foreach($i in 1..10) {
>> $Data += New-Object PSObject -Property @{
>> Money = 10
>> }
>> }
>> echo "-----Measure-----"
>> $Data | Measure -Sum -Property "Money"
>>
>> echo "-----Data-----"
>> $Data
```
Outputs:
```
-----Measure-----
Count : 10
Average :
Sum : 100
Maximum :
Minimum :
Property : Money
-----Data-----
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
```
Well that may seem weird, because the `$Data` object *did* output this time, but it didn't output in a table format. Instead, it followed different formatting rules. The first object is of type `GenericMeasureInfo`, and so it will try to format everything else in the `GenericMeasureInfo` format. Since the second command outputs an object of type `Object[]`, it cannot be formatted in the same way. But in this case, instead of dropping the information, PowerShell figures out that it can fall back to outputting `$Data` formatted as a List (hence you see `"Money : 10"`).
`Out-String` is the other way of doing things:
```
PS C:\> $Data = @()
>> foreach($i in 1..10) {
>> $Data += New-Object PSObject -Property @{
>> Money = 10
>> }
>> }
>>
>> echo "-----Data-----"
>> $Data | Out-String
>>
>> echo "-----Measure-----"
>> $Data | Measure -Sum -Property "Money"
-----Data-----
Money
-----
10
10
10
10
10
10
10
10
10
10
-----Measure-----
Count : 10
Average :
Sum : 100
Maximum :
Minimum :
Property : Money
```
`Out-String` works in this case because it converts the output object type format from `Object[]` to a `String` format, which the Measure object knows how output to. | As @LotPings said, with Out-String code works as expected. |
56,029,423 | I'm working on a android app that will display gemstones. Putting thumbnails in drawable-XXSIZE is not a problem, but how can I continue this with expansion files?
If I create folders such as: drawable-ldpi, drawable-mdpi etc. and put everything in a zip (I can only have 2 expansion files) will I be able to download only what I need? (I'm guessing no...)
So how can I make sure the tablet user will get big image for full screen such as 1920px (worst case scenario) and for mobile phone alot smaller.
What is the best approach for this kind of applications?
Should I just put it on my own server and make my own image management?
I would like to just put it in a bundle and the end user have an app that is as small as possible without loosing quality | 2019/05/07 | [
"https://Stackoverflow.com/questions/56029423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As a note, this only happens when you run the entire code snippit as a single statement (i.e. as a script from the ISE, or copying an pasting the entire code snippit). If, instead, you run each statement line individually from the PowerShell console, you will get the expected results.
As @PetSerAl says, the issue is related to formatting See my answer here for more details: [Running Line by Line Produces Odd Result Compared to Running Lines as a Single Line with Semicolons](https://stackoverflow.com/a/55854591/2150063)
Running:
```
PS C:\> $Data = @()
>> foreach($i in 1..10) {
>> $Data += New-Object PSObject -Property @{
>> Money = 10
>> }
>> }
>>
>> echo "-----Data-----"
>> $Data
>>
>> echo "-----Measure-----"
>> $Data | Measure -Sum -Property "Money"
```
Outputs:
```
-----Data-----
Money
-----
10
10
10
10
10
10
10
10
10
10
-----Measure-----
```
When you chain the commands into one, the **First** object will determine the output format for the entire line. So looking at the types we get:
```
PS C:\> $Data.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\> ($Data | Measure -Sum -Property "Money").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False GenericMeasureInfo Microsoft.PowerShell.Commands.MeasureInfo
```
In this example, the first object `$Data` is of type `Object[]`, and so it will try to format everything else in the `Object[]` format. Since the second command outputs an object of type `GenericMeasureInfo` it cannot be formatted in the same way. Since the two formats are incompatible, the Measure object information is dropped and not outputted.
When you comment out the first `$Data` statement, then the Measure object is the only thing outputted, and yes, you see a properly formatted Measure object.
Now, let's flip it around:
```
PS C:\Temp> $Data = @()
>> foreach($i in 1..10) {
>> $Data += New-Object PSObject -Property @{
>> Money = 10
>> }
>> }
>> echo "-----Measure-----"
>> $Data | Measure -Sum -Property "Money"
>>
>> echo "-----Data-----"
>> $Data
```
Outputs:
```
-----Measure-----
Count : 10
Average :
Sum : 100
Maximum :
Minimum :
Property : Money
-----Data-----
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
Money : 10
```
Well that may seem weird, because the `$Data` object *did* output this time, but it didn't output in a table format. Instead, it followed different formatting rules. The first object is of type `GenericMeasureInfo`, and so it will try to format everything else in the `GenericMeasureInfo` format. Since the second command outputs an object of type `Object[]`, it cannot be formatted in the same way. But in this case, instead of dropping the information, PowerShell figures out that it can fall back to outputting `$Data` formatted as a List (hence you see `"Money : 10"`).
`Out-String` is the other way of doing things:
```
PS C:\> $Data = @()
>> foreach($i in 1..10) {
>> $Data += New-Object PSObject -Property @{
>> Money = 10
>> }
>> }
>>
>> echo "-----Data-----"
>> $Data | Out-String
>>
>> echo "-----Measure-----"
>> $Data | Measure -Sum -Property "Money"
-----Data-----
Money
-----
10
10
10
10
10
10
10
10
10
10
-----Measure-----
Count : 10
Average :
Sum : 100
Maximum :
Minimum :
Property : Money
```
`Out-String` works in this case because it converts the output object type format from `Object[]` to a `String` format, which the Measure object knows how output to. | This is a common gotcha. Format-table is implicitly running, and it doesn't know how to display different sets of columns. Piping the script through format-list works ok. Another weird workaround is to put get-date at the beginning of the script. For some reason, a known object type (that has a format file) at the top makes the output "better". You can also use format-table and format-date for individual commands. |
71,443,066 | after running the query:
```
SELECT title , year FROM movies WHERE title LIKE 'Harry Potter%' ORDER BY year;
```
[sql query output][1]
[1]: https://i.stack.imgur.com/jb0gT.png
but i want to remove title and year headers from the table. How to do that? | 2022/03/11 | [
"https://Stackoverflow.com/questions/71443066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18143801/"
] | I would assume that you're using class components, so the solution I would provide is for that.
First step is to import ConnectedProps:
```
import { connect, ConnectedProps } from 'react-redux'
```
Next step is to define the objects that your state/reducer, so in a file that we can name `TsConnector.ts`, add something like:
```
interface UIState {
a: string,
b: string,
...your other props
}
interface State {
UI: UI,
...your other props
}
```
Then create your `mapState` and `mapDispatch` functions:
```
const mapState = (state: UIState ) => ({
UI: state.UI,
...your other props
})
const mapDispatch = {
... your dispatch action
}
```
And export:
```
export default tsconnector = connect(mapState, mapDispatch)
```
Then use this as you normally would an HOC component:
```
import { tsconnector } from '../components/TsConnector'
export var About =
tsconnector(mapStateToProps, mapDispatchToProps)(About_Class);
```
And that's it. | Have you tried `useDispatch` and `useSelector` in ts file to get redux state
```
import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector
``` |
67,456,334 | I'm new to Flutter and UI development in general and I'm stuck so I need some help!
I'm trying to build a list of video posts in my application with lazy loading / infinite scrolling. The lazy loading part seems to be working fine but the problem I'm having is that every time new videos are loaded, the scroll goes back to the top after the build. Here's my code:
```
class _ProfileState extends State<Profile> {
Future _videoResponseFuture;
ScrollController _scrollController = ScrollController();
UserService _userService = UserService();
List<VideoResponse> _videos = [];
@override
void initState() {
super.initState();
_videoResponseFuture = _getUserVideos();
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
_getMore();
}
});
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
Future<List<VideoResponse>> _getUserVideos() async {
return _userService.getUserVideos();
}
_getMore() {
setState(() {
_videoResponseFuture = _userService.getMoreVideos();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: Scaffold(
body: SafeArea(
child: Padding(
child: Column(
children: <Widget>[
// Other children...
Expanded(
child: FutureBuilder(
future: _videoResponseFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (_videos.length == 0) {
_videos = snapshot.data;
} else {
List<VideoResponse> newVideos = snapshot.data;
newVideos.forEach((element) {
_videos.add(element);
});
}
return Scrollbar(
child: ListView.builder(
shrinkWrap: true,
itemCount: _videos.length,
scrollDirection: Axis.vertical,
controller: _scrollController,
itemBuilder: (BuildContext context, int index) {
return Text(_videos[index].videoDetails.fileName);
},
),
);
}
return CircularProgressIndicator();
},
),
),
],
),
),
),
),
);
}
}
```
I've tried to to get the scroll controller to scroll to the bottom with the following code in the `initState` method but it doesn't work:
`scrollController.jumpTo(scrollController.position.maxScrollExtent);`
I've also tried different scrolling alternatives to using a `ScrollController` but nothing else seemed to work with `ListView`.
Any ideas would be highly appreciated! | 2021/05/09 | [
"https://Stackoverflow.com/questions/67456334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7138472/"
] | you can use property of listview.builder reverse which may help for this question
change reverse=true,
by default reverse is false and check it. | In the `_getMore()` method we could load the videos and then scroll to the bottom.
In order to do so, however, we need to be mindful to not create an infinite-loop. We could do so by the means of a `_loading` state variable:
```
bool _loading = false;
@override
void initState() {
super.initState();
_videoResponseFuture = _getUserVideos();
_scrollController.addListener(() {
if (!_loading &&
_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
_getMore();
}
});
}
_getMore() {
setState(() {
_loading = true;
await _userService.getMoreVideos();
});
await _scrollController.jumpTo(scrollController.position.maxScrollExtent);
setState(() { _loading = false; });
}
``` |
105,803 | I was going to leave my company about 2 months ago, but was offered a promotion to stay. After receiving this promotion I was offered another position at a third company which is even better. Is it unprofessional for me to accept this third position so soon after accepting the promotion at my original company?
How best to accept the new position without burning bridges or seeming to be unprofessional? | 2018/01/29 | [
"https://workplace.stackexchange.com/questions/105803",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/82301/"
] | There Is really no way for your present employer to see this as anything other than a slap in the face. Accept that.
That said, if money were no object, would you move on? If not, then stay. Your present employer has already shown that they care enough to negotiate a promotion to retain you so you KNOW that you are valued. The new company is an unknown.
So, in summation. No, there is no way to move on without burning bridges, so be careful before you make your decision as this time, there will be no going back. | >
> How best to accept the new position without burning bridges or seeming
> to be unprofessional?
>
>
>
The only thing to do if your intent on taking the offer, is to **turn in your notice and leave**. Do it in writing of course, and when there are questions asked, be open and honest about it. Also, be prepared for *the possibility* that you may never be able to go back.
You cannot control how your employer will respond to this, but you can *control your own actions and level of professionalism*.
During your notice period, **be as helpful as you can**. Document whatever you can to make it easier for your employer once you are gone. This will *increase your chances* of going back should you have the need. |
105,803 | I was going to leave my company about 2 months ago, but was offered a promotion to stay. After receiving this promotion I was offered another position at a third company which is even better. Is it unprofessional for me to accept this third position so soon after accepting the promotion at my original company?
How best to accept the new position without burning bridges or seeming to be unprofessional? | 2018/01/29 | [
"https://workplace.stackexchange.com/questions/105803",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/82301/"
] | There Is really no way for your present employer to see this as anything other than a slap in the face. Accept that.
That said, if money were no object, would you move on? If not, then stay. Your present employer has already shown that they care enough to negotiate a promotion to retain you so you KNOW that you are valued. The new company is an unknown.
So, in summation. No, there is no way to move on without burning bridges, so be careful before you make your decision as this time, there will be no going back. | We see over and over people that want to leave, and accept a counter offer, end up leaving anyway. Even in cases where the company doesn't renege on their promises, the employee still feels that there are better positions/offers/companies available.
It is impossible to predict how they will feel. It is likely that your current company knows that their promotion was a stop gap. And you announcing that you are leaving is not unexpected. It is also likely that your announcement will blindside them.
The best you can hope for is to tell them, apologize, and don't accept a counter offer. Then be professional during your remaining time with the company. |
105,803 | I was going to leave my company about 2 months ago, but was offered a promotion to stay. After receiving this promotion I was offered another position at a third company which is even better. Is it unprofessional for me to accept this third position so soon after accepting the promotion at my original company?
How best to accept the new position without burning bridges or seeming to be unprofessional? | 2018/01/29 | [
"https://workplace.stackexchange.com/questions/105803",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/82301/"
] | There Is really no way for your present employer to see this as anything other than a slap in the face. Accept that.
That said, if money were no object, would you move on? If not, then stay. Your present employer has already shown that they care enough to negotiate a promotion to retain you so you KNOW that you are valued. The new company is an unknown.
So, in summation. No, there is no way to move on without burning bridges, so be careful before you make your decision as this time, there will be no going back. | It's best to do what you feel is right. Everyone here is speaking about how you'll burn bridges, but unless your company is brand spanking new, or the HR is brand new, or your manager is brand new, it's highly likely that they know you'll be leaving soon once you put in your original notice and they asked you to come back. Unfortunately, even though they know that, they sort of put the pressure on you because you end up looking bad because they can say, "we tried to reason with him, but couldn't."
Either way I think it's best to go with your guts and if you want to switch jobs, do it now. |
105,803 | I was going to leave my company about 2 months ago, but was offered a promotion to stay. After receiving this promotion I was offered another position at a third company which is even better. Is it unprofessional for me to accept this third position so soon after accepting the promotion at my original company?
How best to accept the new position without burning bridges or seeming to be unprofessional? | 2018/01/29 | [
"https://workplace.stackexchange.com/questions/105803",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/82301/"
] | >
> How best to accept the new position without burning bridges or seeming
> to be unprofessional?
>
>
>
The only thing to do if your intent on taking the offer, is to **turn in your notice and leave**. Do it in writing of course, and when there are questions asked, be open and honest about it. Also, be prepared for *the possibility* that you may never be able to go back.
You cannot control how your employer will respond to this, but you can *control your own actions and level of professionalism*.
During your notice period, **be as helpful as you can**. Document whatever you can to make it easier for your employer once you are gone. This will *increase your chances* of going back should you have the need. | We see over and over people that want to leave, and accept a counter offer, end up leaving anyway. Even in cases where the company doesn't renege on their promises, the employee still feels that there are better positions/offers/companies available.
It is impossible to predict how they will feel. It is likely that your current company knows that their promotion was a stop gap. And you announcing that you are leaving is not unexpected. It is also likely that your announcement will blindside them.
The best you can hope for is to tell them, apologize, and don't accept a counter offer. Then be professional during your remaining time with the company. |
105,803 | I was going to leave my company about 2 months ago, but was offered a promotion to stay. After receiving this promotion I was offered another position at a third company which is even better. Is it unprofessional for me to accept this third position so soon after accepting the promotion at my original company?
How best to accept the new position without burning bridges or seeming to be unprofessional? | 2018/01/29 | [
"https://workplace.stackexchange.com/questions/105803",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/82301/"
] | It's best to do what you feel is right. Everyone here is speaking about how you'll burn bridges, but unless your company is brand spanking new, or the HR is brand new, or your manager is brand new, it's highly likely that they know you'll be leaving soon once you put in your original notice and they asked you to come back. Unfortunately, even though they know that, they sort of put the pressure on you because you end up looking bad because they can say, "we tried to reason with him, but couldn't."
Either way I think it's best to go with your guts and if you want to switch jobs, do it now. | We see over and over people that want to leave, and accept a counter offer, end up leaving anyway. Even in cases where the company doesn't renege on their promises, the employee still feels that there are better positions/offers/companies available.
It is impossible to predict how they will feel. It is likely that your current company knows that their promotion was a stop gap. And you announcing that you are leaving is not unexpected. It is also likely that your announcement will blindside them.
The best you can hope for is to tell them, apologize, and don't accept a counter offer. Then be professional during your remaining time with the company. |
12,992,895 | For a homework assignment, I am not allowed to use any variables like "int i = 0;" -- only pointers.
The problem is that I need to do something n times -- let's say 10 times -- but I can't figure out a way to do this said things n times without a for loop. It is manipulating a pointer to integer, and it is not terminated by zero, but the size is always the same (lets say 10).
Is there a way to do the following operation without using an integer to control the loop?
```
int i;
for (i = 0; i < 10; i++) {
*(p + i) = 0;
}
``` | 2012/10/20 | [
"https://Stackoverflow.com/questions/12992895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1661781/"
] | Maybe like this:
```
int *q = p + 10;
while (p != q) {
*p++ = 0;
}
```
UPDATE:
Doing this you would avoid using integers by just identifying a beginning (p) and an end (p + 10) and then just iterating over them.
It doesn't apply to this particular case but many times you don't know (or need to know) the size of an array. | ```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = (int*)malloc(sizeof(int));
for(*p = 0; *p < 10; (*p)++)
printf("%d\n", (*p));
}
``` |
27,327,426 | My function:
```
Shot *shot_collide(Shot *shot)
{
Shot *moving, *remaining;
remaining=NULL;
moving=shot;
while(moving!=NULL)
{
if(moving->y>658) //ha eléri az alját
{
if(remaining==NULL) //ha ez az első elem
{
shot=moving->next;
free(moving);
moving=shot->next;
}else{
remaining->next=moving->next;
free(moving);
moving=remaining->next;
}
}else{
moving=moving->next;
}
}
return shot;
}
```
When I call free, i get this error in Xcode:
>
> NHF(1670,0x7fff77e1a300) malloc: **\* error for object 0x10050c9e0: pointer being freed was >not allocated
> \*** set a breakpoint in malloc\_error\_break to debug
>
>
>
This is an SDL game, and this function is free the shot after it reaches the end of the map.
I gotta finish this to Sunday, but I'm stuck :( | 2014/12/06 | [
"https://Stackoverflow.com/questions/27327426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330853/"
] | I think the problem is `new Array(data)`, if data is of string type then it creates an array with one element which is the string, else if data is an array then the `tArrx` will be an array with 1 element which is the array so your `$.inArray()` will always return `-1`.
```
$.ajax({
type: 'POST',
url: 'loc/bcheck.php',
//set datatype as json
dataType: 'json',
success: function (data) {
var tArrx = data;
$('.bHr').each(function () {
var curElm = $(this);
//wrong variable name& you might have to trim the html contents
var bTm = curElm.html().trim();
if ($.inArray(bTm, tArrx) !== -1) {
curElm.addClass('disabled');
curElm.removeClass('available');
} else {
curElm.addClass('available');
curElm.removeClass('disabled');
}
});
}
});
``` | It seems to me that you have to cast the variables:
```
if ($.inArray(bTm.toString(), tArrx) !== -1)
``` |
27,327,426 | My function:
```
Shot *shot_collide(Shot *shot)
{
Shot *moving, *remaining;
remaining=NULL;
moving=shot;
while(moving!=NULL)
{
if(moving->y>658) //ha eléri az alját
{
if(remaining==NULL) //ha ez az első elem
{
shot=moving->next;
free(moving);
moving=shot->next;
}else{
remaining->next=moving->next;
free(moving);
moving=remaining->next;
}
}else{
moving=moving->next;
}
}
return shot;
}
```
When I call free, i get this error in Xcode:
>
> NHF(1670,0x7fff77e1a300) malloc: **\* error for object 0x10050c9e0: pointer being freed was >not allocated
> \*** set a breakpoint in malloc\_error\_break to debug
>
>
>
This is an SDL game, and this function is free the shot after it reaches the end of the map.
I gotta finish this to Sunday, but I'm stuck :( | 2014/12/06 | [
"https://Stackoverflow.com/questions/27327426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330853/"
] | You have actually created a multidimensional array
```
tArrx = new Array(data);
```
So this is how you would match your array
```
var data = ["1","2","3","4"];
var tArrx = new Array(data);
confirm(tArrx[0]);
confirm(data);
confirm($.inArray('1', tArrx[0]) !== -1);
```
Better yet simply don't cast data to an array
```
var data = ["1","2","3","4"];
confirm(data);
confirm($.inArray('1', data) !== -1);
```
[Working example HERE](http://jsfiddle.net/threadid/rpa1u7dd/)
I modified the example to replicate your conditions as closely as possible.
```
var data = '1","2","3","4';
var tArrx = new Array(data);
console.log('data '+data);
console.log('data.length '+data.length);
console.log('data[0] '+data[0]);
console.log('data[1] '+data[1]);
console.log('data[2] '+data[2]);
console.log('data[3] '+data[3]);
console.log(tArrx.length);
console.log(tArrx[0].length);
console.log(tArrx);
console.log(tArrx[0]);
$('.bHr').each(function(){
curElm = $(this);
var bTm = curElm.html();
console.log(typeof bTm);
console.log($.inArray(bTm, tArrx) !== -1);
console.log($.inArray(bTm, tArrx[0]) !== -1);
console.log($.inArray(bTm, data) !== -1);
});
```
Not having the beginning and ending quotes returned from your PHP request is causing the array assignment to return an array of length 1 populated with a string of length 13. This will cause `jQuery.inArray()` method to not find a match between 1 and the 13 char string. It can find 1 if you pass the string. Fixing the missing beginning and ending qoutes is going to be your best solution. Look at the console log from the updated working example.
```
data 1","2","3","4
data.length 13
data[0] 1
data[1] "
data[2] ,
data[3] "
1
13
["1","2","3","4"]
1","2","3","4
string
false
true
true
string
false
false
false
``` | It seems to me that you have to cast the variables:
```
if ($.inArray(bTm.toString(), tArrx) !== -1)
``` |
27,327,426 | My function:
```
Shot *shot_collide(Shot *shot)
{
Shot *moving, *remaining;
remaining=NULL;
moving=shot;
while(moving!=NULL)
{
if(moving->y>658) //ha eléri az alját
{
if(remaining==NULL) //ha ez az első elem
{
shot=moving->next;
free(moving);
moving=shot->next;
}else{
remaining->next=moving->next;
free(moving);
moving=remaining->next;
}
}else{
moving=moving->next;
}
}
return shot;
}
```
When I call free, i get this error in Xcode:
>
> NHF(1670,0x7fff77e1a300) malloc: **\* error for object 0x10050c9e0: pointer being freed was >not allocated
> \*** set a breakpoint in malloc\_error\_break to debug
>
>
>
This is an SDL game, and this function is free the shot after it reaches the end of the map.
I gotta finish this to Sunday, but I'm stuck :( | 2014/12/06 | [
"https://Stackoverflow.com/questions/27327426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330853/"
] | So, I figured it out. The problem was that the PHP response was not an PHP array. To fix this I made my response an array and added this to my PHP file:
```
json_encode($tArrx);
```
And changed my jQuery as follows:
```
$.ajax({
type: 'POST',
url: 'loc/bcheck.php',
dataType: 'json',
success: function (data) {
tArrx = data;
},
complete: function(){
$('.bHr').each(function(){
curElm = $(this);
var bTm = curElm.html();
if ($.inArray(bTm, tArrx) !== -1){
curElm.addClass('disabled');
curElm.removeClass('available');
}
else{
curElm.addClass('available');
curElm.removeClass('disabled');
}
});
}
});
```
I used the examples from all of you guys to achieve this and I thank you for it. Couldn't have done it without your help! | It seems to me that you have to cast the variables:
```
if ($.inArray(bTm.toString(), tArrx) !== -1)
``` |
27,327,426 | My function:
```
Shot *shot_collide(Shot *shot)
{
Shot *moving, *remaining;
remaining=NULL;
moving=shot;
while(moving!=NULL)
{
if(moving->y>658) //ha eléri az alját
{
if(remaining==NULL) //ha ez az első elem
{
shot=moving->next;
free(moving);
moving=shot->next;
}else{
remaining->next=moving->next;
free(moving);
moving=remaining->next;
}
}else{
moving=moving->next;
}
}
return shot;
}
```
When I call free, i get this error in Xcode:
>
> NHF(1670,0x7fff77e1a300) malloc: **\* error for object 0x10050c9e0: pointer being freed was >not allocated
> \*** set a breakpoint in malloc\_error\_break to debug
>
>
>
This is an SDL game, and this function is free the shot after it reaches the end of the map.
I gotta finish this to Sunday, but I'm stuck :( | 2014/12/06 | [
"https://Stackoverflow.com/questions/27327426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330853/"
] | I think the problem is `new Array(data)`, if data is of string type then it creates an array with one element which is the string, else if data is an array then the `tArrx` will be an array with 1 element which is the array so your `$.inArray()` will always return `-1`.
```
$.ajax({
type: 'POST',
url: 'loc/bcheck.php',
//set datatype as json
dataType: 'json',
success: function (data) {
var tArrx = data;
$('.bHr').each(function () {
var curElm = $(this);
//wrong variable name& you might have to trim the html contents
var bTm = curElm.html().trim();
if ($.inArray(bTm, tArrx) !== -1) {
curElm.addClass('disabled');
curElm.removeClass('available');
} else {
curElm.addClass('available');
curElm.removeClass('disabled');
}
});
}
});
``` | Do you have a typo in this line:
```
if ($.inArray(bTm, tArrx) !== -1){
```
shouldn't it be:
```
if ($.inArray(Tbm, tArrx) !== -1){
``` |
27,327,426 | My function:
```
Shot *shot_collide(Shot *shot)
{
Shot *moving, *remaining;
remaining=NULL;
moving=shot;
while(moving!=NULL)
{
if(moving->y>658) //ha eléri az alját
{
if(remaining==NULL) //ha ez az első elem
{
shot=moving->next;
free(moving);
moving=shot->next;
}else{
remaining->next=moving->next;
free(moving);
moving=remaining->next;
}
}else{
moving=moving->next;
}
}
return shot;
}
```
When I call free, i get this error in Xcode:
>
> NHF(1670,0x7fff77e1a300) malloc: **\* error for object 0x10050c9e0: pointer being freed was >not allocated
> \*** set a breakpoint in malloc\_error\_break to debug
>
>
>
This is an SDL game, and this function is free the shot after it reaches the end of the map.
I gotta finish this to Sunday, but I'm stuck :( | 2014/12/06 | [
"https://Stackoverflow.com/questions/27327426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330853/"
] | You have actually created a multidimensional array
```
tArrx = new Array(data);
```
So this is how you would match your array
```
var data = ["1","2","3","4"];
var tArrx = new Array(data);
confirm(tArrx[0]);
confirm(data);
confirm($.inArray('1', tArrx[0]) !== -1);
```
Better yet simply don't cast data to an array
```
var data = ["1","2","3","4"];
confirm(data);
confirm($.inArray('1', data) !== -1);
```
[Working example HERE](http://jsfiddle.net/threadid/rpa1u7dd/)
I modified the example to replicate your conditions as closely as possible.
```
var data = '1","2","3","4';
var tArrx = new Array(data);
console.log('data '+data);
console.log('data.length '+data.length);
console.log('data[0] '+data[0]);
console.log('data[1] '+data[1]);
console.log('data[2] '+data[2]);
console.log('data[3] '+data[3]);
console.log(tArrx.length);
console.log(tArrx[0].length);
console.log(tArrx);
console.log(tArrx[0]);
$('.bHr').each(function(){
curElm = $(this);
var bTm = curElm.html();
console.log(typeof bTm);
console.log($.inArray(bTm, tArrx) !== -1);
console.log($.inArray(bTm, tArrx[0]) !== -1);
console.log($.inArray(bTm, data) !== -1);
});
```
Not having the beginning and ending quotes returned from your PHP request is causing the array assignment to return an array of length 1 populated with a string of length 13. This will cause `jQuery.inArray()` method to not find a match between 1 and the 13 char string. It can find 1 if you pass the string. Fixing the missing beginning and ending qoutes is going to be your best solution. Look at the console log from the updated working example.
```
data 1","2","3","4
data.length 13
data[0] 1
data[1] "
data[2] ,
data[3] "
1
13
["1","2","3","4"]
1","2","3","4
string
false
true
true
string
false
false
false
``` | Do you have a typo in this line:
```
if ($.inArray(bTm, tArrx) !== -1){
```
shouldn't it be:
```
if ($.inArray(Tbm, tArrx) !== -1){
``` |
27,327,426 | My function:
```
Shot *shot_collide(Shot *shot)
{
Shot *moving, *remaining;
remaining=NULL;
moving=shot;
while(moving!=NULL)
{
if(moving->y>658) //ha eléri az alját
{
if(remaining==NULL) //ha ez az első elem
{
shot=moving->next;
free(moving);
moving=shot->next;
}else{
remaining->next=moving->next;
free(moving);
moving=remaining->next;
}
}else{
moving=moving->next;
}
}
return shot;
}
```
When I call free, i get this error in Xcode:
>
> NHF(1670,0x7fff77e1a300) malloc: **\* error for object 0x10050c9e0: pointer being freed was >not allocated
> \*** set a breakpoint in malloc\_error\_break to debug
>
>
>
This is an SDL game, and this function is free the shot after it reaches the end of the map.
I gotta finish this to Sunday, but I'm stuck :( | 2014/12/06 | [
"https://Stackoverflow.com/questions/27327426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330853/"
] | So, I figured it out. The problem was that the PHP response was not an PHP array. To fix this I made my response an array and added this to my PHP file:
```
json_encode($tArrx);
```
And changed my jQuery as follows:
```
$.ajax({
type: 'POST',
url: 'loc/bcheck.php',
dataType: 'json',
success: function (data) {
tArrx = data;
},
complete: function(){
$('.bHr').each(function(){
curElm = $(this);
var bTm = curElm.html();
if ($.inArray(bTm, tArrx) !== -1){
curElm.addClass('disabled');
curElm.removeClass('available');
}
else{
curElm.addClass('available');
curElm.removeClass('disabled');
}
});
}
});
```
I used the examples from all of you guys to achieve this and I thank you for it. Couldn't have done it without your help! | Do you have a typo in this line:
```
if ($.inArray(bTm, tArrx) !== -1){
```
shouldn't it be:
```
if ($.inArray(Tbm, tArrx) !== -1){
``` |
332,121 | I was reviewing few posts and noticed that after reviewing a particular post I get this error
>
> Our system has identified this post as possible spam; please review carefully
>
>
>
I immediately reverted back to check what was the 'probable' spam link. **When I looked back, there wasn't any link at all**. I'm not sure why I got this notification.
Am I missing something while reviewing ?
[Question I reviewed](https://stackoverflow.com/questions/38879736/visual-studio-how-to-chain-build-of-projects-with-different-bitness) - [screenshot](https://stackoverflow.com/questions/38879736/visual-studio-how-to-chain-build-of-projects-with-different-bitness)
[Next question where I got the error](https://stackoverflow.com/questions/38880562/barcode-scanner-red-light-not-showing-in-android-studio) - [screenshot](https://stackoverflow.com/questions/38880562/barcode-scanner-red-light-not-showing-in-android-studio)
**Screenshots** -
[](https://i.stack.imgur.com/0iHH8.png)
[](https://i.stack.imgur.com/g0Lgp.png) | 2016/08/10 | [
"https://meta.stackoverflow.com/questions/332121",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/4046274/"
] | Posts don't have to contain links in order to be spam. They can also contain phone numbers and emails, or just plain information about a product hoping you'll be interested enough to look it up. Sometimes the algorithms that attempt to detect these things pick up false positives. That's why the message says *possible* spam. | This happens when somebody has flagged the post as spam.
Then the system knows that there's a reasonable chance that it is spam, and warns subsequent reviewers. |
332,121 | I was reviewing few posts and noticed that after reviewing a particular post I get this error
>
> Our system has identified this post as possible spam; please review carefully
>
>
>
I immediately reverted back to check what was the 'probable' spam link. **When I looked back, there wasn't any link at all**. I'm not sure why I got this notification.
Am I missing something while reviewing ?
[Question I reviewed](https://stackoverflow.com/questions/38879736/visual-studio-how-to-chain-build-of-projects-with-different-bitness) - [screenshot](https://stackoverflow.com/questions/38879736/visual-studio-how-to-chain-build-of-projects-with-different-bitness)
[Next question where I got the error](https://stackoverflow.com/questions/38880562/barcode-scanner-red-light-not-showing-in-android-studio) - [screenshot](https://stackoverflow.com/questions/38880562/barcode-scanner-red-light-not-showing-in-android-studio)
**Screenshots** -
[](https://i.stack.imgur.com/0iHH8.png)
[](https://i.stack.imgur.com/g0Lgp.png) | 2016/08/10 | [
"https://meta.stackoverflow.com/questions/332121",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/4046274/"
] | A post doesn't need to have a link in it for it to be spam. I.e:
Call 863-555-9385 to get **SUPER CHEAP** programming books. | This happens when somebody has flagged the post as spam.
Then the system knows that there's a reasonable chance that it is spam, and warns subsequent reviewers. |
332,121 | I was reviewing few posts and noticed that after reviewing a particular post I get this error
>
> Our system has identified this post as possible spam; please review carefully
>
>
>
I immediately reverted back to check what was the 'probable' spam link. **When I looked back, there wasn't any link at all**. I'm not sure why I got this notification.
Am I missing something while reviewing ?
[Question I reviewed](https://stackoverflow.com/questions/38879736/visual-studio-how-to-chain-build-of-projects-with-different-bitness) - [screenshot](https://stackoverflow.com/questions/38879736/visual-studio-how-to-chain-build-of-projects-with-different-bitness)
[Next question where I got the error](https://stackoverflow.com/questions/38880562/barcode-scanner-red-light-not-showing-in-android-studio) - [screenshot](https://stackoverflow.com/questions/38880562/barcode-scanner-red-light-not-showing-in-android-studio)
**Screenshots** -
[](https://i.stack.imgur.com/0iHH8.png)
[](https://i.stack.imgur.com/g0Lgp.png) | 2016/08/10 | [
"https://meta.stackoverflow.com/questions/332121",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/4046274/"
] | Posts don't have to contain links in order to be spam. They can also contain phone numbers and emails, or just plain information about a product hoping you'll be interested enough to look it up. Sometimes the algorithms that attempt to detect these things pick up false positives. That's why the message says *possible* spam. | A post doesn't need to have a link in it for it to be spam. I.e:
Call 863-555-9385 to get **SUPER CHEAP** programming books. |
995,691 | I am trying to install the `kernel-devel` package matching the running kernel version.
My guess was:
```
package { 'kernel-devel':
ensure => "${facts['kernelrelease']}",
}
```
but it doesn't work if more than one `kernel-devel` package are already installed. This is the error I get:
`Error: Could not update: Failed to update to version 3.10.0-957.21.3.el7.x86_64, got version 3.10.0-957.21.3.el7; 3.10.0-1062.4.3.el7; 3.10.0-1062.9.1.el7 instead`
So the package is already installed, but the Package class raises an error because (apparently) it performs a string comparison instead of looking in the versions list.
What is the proper way to handle this? | 2019/12/16 | [
"https://serverfault.com/questions/995691",
"https://serverfault.com",
"https://serverfault.com/users/288777/"
] | Unless I am misunderstanding, you can solve this with the version in the resource title.
```
package { "kernel-devel-${facts['kernelrelease']}":
ensure => present,
}
```
Or, if you have other resources which depend on 'kernel-devel' you can use the name attribute.
```
package { 'kernel-devel':
name => "kernel-devel-${facts['kernelrelease']}",
ensure => present,
}
```
---
```
[root@aaron ~]# dnf list installed kernel-devel
Installed Packages
kernel-devel.x86_64 5.3.11-200.fc30 @updates
kernel-devel.x86_64 5.3.14-200.fc30 @updates
[root@aaron ~]# uname -a
Linux aaron 5.3.15-200.fc30.x86_64 #1 SMP Thu Dec 5 15:18:00 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
[root@aaron ~]# puppet apply kernel-devel.pp
Notice: Compiled catalog for aaron.tsp in environment production in 0.54 seconds
Notice: /Stage[main]/Main/Package[kernel-devel-5.3.15-200.fc30.x86_64]/ensure: created
Notice: Applied catalog in 62.18 seconds
[root@aaron ~]# dnf list installed kernel-devel
Installed Packages
kernel-devel.x86_64 5.3.11-200.fc30 @updates
kernel-devel.x86_64 5.3.14-200.fc30 @updates
kernel-devel.x86_64 5.3.15-200.fc30 @updates
``` | I've recently run into the same thing. I'm not sure there is a nice way to handle this, from bug tickets I've found apparently Puppet don't really want to acknowledge that there could be multiple versions of a package installed as it breaks their resource model.
I think the only thing you can do is fall back to using an `exec`, something like
```
exec { "yum install kernel-devel-${facts['kernelrelease']}":
path => $facts['path'],
unless => "rpm -qa kernel-devel | grep -q ${facts['kernelrelease']}",
}
``` |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | It has a very large impact, you can run this quick test to see for yourself:
```
from datetime import datetime as dt
now = dt.now
l = []
#create list
for i in range(20000):
l.append(i)
#mark time
print(str(now().time()))
#save min first
min_val = min(l)
new = [x - min_val for x in l]
#mark time
print(str(now().time()))
#do min() each time
[x - min(l) for x in l]
#mark time
print(str(now().time()))
```
Output:
```
15:17:38.392065
15:17:38.393058
15:17:40.592543
```
The first ran instantly and the second took over two seconds and that is only for 20,000 items.
So practically a large difference even though it would be expected due to the change in time complexity. (O(n) to O(n^2)) | ```
import time
from functools import lru_cache
l = [i for i in range(10000)]
min_val = min(l)
def f1():
min_l = [x - min(l) for x in l]
def f2():
min_l = [x - min_val for x in l]
@lru_cache
def lru_min(x):
return min(x)
if __name__ == '__main__':
start_time = time.time()
f1()
print("--- f1 runs in %s seconds ---" % (time.time() - start_time))
start_time = time.time()
f2()
print("--- f2 runs in %s seconds ---" % (time.time() - start_time))
```
This code results in
```
--- f1 runs in 0.7290558815002441 seconds ---
--- f2 runs in 0.0003840923309326172 seconds ---
``` |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | I prefer the timeit calls from the commandline in this case as this problem isn't too complicated:
```
$ python -m timeit --setup "x = [i for i in range(1000)]" "[i - min(x) for i in x]"
50 loops, best of 5: 8.07 msec per loop
$ python -m timeit --setup "x = [i for i in range(1000)]" "y = min(x);[i - y for i in x]"
10000 loops, best of 5: 36.8 usec per loop
```
Where you can see very clearly that there is a tremendous benefit to storing the minimum value before the list comprehension. | It has a very large impact, you can run this quick test to see for yourself:
```
from datetime import datetime as dt
now = dt.now
l = []
#create list
for i in range(20000):
l.append(i)
#mark time
print(str(now().time()))
#save min first
min_val = min(l)
new = [x - min_val for x in l]
#mark time
print(str(now().time()))
#do min() each time
[x - min(l) for x in l]
#mark time
print(str(now().time()))
```
Output:
```
15:17:38.392065
15:17:38.393058
15:17:40.592543
```
The first ran instantly and the second took over two seconds and that is only for 20,000 items.
So practically a large difference even though it would be expected due to the change in time complexity. (O(n) to O(n^2)) |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | Yes, `min(l)` will be called for every iteration in the list comprehension. You can test this using your own function, as @jarmod has mentioned.
Yes, this will add complexity compared to storing it in a variable, because [`min(l)` is `O(n)`](https://stackoverflow.com/questions/35386546/big-o-of-min-and-max-in-python). That makes your code with the method call inside comprehension `O(n^2)` vs just `O(n)` if you store it in a variable beforehand.
And yes, the other example (list comprehension vs append) is equivalent, as [shown in the docs](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). | ```
import time
from functools import lru_cache
l = [i for i in range(10000)]
min_val = min(l)
def f1():
min_l = [x - min(l) for x in l]
def f2():
min_l = [x - min_val for x in l]
@lru_cache
def lru_min(x):
return min(x)
if __name__ == '__main__':
start_time = time.time()
f1()
print("--- f1 runs in %s seconds ---" % (time.time() - start_time))
start_time = time.time()
f2()
print("--- f2 runs in %s seconds ---" % (time.time() - start_time))
```
This code results in
```
--- f1 runs in 0.7290558815002441 seconds ---
--- f2 runs in 0.0003840923309326172 seconds ---
``` |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | I prefer the timeit calls from the commandline in this case as this problem isn't too complicated:
```
$ python -m timeit --setup "x = [i for i in range(1000)]" "[i - min(x) for i in x]"
50 loops, best of 5: 8.07 msec per loop
$ python -m timeit --setup "x = [i for i in range(1000)]" "y = min(x);[i - y for i in x]"
10000 loops, best of 5: 36.8 usec per loop
```
Where you can see very clearly that there is a tremendous benefit to storing the minimum value before the list comprehension. | Yes, `min(l)` will be called for every iteration in the list comprehension. You can test this using your own function, as @jarmod has mentioned.
Yes, this will add complexity compared to storing it in a variable, because [`min(l)` is `O(n)`](https://stackoverflow.com/questions/35386546/big-o-of-min-and-max-in-python). That makes your code with the method call inside comprehension `O(n^2)` vs just `O(n)` if you store it in a variable beforehand.
And yes, the other example (list comprehension vs append) is equivalent, as [shown in the docs](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | There is this really cool module called timeit ... with wich you can ... timeit. Don't ask, measure:
```
import timeit
def a():
l = list(range(100))[::-1]
return [x - min(l) for x in l]
def b():
l = list(range(100))[::-1]
min_val = min(l)
return [x - min_val for x in l]
# do 100 calls to the given function, average results to avoid
# caching mishaps
print("min inside list comp: ", timeit.timeit(a, number=100))
print("min outside list comp:", timeit.timeit(b, number=100))
```
Output:
```
min inside list comp: 0.008259299998826464
min outside list comp: 0.0010576999993645586
```
See [How to use timeit module](https://stackoverflow.com/questions/8220801/how-to-use-timeit-module) | ```
import time
from functools import lru_cache
l = [i for i in range(10000)]
min_val = min(l)
def f1():
min_l = [x - min(l) for x in l]
def f2():
min_l = [x - min_val for x in l]
@lru_cache
def lru_min(x):
return min(x)
if __name__ == '__main__':
start_time = time.time()
f1()
print("--- f1 runs in %s seconds ---" % (time.time() - start_time))
start_time = time.time()
f2()
print("--- f2 runs in %s seconds ---" % (time.time() - start_time))
```
This code results in
```
--- f1 runs in 0.7290558815002441 seconds ---
--- f2 runs in 0.0003840923309326172 seconds ---
``` |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | I prefer the timeit calls from the commandline in this case as this problem isn't too complicated:
```
$ python -m timeit --setup "x = [i for i in range(1000)]" "[i - min(x) for i in x]"
50 loops, best of 5: 8.07 msec per loop
$ python -m timeit --setup "x = [i for i in range(1000)]" "y = min(x);[i - y for i in x]"
10000 loops, best of 5: 36.8 usec per loop
```
Where you can see very clearly that there is a tremendous benefit to storing the minimum value before the list comprehension. | There is this really cool module called timeit ... with wich you can ... timeit. Don't ask, measure:
```
import timeit
def a():
l = list(range(100))[::-1]
return [x - min(l) for x in l]
def b():
l = list(range(100))[::-1]
min_val = min(l)
return [x - min_val for x in l]
# do 100 calls to the given function, average results to avoid
# caching mishaps
print("min inside list comp: ", timeit.timeit(a, number=100))
print("min outside list comp:", timeit.timeit(b, number=100))
```
Output:
```
min inside list comp: 0.008259299998826464
min outside list comp: 0.0010576999993645586
```
See [How to use timeit module](https://stackoverflow.com/questions/8220801/how-to-use-timeit-module) |
70,947,518 | I often run into this situation while coding in Python, and am not sure which is more performant. Suppose I have a list `l = [3, 13, 6, 8, 9, 53]`, and I want to use a list comprehension to create a new list that subtracts off the minimum value so that the lowest number is zero. I could do:
```py
[x - min(l) for x in l]
```
On the other hand, I could do:
```py
min_val = min(l)
[x - min_val for x in l]
```
Is it true that the first option causes `min(l)` to run for every new item in the list, while the second option only calculates the minimum value once? Potentially, if `l` is a very long list, this could be a significant performance difference? On the other hand, perhaps with a shorter list, the creation of a variable in option 2 results in some overhead?
I guess my question is: how much of a difference does this make? I find the first option cleaner and more compact, but don't know if that comes at a performance cost.
Relatedly, is there any performance difference between:
```py
new_list = []
for x in l:
new_list.append(x ** 2)
```
and:
```py
new_list = [x ** 2 for x in l]
```
Does the latter directly translate into the former, or is there a difference in what goes on under the hood? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70947518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2392192/"
] | I prefer the timeit calls from the commandline in this case as this problem isn't too complicated:
```
$ python -m timeit --setup "x = [i for i in range(1000)]" "[i - min(x) for i in x]"
50 loops, best of 5: 8.07 msec per loop
$ python -m timeit --setup "x = [i for i in range(1000)]" "y = min(x);[i - y for i in x]"
10000 loops, best of 5: 36.8 usec per loop
```
Where you can see very clearly that there is a tremendous benefit to storing the minimum value before the list comprehension. | ```
import time
from functools import lru_cache
l = [i for i in range(10000)]
min_val = min(l)
def f1():
min_l = [x - min(l) for x in l]
def f2():
min_l = [x - min_val for x in l]
@lru_cache
def lru_min(x):
return min(x)
if __name__ == '__main__':
start_time = time.time()
f1()
print("--- f1 runs in %s seconds ---" % (time.time() - start_time))
start_time = time.time()
f2()
print("--- f2 runs in %s seconds ---" % (time.time() - start_time))
```
This code results in
```
--- f1 runs in 0.7290558815002441 seconds ---
--- f2 runs in 0.0003840923309326172 seconds ---
``` |
9,433,667 | Short question: Can anyone tell me what the requirements (especially when it comes to SQL components) are for the web server used as web sync for merge replication?
Background:
I have a solution which uses merge replication to do one-way data sync with the client application of the solution.
The server uses SQL Server 2008, the client SQL Server 2008 Express and initiates the pull subscription using RMO. The request goes through Web Sync. All is fine when the IIS and the DB is on the same server - the problem occurs when the IIS is on a standalone web server.
From the error logs, it seems certain SQL components are required on the web server to make this work - but I haven't been able to find which ones. I've tried installing SQL Server 2008 Express on this server, with no luck.
So: Can anyone tell me what the requirements (especially when it comes to SQL components) are for the web server used as web sync for merge replication?
**EDIT:**
I've tried to install the native client, but no luck. Perhaps I'm interpreting the log wrong? Here it is:
>
> CReplicationListenerWorker , 2012/02/27 09:55:24.901, 1060, 174,
> S2, INFO: =============== START PROCESSING REQUEST ==============
> CReplicationListenerWorker , 2012/02/27 09:55:24.901, 1060, 212,
> S1, ERROR: CoCreateInstance failed for CLSID\_SQLReplErrors, hr =
> 0x00000000. CReplicationListenerWorker , 2012/02/27 09:55:24.901,
> 1060, 298, S2, INFO: Processed request type:
> MESSAGE\_TYPE\_UploadEmpty. CReplicationListenerWorker , 2012/02/27
> 09:55:24.901, 1060, 396, S2, INFO: =============== DONE PROCESSING
> REQUEST =============== CReplicationListenerWorker , 2012/02/27
> 09:55:24.964, 1060, 174, S2, INFO: =============== START PROCESSING
> REQUEST ============== CReplicationListenerWorker , 2012/02/27
> 09:55:24.964, 1060, 212, S1, ERROR: CoCreateInstance failed for
> CLSID\_SQLReplErrors, hr = 0x00000000. CReplicationListenerWorker ,
> 2012/02/27 09:55:24.964, 1060, 298, S2, INFO: Processed request
> type: MESSAGE\_TYPE\_UploadEmpty. CReplicationListenerWorker ,
> 2012/02/27 09:55:24.964, 1060, 396, S2, INFO: =============== DONE
> PROCESSING REQUEST =============== CReplicationListenerWorker ,
> 2012/02/27 09:55:24.964, 1060, 174, S2, INFO: =============== START
> PROCESSING REQUEST ============== CReplicationListenerWorker ,
> 2012/02/27 09:55:24.964, 1060, 212, S1, ERROR: CoCreateInstance
> failed for CLSID\_SQLReplErrors, hr = 0x00000000. CHttpListener
>
> , 2012/02/27 09:55:24.964, 1060, 258, S2, INFO: Exchange ID =
> EF7753FB-F315-4FE3-8E8D-E77CCD366825. CReplicationListenerWorker ,
> 2012/02/27 09:55:24.964, 1060, 298, S2, INFO: Processed request
> type: MESSAGE\_TYPE\_SyncContentsUpload. ReconcilerHost ,
> 2012/02/27 09:55:24.964, 1060, 160, S1, ERROR: CoCreateInstance
> failed for CLSID\_CDatabaseReconciler, hr = 0x80040154. ReconcilerHost
> , 2012/02/27 09:55:24.964, 1060, 191, S1, ERROR:
> ReconcilerHost::Initialize failed, hr = 0x80040154.
> CReplicationListenerWorker , 2012/02/27 09:55:24.964, 1060, 315,
> S1, ERROR: Failure initializing ReconcilerHost, hr = 0x80040154.
> CReplicationListenerWorker , 2012/02/27 09:55:24.964, 1060, 396,
> S2, INFO: =============== DONE PROCESSING REQUEST ===============
>
>
> | 2012/02/24 | [
"https://Stackoverflow.com/questions/9433667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391658/"
] | According to [How to: Configure IIS for Web Synchronization](http://msdn.microsoft.com/en-us/library/ms152511%28v=sql.105%29.aspx), Microsoft SQL Server Connectivity Components and SQL Server Management Studio will need to be installed on the computer that is running IIS by using the SQL Server Installation Wizard. | You will need SQL Server Native Client (SNAC). But as far as I'm aware, you won't need anything else on the IIS server. |
26,642,433 | I'm a bit confused with the counting of a string that I would enter manually. I am basically trying to count the number of words and the number of characters without spaces. Also if it would be possible, who can help with counting the vowels?
This is all I have so far:
```
vowels = [ 'a','e','i','o','u','A','E','I','O','U']
constants= ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
s= input ('Enter a Sentence: ')
print ('Your sentence is:', s)
print ('Number of Characters', len(s));
print ('Number of Vowels', s);
``` | 2014/10/29 | [
"https://Stackoverflow.com/questions/26642433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196251/"
] | ```
s = input("Enter a sentence: ")
word_count = len(s.split()) # count the words with split
char_count = len(s.replace(' ', '')) # count the chars having replaced spaces with ''
vowel_count = sum(1 for c in s if c.lower() in ['a','e','i','o','u']) # sum 1 for each vowel
```
**more info:**
on `str.split`: <http://www.tutorialspoint.com/python/string_split.htm>
on `sum`:
```
sum(sequence[, start]) -> value
Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, return start.
```
on `str.replace`: <http://www.tutorialspoint.com/python/string_replace.htm> | ```
vowels = [ 'a','e','i','o','u']
sentence = "Our World is a better place"
count_vow = 0
count_con = 0
for x in sentence:
if x.isalpha():
if x.lower() in vowels:
count_vow += 1
else:
count_con += 1
print count_vow,count_con
``` |
26,642,433 | I'm a bit confused with the counting of a string that I would enter manually. I am basically trying to count the number of words and the number of characters without spaces. Also if it would be possible, who can help with counting the vowels?
This is all I have so far:
```
vowels = [ 'a','e','i','o','u','A','E','I','O','U']
constants= ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
s= input ('Enter a Sentence: ')
print ('Your sentence is:', s)
print ('Number of Characters', len(s));
print ('Number of Vowels', s);
``` | 2014/10/29 | [
"https://Stackoverflow.com/questions/26642433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196251/"
] | ```
s = input("Enter a sentence: ")
word_count = len(s.split()) # count the words with split
char_count = len(s.replace(' ', '')) # count the chars having replaced spaces with ''
vowel_count = sum(1 for c in s if c.lower() in ['a','e','i','o','u']) # sum 1 for each vowel
```
**more info:**
on `str.split`: <http://www.tutorialspoint.com/python/string_split.htm>
on `sum`:
```
sum(sequence[, start]) -> value
Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, return start.
```
on `str.replace`: <http://www.tutorialspoint.com/python/string_replace.htm> | For vowels:
Basic way of doing this is using a for loop and checking each character if they exist in a string, list or other sequence (vowels in this case). I think this is the way you should first learn to do it since it's easiest for beginner to understand.
```
def how_many_vowels(text):
vowels = 'aeiou'
vowel_count = 0
for char in text:
if char.lower() in vowels:
vowel_count += 1
return vowel_count
```
Once you learn more and figure out [list comprehensions](https://docs.python.org/2/tutorial/datastructures.html), you could do it
```
def how_many_vowels(text):
vowels = 'aeiou'
vowels_in_text = [ch for ch in text if ch.lower() in vowels]
return len(vowels_in_text)
```
or as @totem wrote, using sum
```
def how_many_vowels(text):
vowels = 'aeiou'
vowel_count = sum(1 for ch in text if ch.lower() in vowels)
return vowel_count
``` |
62,270 | Suggestions for other ways to describe such a person would also be appreciated | 2022/06/01 | [
"https://writers.stackexchange.com/questions/62270",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/52787/"
] | No, this description wouldn’t be appropriate. As Kate Gregory points out in a comment, ‘the apple of my eye’ is often used by doting parents/older relatives about children, and doesn’t work in a romantic sense.
You don’t give much context so it’s difficult to suggest a useful alternative. Any one line is going to depend on host of things, including where they are, when the story is set, the personalities involved, their relationship with each other, how they personally view the woman and what has been said in the argument so far. Knowing these things should help you write the right kind of line for your story.
A few possibilities off the top of my head that probably won't be applicable to your context, but might spark something:
‘You don’t stick a chance mate, every bloke here wants to get into her knickers.’
‘Every man here worships at her feet. What could she possibly want with you?’
‘Face it, Clifford, my daughter is more talented, better read and better looking than yours. Her suitors come from miles around.’
‘Lizzie’s sickening. She’s got all the men eating from the palm of her hand. What do I have to do to get noticed here?’ | For fiction writing you need more exposition & less narrative.
Narrative tells the reader.
Exposition shows the reader.
**Narrative Example (less good)**
>
> George was a nice man.
>
>
>
**Expositional Example (more good)**
>
> George looked at his watch and saw it was already 7:45am. Going to be
> late for the meeting and Mr. Murphy is going to kill me. He pushed his
> front door open and ran out toward his car. As George pulled the door
> open on his Jaguar X45 he heard a faint whimpering sound.
>
>
> He dropped his brief case into the car and walked around to the
> passenger side and looked under the car. Nothing there. He looked at
> his watch again and felt a pulse of heat travel down his back. He
> heard the whimpering sound again and walked around to the back of his
> car and looked down at the storm drain. He held his tie back so it
> wouldn't get dirty and he looked into the drain and saw two eyes
> looking back.
>
>
> The small dog he was now looking at let out a louder whine and he knew
> he'd have to get it out of the drain. He reached down and was just
> able to grab the dog by the scruff of the neck and hoist him out.
>
>
> He pulled the dog close trying to calm it. "Hey little fella. How'd
> you get stuck down there?" He looked at his watch again. Murphy is
> going to fire me. He looked back into the puppy's eyes and said,
> "Well, I guess you can comfort me on those lonely days when I'm
> looking for my next job."
>
>
>
**The Challenge**
It's a lot more work to write exposition (showing the reader) than it is to just tell the reader (narrative).
You can read more about this in an answer I posted here at [Writing SE](https://writing.stackexchange.com/questions/14586/are-how-to-write-fiction-books-full-of-it/14600#14600) |
62,270 | Suggestions for other ways to describe such a person would also be appreciated | 2022/06/01 | [
"https://writers.stackexchange.com/questions/62270",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/52787/"
] | The answer is an emphatic yes. Further you could dress that up. In fiction, you want movement and flow, emotion, oomph, a pointed description and a hold-no-punches emphasis.
*To say she was the apple of every man's eye in town was to massively, outrageously, understate the point. Clementine was far more than some common piece of fruit. She was the ship that launched. She was the summer's day. She was the drop-dead ten out of ten with a heart of gold.*
*In a word, irresistible.*
If that's too expositional for your tastes, you can modify it so that it fits dialog.
*"The apple of every man's eye? She's more than that, laddie. She's (etc)"* | For fiction writing you need more exposition & less narrative.
Narrative tells the reader.
Exposition shows the reader.
**Narrative Example (less good)**
>
> George was a nice man.
>
>
>
**Expositional Example (more good)**
>
> George looked at his watch and saw it was already 7:45am. Going to be
> late for the meeting and Mr. Murphy is going to kill me. He pushed his
> front door open and ran out toward his car. As George pulled the door
> open on his Jaguar X45 he heard a faint whimpering sound.
>
>
> He dropped his brief case into the car and walked around to the
> passenger side and looked under the car. Nothing there. He looked at
> his watch again and felt a pulse of heat travel down his back. He
> heard the whimpering sound again and walked around to the back of his
> car and looked down at the storm drain. He held his tie back so it
> wouldn't get dirty and he looked into the drain and saw two eyes
> looking back.
>
>
> The small dog he was now looking at let out a louder whine and he knew
> he'd have to get it out of the drain. He reached down and was just
> able to grab the dog by the scruff of the neck and hoist him out.
>
>
> He pulled the dog close trying to calm it. "Hey little fella. How'd
> you get stuck down there?" He looked at his watch again. Murphy is
> going to fire me. He looked back into the puppy's eyes and said,
> "Well, I guess you can comfort me on those lonely days when I'm
> looking for my next job."
>
>
>
**The Challenge**
It's a lot more work to write exposition (showing the reader) than it is to just tell the reader (narrative).
You can read more about this in an answer I posted here at [Writing SE](https://writing.stackexchange.com/questions/14586/are-how-to-write-fiction-books-full-of-it/14600#14600) |
62,270 | Suggestions for other ways to describe such a person would also be appreciated | 2022/06/01 | [
"https://writers.stackexchange.com/questions/62270",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/52787/"
] | No, this description wouldn’t be appropriate. As Kate Gregory points out in a comment, ‘the apple of my eye’ is often used by doting parents/older relatives about children, and doesn’t work in a romantic sense.
You don’t give much context so it’s difficult to suggest a useful alternative. Any one line is going to depend on host of things, including where they are, when the story is set, the personalities involved, their relationship with each other, how they personally view the woman and what has been said in the argument so far. Knowing these things should help you write the right kind of line for your story.
A few possibilities off the top of my head that probably won't be applicable to your context, but might spark something:
‘You don’t stick a chance mate, every bloke here wants to get into her knickers.’
‘Every man here worships at her feet. What could she possibly want with you?’
‘Face it, Clifford, my daughter is more talented, better read and better looking than yours. Her suitors come from miles around.’
‘Lizzie’s sickening. She’s got all the men eating from the palm of her hand. What do I have to do to get noticed here?’ | The answer is an emphatic yes. Further you could dress that up. In fiction, you want movement and flow, emotion, oomph, a pointed description and a hold-no-punches emphasis.
*To say she was the apple of every man's eye in town was to massively, outrageously, understate the point. Clementine was far more than some common piece of fruit. She was the ship that launched. She was the summer's day. She was the drop-dead ten out of ten with a heart of gold.*
*In a word, irresistible.*
If that's too expositional for your tastes, you can modify it so that it fits dialog.
*"The apple of every man's eye? She's more than that, laddie. She's (etc)"* |
32,012 | I'm working on an ASP.NET web application that will have to store sensitive information. I would like to encrypt the sensitive fields to protect against any possible SQL injection vulnerabilities. However, I also will need to report on these fields. For these reasons, I've excluded transparent database encryption (since it wouldn't provide protection against SQL injection) and application layer encryption (since it would make it hard to report against the data) and I'm left with database level encryption.
My plan is to use SQL Server's `EncryptByPassphrase` function, with an SSL connection to the database to protect the passphrase over the wire. The key would be stored in the `web.config`, protected by the Windows Data Protection API at the machine level.
Is this a good plan? What are the potential vulnerabilities? | 2013/03/05 | [
"https://security.stackexchange.com/questions/32012",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/10574/"
] | Yes, it's a good plan, but there are still a number of potential vulnerabilities. Really, the only attack that you're mitigating is the attack you mentioned, the ability to grab the cleartext data with an arbitrary SQL statement. You're not mitigating any other attacks, for instance, a malicious user who uses SQL injection to elevate their privileges within the application so that they can view a pages where the application expects to display this date in cleartext.
So, the real solution is defense in depth. This is a fine part of that solution (and indeed sensitive data *should* be encrypted at rest) but in order to effectively protect it you also need additional safeguards, such as:
1. General SQL injection protection strategies such as only allowing access to the application user via parameterized stored procedures and denying access to the underlying tables completely.
2. Protection against attacks relying on arbitrary code upload and execution
3. Protection against XSS and session stealing attacks that might allow a malicious user to capture authentication cookies from an administrator.
The data is only safe as the weakest link in the overall application security, so remember that direct attack on the data itself via SQL injection is not the only thing you need to think about in order to protect it. | >
> I would like to encrypt the sensitive fields to protect against any possible SQL injection vulnerabilities.
>
>
>
This is probably wrong at the outset. If your database is accessed through the application, in what circumstance would the application not decrypt the data? SQL injection is an application vulnerability, and hence at a level higher than when your data is decrypted.
Encrypting data in the database is meant to prevent data exposure by unauthorized access to the database. Since your application is authorized and can decrypt, it is not really protected against injection through this method. What you should be doing to protect against injection is using [parameterized queries](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html).
What you would be protected against is somebody compromised the database server directly without being able to compromise the web application.
>
> You would need to get the web application to retrieve the key first. And you can't inject code into the complied web application to do that.
>
>
>
A quick search for "[buffer overflow web application](https://www.google.com/search?q=buffer%20overflow%20web%20application)" should convince you otherwise. Also, the key would be exposed if they could somehow read the application. |
32,012 | I'm working on an ASP.NET web application that will have to store sensitive information. I would like to encrypt the sensitive fields to protect against any possible SQL injection vulnerabilities. However, I also will need to report on these fields. For these reasons, I've excluded transparent database encryption (since it wouldn't provide protection against SQL injection) and application layer encryption (since it would make it hard to report against the data) and I'm left with database level encryption.
My plan is to use SQL Server's `EncryptByPassphrase` function, with an SSL connection to the database to protect the passphrase over the wire. The key would be stored in the `web.config`, protected by the Windows Data Protection API at the machine level.
Is this a good plan? What are the potential vulnerabilities? | 2013/03/05 | [
"https://security.stackexchange.com/questions/32012",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/10574/"
] | Yes, it's a good plan, but there are still a number of potential vulnerabilities. Really, the only attack that you're mitigating is the attack you mentioned, the ability to grab the cleartext data with an arbitrary SQL statement. You're not mitigating any other attacks, for instance, a malicious user who uses SQL injection to elevate their privileges within the application so that they can view a pages where the application expects to display this date in cleartext.
So, the real solution is defense in depth. This is a fine part of that solution (and indeed sensitive data *should* be encrypted at rest) but in order to effectively protect it you also need additional safeguards, such as:
1. General SQL injection protection strategies such as only allowing access to the application user via parameterized stored procedures and denying access to the underlying tables completely.
2. Protection against attacks relying on arbitrary code upload and execution
3. Protection against XSS and session stealing attacks that might allow a malicious user to capture authentication cookies from an administrator.
The data is only safe as the weakest link in the overall application security, so remember that direct attack on the data itself via SQL injection is not the only thing you need to think about in order to protect it. | I second @Jeff Ferland in that there is a confusing statement in your question:
>
> I would like to encrypt the sensitive fields to protect against any
> possible SQL injection vulnerabilities
>
>
>
SQL injection is an application level problem, while DB encryption is meant to avoid insider threat, or someone who may have direct access to your database.
I am not very clear about which DBMS you are using, but I think what you need here is a column-based, database-level encryption. In the commercial world, [MyDiamo](https://mydiamo.com/) is the common solution for open source DB.
If you're using proprietary DBMS(Oracle, MSSQL, etc.) for a database-level encryption with Access Control capabilities, you'll probably want to go with MyDiamo's sister solutions suite [D'Amo](https://www.pentasecurity.com/product/encryption/damo/). Most other solutions on the market will be mainly file-level encryption which as you stated above, would thwart your purpose.
Note: I have been working as a DB encryption consultant and dealt with the above solutions for a while. |
32,012 | I'm working on an ASP.NET web application that will have to store sensitive information. I would like to encrypt the sensitive fields to protect against any possible SQL injection vulnerabilities. However, I also will need to report on these fields. For these reasons, I've excluded transparent database encryption (since it wouldn't provide protection against SQL injection) and application layer encryption (since it would make it hard to report against the data) and I'm left with database level encryption.
My plan is to use SQL Server's `EncryptByPassphrase` function, with an SSL connection to the database to protect the passphrase over the wire. The key would be stored in the `web.config`, protected by the Windows Data Protection API at the machine level.
Is this a good plan? What are the potential vulnerabilities? | 2013/03/05 | [
"https://security.stackexchange.com/questions/32012",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/10574/"
] | >
> I would like to encrypt the sensitive fields to protect against any possible SQL injection vulnerabilities.
>
>
>
This is probably wrong at the outset. If your database is accessed through the application, in what circumstance would the application not decrypt the data? SQL injection is an application vulnerability, and hence at a level higher than when your data is decrypted.
Encrypting data in the database is meant to prevent data exposure by unauthorized access to the database. Since your application is authorized and can decrypt, it is not really protected against injection through this method. What you should be doing to protect against injection is using [parameterized queries](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html).
What you would be protected against is somebody compromised the database server directly without being able to compromise the web application.
>
> You would need to get the web application to retrieve the key first. And you can't inject code into the complied web application to do that.
>
>
>
A quick search for "[buffer overflow web application](https://www.google.com/search?q=buffer%20overflow%20web%20application)" should convince you otherwise. Also, the key would be exposed if they could somehow read the application. | I second @Jeff Ferland in that there is a confusing statement in your question:
>
> I would like to encrypt the sensitive fields to protect against any
> possible SQL injection vulnerabilities
>
>
>
SQL injection is an application level problem, while DB encryption is meant to avoid insider threat, or someone who may have direct access to your database.
I am not very clear about which DBMS you are using, but I think what you need here is a column-based, database-level encryption. In the commercial world, [MyDiamo](https://mydiamo.com/) is the common solution for open source DB.
If you're using proprietary DBMS(Oracle, MSSQL, etc.) for a database-level encryption with Access Control capabilities, you'll probably want to go with MyDiamo's sister solutions suite [D'Amo](https://www.pentasecurity.com/product/encryption/damo/). Most other solutions on the market will be mainly file-level encryption which as you stated above, would thwart your purpose.
Note: I have been working as a DB encryption consultant and dealt with the above solutions for a while. |
31,361,930 | I want to make an array of players sorted in order of salary from the following XML. Notice that I already sort the basketball teams by salary.
```
<?php
$string = <<<EOS
<Sports_Team>
<Basketball>
<Players>Tom, Jack, Sue</Players>
<salary>4</salary>
</Basketball>
<Basketball>
<Players>Josh, Lee, Carter, Bennett</Players>
<salary>6</salary>
</Basketball>
<Basketball>
<Players>Mary, Jimmy, Nancy</Players>
<salary>44</salary>
</Basketball>
</Sports_Team>
EOS;
$xml = simplexml_load_string($string);
$trees = $xml->xpath('/Sports_Team/Basketball');
function sort_trees($t1, $t2) {
return strcmp($t1['salary'], $t2['salary']);
}
usort($trees, 'sort_trees');
var_dump($trees);
?>
```
I want to make an array of Players from `$trees`. How do I create an array object such that:
```
[0]-> Mary, Jimmy, Nancy
[1]-> Josh, Lee, Carter, Bennett
[2]-> Tom, Jack, Sue
```
Also, once I've stored my array how do I print it out visually? | 2015/07/11 | [
"https://Stackoverflow.com/questions/31361930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2237387/"
] | Basically you have done everything perfectly right, except a couple of tiny bits which i will address bellow :)
* In your user-defined comparison function 'sort\_trees', best to compare integer directly and not the string, so no need to compare string using (strcmp).
* Also you could use `uasort()` method instead of `usort()` to maintain index association
so your code with a tiny change can be something like the following, and finally I'm using `print_r()` method to print the array as you asked
```
<?php
function sort_trees_by_salary($t1, $t2)
{
return (int)$t1['salary'] > (int)$t2['salary'];
}
function sort_trees_by_number_of_players($t1, $t2)
{
return substr_count($t1->Players, ',') > substr_count($t2->Players, ',');
}
$string = <<<EOS
<Sports_Team>
<Basketball>
<Players>Tom, Jack, Sue</Players>
<salary>4</salary>
</Basketball>
<Basketball>
<Players>Josh, Lee, Carter, Bennett</Players>
<salary>6</salary>
</Basketball>
<Basketball>
<Players>Mary, Jimmy, Nancy</Players>
<salary>44</salary>
</Basketball>
</Sports_Team>
EOS;
$xml = simplexml_load_string($string);
$trees = $xml->xpath('/Sports_Team/Basketball');
// Lets say you want to sort by salary
uasort($trees, 'sort_trees_by_salary');
$results = [];
foreach ($trees as $tree) {
$results[] = (string)$tree->Players;
}
echo 'Sorted by Salary:';
print_r($results);
// Lets say you want to sort by number of players
uasort($trees, 'sort_trees_by_number_of_players');
$results = [];
foreach ($trees as $tree) {
$results[] = (string)$tree->Players;
}
echo 'Sorted by number of players:';
print_r($results);
```
Output:
```
Sorted by Salary:Array
(
[0] => Mary, Jimmy, Nancy
[1] => Josh, Lee, Carter, Bennett
[2] => Tom, Jack, Sue
)
Sorted by number of players:Array
(
[0] => Mary, Jimmy, Nancy
[1] => Tom, Jack, Sue
[2] => Josh, Lee, Carter, Bennett
)
```
**Please note:** considering the [user-defined comparison function](http://php.net/manual/en/function.uasort.php) works with the reference the above example will apply both sorting methods on your set of data, first to order the list based on the salary and second based on the number players | Assuming you have PHP 5.3+, try this:
```
$playersArray = array_map(
create_function('$inputArray', 'return (string) $inputArray->Players;'),
$trees
);
```
For example:
```
php > var_dump($playersArray);
array(3) {
[0]=>
string(18) "Mary, Jimmy, Nancy"
[1]=>
string(26) "Josh, Lee, Carter, Bennett"
[2]=>
string(14) "Tom, Jack, Sue"
}
```
If you're using older PHP, you need to use a real (non-anonymous) function for `array_map()`, or use `create_function()`:
```
$playersArray = array_map(
create_function('$inputArray', 'return (array) $inputArray->Players;'),
$users
);
```
To answer the last part, how do you print it out visually, well, that depends! If you just want to dump it to view it for debugging purposes, use `var_dump()` or `print_r()`. Both take the array variable as the only needed argument. `var_dump()` is a bit more verbose.
This is `var_dump()` ([manual](https://secure.php.net/manual/en/function.var-dump.php)):
```
php > var_dump($playersArray);
array(3) {
[0]=>
string(18) "Mary, Jimmy, Nancy"
[1]=>
string(26) "Josh, Lee, Carter, Bennett"
[2]=>
string(14) "Tom, Jack, Sue"
}
```
This is `print_r()` ([manual](https://secure.php.net/manual/en/function.print-r.php)):
```
php > print_r($playersArray);
Array
(
[0] => Mary, Jimmy, Nancy
[1] => Josh, Lee, Carter, Bennett
[2] => Tom, Jack, Sue
)
```
Otherwise, to process and display output for end users based on the array, you'll likely want to loop through it and process it, or use `array_map()` similarly to above to generate the output. Also, if you want to experiment with this in a [PHP Console](https://secure.php.net/manual/en/features.commandline.interactive.php) similarly to what I did in my examples, you can run `php -a` and type your code at the prompt.
**Edit**
To answer the question from the comments, try this:
```
/* Sort by the number of ',' characters in the string. */
function sort_players($a, $b) {
$ca = substr_count($a, ',');
$cb = substr_count($b, ',');
if ($ca == $cb) return 0;
return ($ca > $cb) ? -1 : 1;
}
usort($playersArray, 'sort_players');
``` |
67,817,640 | I want to use json schema in order to validate something like this:
```json
{
"function_mapper": {
"critical": [
"DataContentValidation.get_multiple_types_columns",
"DataContentValidation.get_invalid_session_ids"
],
"warning": [
"DataContentValidation.get_columns_if_most_data_null",
"FeatureContentValidation.detect_inconsistencies"
]
}
}
```
And I want to use regex to check if the list content looks like this `Class.function` I've tried to change on of the functions to `'dataContentValidation.get_multiple_types_columns'`
and I came up with this schema but it didn't work:
```json
{
"type": "object",
"properties": {
"function_mapper": {
"type": "object",
"properties": {
"critical": {
"type": "array",
"uniqueItems": True,
"items":
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
},
"error": {
"type": "array",
"items": [
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
]
},
"informative": {
"type": "array",
"items": [
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
]
}
}
},
"days_gap": {"type": "integer", "minimum": 0},
"timestamp_column": {"type": "string"},
"missing_data_median_epsilon": {"type": "number", "minimum": 0, "maximum": 1},
"group_by_time_unit": {"type": "string", "enum": ["d", "w", "m", "h", "T", "min", "s"]},
"null_data_percentage": {"type": "number", "minimum": 0, "maximum": 1},
"common_feature_threshold": {"type": "number", "minimum": 0, "maximum": 1},
"columns_to_count": {"type": "array", "items": {"type": "string"}},
"cluster_median_epsilon": {"type": "number", "minimum": 0, "maximum": 1},
"app_session_id_column": {"type": "string"}
}
}
```
I also tried replacing the contains with items but it still does not work.
What am I doing wrong? | 2021/06/03 | [
"https://Stackoverflow.com/questions/67817640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15414616/"
] | `.Find` returns a range object. Is this what you are trying?
```
Option Explicit
Sub Sample()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("worksheet1")
Dim lo As ListObject: Set lo = ws.ListObjects("Table1")
Dim aCell As Range
Set aCell = lo.HeaderRowRange.Find("Column3", LookIn:=xlValues, LookAt:=xlWhole)
If Not aCell Is Nothing Then
MsgBox aCell.Column
End If
End Sub
```
Alternatively you can also use `Application.Match`
```
Option Explicit
Sub Sample()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("worksheet1")
Dim lo As ListObject: Set lo = ws.ListObjects("Table1")
Dim j As Long: j = Application.Match("Column3", lo.HeaderRowRange, 0)
MsgBox j
End Sub
```
**PS**: You also have a typo in your code. `Dim lo As listoject` should be `Dim lo As ListObject`
**EDIT**
>
> See screenshot to understand better my goal: w/in the ListObject Column3 is the 3rd column, while w/in the worksheet it is column 6 (column F). I want the j in my code to be 3 (not 6).
>
>
>
In such a case if your table doesn't start from Col `A` then you will have to do the range adjustment. Change `MsgBox aCell.Column` to `MsgBox aCell.Column - lo.HeaderRowRange.Column + 1` in the first code.
**Output**
[](https://i.stack.imgur.com/oJ3fA.png) | There are several way to access the column in `listobject table` other than `hearderRow`, hope you find it useful
```
Sub tt()
Dim tb1 As ListObject
Dim rcol As Range
Set tb1 = Sheet1.ListObjects("Table1")
Set rcol = tb1.ListColumns("Ctry").DataBodyRange
Debug.Print rcol(3).Value 'Hawaii
End Sub
```
[](https://i.stack.imgur.com/ma2cm.png) |
67,817,640 | I want to use json schema in order to validate something like this:
```json
{
"function_mapper": {
"critical": [
"DataContentValidation.get_multiple_types_columns",
"DataContentValidation.get_invalid_session_ids"
],
"warning": [
"DataContentValidation.get_columns_if_most_data_null",
"FeatureContentValidation.detect_inconsistencies"
]
}
}
```
And I want to use regex to check if the list content looks like this `Class.function` I've tried to change on of the functions to `'dataContentValidation.get_multiple_types_columns'`
and I came up with this schema but it didn't work:
```json
{
"type": "object",
"properties": {
"function_mapper": {
"type": "object",
"properties": {
"critical": {
"type": "array",
"uniqueItems": True,
"items":
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
},
"error": {
"type": "array",
"items": [
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
]
},
"informative": {
"type": "array",
"items": [
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
]
}
}
},
"days_gap": {"type": "integer", "minimum": 0},
"timestamp_column": {"type": "string"},
"missing_data_median_epsilon": {"type": "number", "minimum": 0, "maximum": 1},
"group_by_time_unit": {"type": "string", "enum": ["d", "w", "m", "h", "T", "min", "s"]},
"null_data_percentage": {"type": "number", "minimum": 0, "maximum": 1},
"common_feature_threshold": {"type": "number", "minimum": 0, "maximum": 1},
"columns_to_count": {"type": "array", "items": {"type": "string"}},
"cluster_median_epsilon": {"type": "number", "minimum": 0, "maximum": 1},
"app_session_id_column": {"type": "string"}
}
}
```
I also tried replacing the contains with items but it still does not work.
What am I doing wrong? | 2021/06/03 | [
"https://Stackoverflow.com/questions/67817640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15414616/"
] | As I know the name of the column header, I can simply use this code to get the column count w/in the ListObject:
```
j= lo.ListColumns("Column3").Index
``` | There are several way to access the column in `listobject table` other than `hearderRow`, hope you find it useful
```
Sub tt()
Dim tb1 As ListObject
Dim rcol As Range
Set tb1 = Sheet1.ListObjects("Table1")
Set rcol = tb1.ListColumns("Ctry").DataBodyRange
Debug.Print rcol(3).Value 'Hawaii
End Sub
```
[](https://i.stack.imgur.com/ma2cm.png) |
67,817,640 | I want to use json schema in order to validate something like this:
```json
{
"function_mapper": {
"critical": [
"DataContentValidation.get_multiple_types_columns",
"DataContentValidation.get_invalid_session_ids"
],
"warning": [
"DataContentValidation.get_columns_if_most_data_null",
"FeatureContentValidation.detect_inconsistencies"
]
}
}
```
And I want to use regex to check if the list content looks like this `Class.function` I've tried to change on of the functions to `'dataContentValidation.get_multiple_types_columns'`
and I came up with this schema but it didn't work:
```json
{
"type": "object",
"properties": {
"function_mapper": {
"type": "object",
"properties": {
"critical": {
"type": "array",
"uniqueItems": True,
"items":
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
},
"error": {
"type": "array",
"items": [
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
]
},
"informative": {
"type": "array",
"items": [
{
"type": "string",
"pattern": r"[A-Z]\w+\.\w+"
# TODO add pattern that represent a class and function i.e: Class.function
}
]
}
}
},
"days_gap": {"type": "integer", "minimum": 0},
"timestamp_column": {"type": "string"},
"missing_data_median_epsilon": {"type": "number", "minimum": 0, "maximum": 1},
"group_by_time_unit": {"type": "string", "enum": ["d", "w", "m", "h", "T", "min", "s"]},
"null_data_percentage": {"type": "number", "minimum": 0, "maximum": 1},
"common_feature_threshold": {"type": "number", "minimum": 0, "maximum": 1},
"columns_to_count": {"type": "array", "items": {"type": "string"}},
"cluster_median_epsilon": {"type": "number", "minimum": 0, "maximum": 1},
"app_session_id_column": {"type": "string"}
}
}
```
I also tried replacing the contains with items but it still does not work.
What am I doing wrong? | 2021/06/03 | [
"https://Stackoverflow.com/questions/67817640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15414616/"
] | As I know the name of the column header, I can simply use this code to get the column count w/in the ListObject:
```
j= lo.ListColumns("Column3").Index
``` | `.Find` returns a range object. Is this what you are trying?
```
Option Explicit
Sub Sample()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("worksheet1")
Dim lo As ListObject: Set lo = ws.ListObjects("Table1")
Dim aCell As Range
Set aCell = lo.HeaderRowRange.Find("Column3", LookIn:=xlValues, LookAt:=xlWhole)
If Not aCell Is Nothing Then
MsgBox aCell.Column
End If
End Sub
```
Alternatively you can also use `Application.Match`
```
Option Explicit
Sub Sample()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("worksheet1")
Dim lo As ListObject: Set lo = ws.ListObjects("Table1")
Dim j As Long: j = Application.Match("Column3", lo.HeaderRowRange, 0)
MsgBox j
End Sub
```
**PS**: You also have a typo in your code. `Dim lo As listoject` should be `Dim lo As ListObject`
**EDIT**
>
> See screenshot to understand better my goal: w/in the ListObject Column3 is the 3rd column, while w/in the worksheet it is column 6 (column F). I want the j in my code to be 3 (not 6).
>
>
>
In such a case if your table doesn't start from Col `A` then you will have to do the range adjustment. Change `MsgBox aCell.Column` to `MsgBox aCell.Column - lo.HeaderRowRange.Column + 1` in the first code.
**Output**
[](https://i.stack.imgur.com/oJ3fA.png) |
21,703,537 | I have the following code for responsive fonts:
```
@media all and (max-width: 1200px) { /* screen size until 1200px */
body {
font-size: 1.5em; /* 1.5x default size */
}
}
@media all and (max-width: 1000px) { /* screen size until 1000px */
body {
font-size: 1.2em; /* 1.2x default size */
}
}
@media all and (max-width: 500px) { /* screen size until 500px */
body {
font-size: 0.8em; /* 0.8x default size */
}
}
```
I dont know how can I set the 'default size'. For example 1.5em font-size how many pxs are? 14px? 12px?.
Regards. | 2014/02/11 | [
"https://Stackoverflow.com/questions/21703537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3157384/"
] | Here's a simple formula to convert from px to em:
```
Size in em = size in pixels / parent size in pixels
```
**Example**: 21px / 14px = 1.5em
and back:
```
Size in px = size in EMs * parent size in pixels
```
**Example**: 1.5em \* 14px = 21px
PS: 14px is the default font size in Bootstrap. [Source](http://getbootstrap.com/css/#type-body-copy): Bootstrap CSS. | The `em` unit always uses the unit of the parent element as the base.
e.g. if your `body` has a `font-size` of `12px`, then setting `1em` on a child element would also render it with `12px` (1em = 100%)
From then on, you can use sites like <http://pxtoem.com/> to calculate the appropriate `em` values you're trying to achieve
You may also just refer to percents (`1.5em` = `150%`, `2em` = `200%` and so on...) |
21,703,537 | I have the following code for responsive fonts:
```
@media all and (max-width: 1200px) { /* screen size until 1200px */
body {
font-size: 1.5em; /* 1.5x default size */
}
}
@media all and (max-width: 1000px) { /* screen size until 1000px */
body {
font-size: 1.2em; /* 1.2x default size */
}
}
@media all and (max-width: 500px) { /* screen size until 500px */
body {
font-size: 0.8em; /* 0.8x default size */
}
}
```
I dont know how can I set the 'default size'. For example 1.5em font-size how many pxs are? 14px? 12px?.
Regards. | 2014/02/11 | [
"https://Stackoverflow.com/questions/21703537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3157384/"
] | Since this is the body font-size, 1.5em should equal to 24px.
**em** always use his parent element as its base but, relative em or **rem** doesn't use his immediate parent; It uses the html or body font-size.
e.g.
```
body{
font-size:1em = 16px
}
.container{
font-size:1em = 16px
font-size:0.75em = 12px
}
``` | Here's a simple formula to convert from px to em:
```
Size in em = size in pixels / parent size in pixels
```
**Example**: 21px / 14px = 1.5em
and back:
```
Size in px = size in EMs * parent size in pixels
```
**Example**: 1.5em \* 14px = 21px
PS: 14px is the default font size in Bootstrap. [Source](http://getbootstrap.com/css/#type-body-copy): Bootstrap CSS. |
21,703,537 | I have the following code for responsive fonts:
```
@media all and (max-width: 1200px) { /* screen size until 1200px */
body {
font-size: 1.5em; /* 1.5x default size */
}
}
@media all and (max-width: 1000px) { /* screen size until 1000px */
body {
font-size: 1.2em; /* 1.2x default size */
}
}
@media all and (max-width: 500px) { /* screen size until 500px */
body {
font-size: 0.8em; /* 0.8x default size */
}
}
```
I dont know how can I set the 'default size'. For example 1.5em font-size how many pxs are? 14px? 12px?.
Regards. | 2014/02/11 | [
"https://Stackoverflow.com/questions/21703537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3157384/"
] | Since this is the body font-size, 1.5em should equal to 24px.
**em** always use his parent element as its base but, relative em or **rem** doesn't use his immediate parent; It uses the html or body font-size.
e.g.
```
body{
font-size:1em = 16px
}
.container{
font-size:1em = 16px
font-size:0.75em = 12px
}
``` | The `em` unit always uses the unit of the parent element as the base.
e.g. if your `body` has a `font-size` of `12px`, then setting `1em` on a child element would also render it with `12px` (1em = 100%)
From then on, you can use sites like <http://pxtoem.com/> to calculate the appropriate `em` values you're trying to achieve
You may also just refer to percents (`1.5em` = `150%`, `2em` = `200%` and so on...) |
39,860,225 | I have a "document" model, an upload system using dropzone.js and the register/login. Im now lost on how to apply permissions to each individual uploaded **File** so only the specified users can access them.
Basically:
File1->accessible\_by = user1,user2
File2->accesible\_by=user3,user5...
And so on.
Thanks to anyone for advice/help on my problem.
Edit with relevant code:
========================
Create Document View:
---------------------
```
class DocumentCreate(CreateView):
model = Document
fields = ['file', 'is_public']
def form_valid(self, form):
self.object = form.save()
data = {'status': 'success'}
response = JSONResponse(data, mimetype =
response_mimetype(self.request))
return response
```
I did the above to the view to handle dropzone.js file uploading.
This is my "document" model
---------------------------
```
class Document(models.Model):
file = models.FileField(upload_to = 'files/')
#validators=[validate_file_type])
uploaded_at = models.DateTimeField(auto_now_add = True)
extension = models.CharField(max_length = 30, blank = True)
thumbnail = models.ImageField(blank = True, null = True)
is_public = models.BooleanField(default = False)
uploaded_by = models.ForeignKey(User,
related_name='uploadedByAsUser', null=True)
allowed_users = models.ManyToManyField(User,
related_name='allowedUsersAsUser')
def clean(self):
self.file.seek(0)
self.extension = self.file.name.split('/')[-1].split('.')[-1]
if self.extension == 'xlsx' or self.extension == 'xls':
self.thumbnail = 'xlsx.png'
elif self.extension == 'pptx' or self.extension == 'ppt':
self.thumbnail = 'pptx.png'
elif self.extension == 'docx' or self.extension == 'doc':
self.thumbnail = 'docx.png'
def delete(self, *args, **kwargs):
#delete file from /media/files
self.file.delete(save = False)
#call parent delete method.
super().delete(*args, **kwargs)
#Redirect to file list page.
def get_absolute_url(self):
return reverse('dashby-files:files')
def __str__(self):
return self.file.name.split('/')[-1]
class Meta():
ordering = ['-uploaded_at']
``` | 2016/10/04 | [
"https://Stackoverflow.com/questions/39860225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6900730/"
] | Just return a `(payload)` from weave. It will be a `HashMap`. | You can do that without DataWeave too, like below -
```
<json:json-to-object-transformer
returnClass="java.util.HashMap" doc:name="JSON to Object" />
``` |
72,709,031 | My code is failing this testcase. Can someone please help me understand what is incorrect with my code?
Input:
"badc"
"baba"
Output:
true
Expected:
false
```
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict = {}
if len(s)==0 or len(t)==0:
return False
for i in range(len(s)):
if s[i] in dict:
if dict[s[i]] != t[i]:
return False
else:
dict[s[i]] = t[i]
return True
``` | 2022/06/22 | [
"https://Stackoverflow.com/questions/72709031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13144897/"
] | This works but i would prefer not to hardcode in the where clause of the 2nd query in this union :
```
select st.ID "Student ID", st.Name "Name", round(avg(scr.Score),0) "Average Score"
from Student st LEFT OUTER JOIN Score scr on st.ID = scr.Student
where scr.ID < 9
Group by st.ID
union
select st.ID "Student ID", st.Name "Name", round(avg(scr.Score),0) "Average Score"
from Student st LEFT OUTER JOIN Score scr on st.ID = scr.Student
where st.ID = 'Z'
Group by st.ID
```
By the way, I did switched to SQLServer 2017 using free software on the web that allows us to switched from MySQL to SQLServer 2017 ) and this newly created UNION is still working but i first had to add the "decimal" argument value of 0 for the round function.
I mean, i would prefer using the following proposed code but somehow it's not working ?
```
SELECT
st.ID "Student ID",
st.Name "Name",
round(avg(scr.Score)) "Av Score"
FROM
Student st LEFT OUTER JOIN
Score scr on st.ID = scr.Player
WHERE
scr.ID < 9 -- Because records greater have been known to be false and we don't need them
GROUP BY
st.ID
``` | All you need is to use `ISNULL`
```sql
SELECT
st.ID "Student ID",
st.Name "Name",
round(avg(ISNULL(scr.Score, -1)), 0) "Av Score"
FROM
Student st LEFT OUTER JOIN
Score scr on st.ID = scr.Player
WHERE
scr.ID < 9 -- Because records greater have been known to be false and we don't need them
GROUP BY
st.ID,
st.Name
```
In this case, you will see that anyone with `-1` score is a person who did not take the exams. It could be useful since score of `0` could come from a very bad exam taker
Also, while this is posibble, try to avoid spaces and system words in the identifiers and aliases
Here is running code <https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5ab664ba7a29344a094e5aca9cd35e9e> |
72,709,031 | My code is failing this testcase. Can someone please help me understand what is incorrect with my code?
Input:
"badc"
"baba"
Output:
true
Expected:
false
```
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict = {}
if len(s)==0 or len(t)==0:
return False
for i in range(len(s)):
if s[i] in dict:
if dict[s[i]] != t[i]:
return False
else:
dict[s[i]] = t[i]
return True
``` | 2022/06/22 | [
"https://Stackoverflow.com/questions/72709031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13144897/"
] | An outer join works thus: If there are matching rows, they get joined (just like with an inner join). If there are no matching rows, you still get a joined row, but the columns of the outer joined table are set to null.
You want to outer join all scores below nine. Instead you outer join all scores:
```
LEFT OUTER JOIN Score scr ON st.ID = scr.Player
```
Then you want to get rid of the higher scores with
```
WHERE scr.ID < 9
```
But in outer joined rows the scr.ID is null, and this clause dismisses these rows, too. Thus you end up with a mere inner join.
Instead outer join the scores below nine as intended:
```
LEFT OUTER JOIN Score scr ON st.ID = scr.Player AND scr.ID < 9
``` | All you need is to use `ISNULL`
```sql
SELECT
st.ID "Student ID",
st.Name "Name",
round(avg(ISNULL(scr.Score, -1)), 0) "Av Score"
FROM
Student st LEFT OUTER JOIN
Score scr on st.ID = scr.Player
WHERE
scr.ID < 9 -- Because records greater have been known to be false and we don't need them
GROUP BY
st.ID,
st.Name
```
In this case, you will see that anyone with `-1` score is a person who did not take the exams. It could be useful since score of `0` could come from a very bad exam taker
Also, while this is posibble, try to avoid spaces and system words in the identifiers and aliases
Here is running code <https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5ab664ba7a29344a094e5aca9cd35e9e> |
32,973,285 | ```
class Example {
@Override
protected void finalize() {
System.out.println("Object getting garbage collected");
}
}
public class GarbageCollectionDemo {
public static void main(String [] args) {
Example e1 = new Example();
{
Example e2 = new Example();
}
e1.finalize();
}
}
```
I wanted to check whether the output shows when the `finalize()` is called, and when the objects are actually getting removed. But I could not track, is it because its according to the JVM that the object will be garbage collected? What happens if we override the `finalize()` method? Do we have to explicitly call it ourselves? Then why does Netbeans suggest to add the `finally` block with `super.finally()`? | 2015/10/06 | [
"https://Stackoverflow.com/questions/32973285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5249269/"
] | You can interact with the GC using references, like for example shown [here](http://pawlan.com/monica/articles/refobjs/). In particular, keeping a reference (created with a ReferenceQueue) to your object gives you an option to be notified when the object is GC-ed. | Try to read first [Why not to use finalize() method in java](http://howtodoinjava.com/2012/10/31/why-not-to-use-finalize-method-in-java/), before take a look deeper in my answer. In most cases, you can find a better solution, then to rely on finalize method behaviour.
If you still need to use `finalize()`, for some reason, then you can use this example:
```
class SimpleClass {
@Override
protected void finalize() {
System.out.println("Object getting garbage collected");
}
}
public class GarbageCollectionDemo {
public static void main(String [] args) throws InterruptedException {
GarbageCollectionDemo demo = new GarbageCollectionDemo();
demo.call();
System.gc();
Thread.sleep(1000);
System.out.println("Collected");
}
public void call() {
SimpleClass e1 = new SimpleClass();
}
}
```
But it's not guaranteed, that it'll be finilized even in this case.
>
> What happens if we override the finalize() method? Do we have to explicitly call it ourselves?
>
>
>
You just override it, as any other method. No, you don't have to call it yourself, it'll be called on object finalization.
>
> Then why does Netbeans suggest to add the finally block with super.finally()?
>
>
>
Your Superclass could have a specific behaviour in it's implementation of `finalize()` method. Netbeans try to prevent the situation, when this logic will not be called, if you'll forget to call `super.finally()` or your logic will cause an exception just before the SuperClass finilize call. |
37,069,678 | ```
string x = "alok b";
string y = "alok b";
string z = "alok";
//y += x.Replace(y, string.Empty);
z += " b";
Console.WriteLine(object.ReferenceEquals(x,y));
Console.WriteLine(object.ReferenceEquals(y, z));
```
How is first line is printing `true` and second `false`?
and changing to below statement is printing `true`.
```
Console.WriteLine(object.ReferenceEquals(y,string.Intern(z)));
``` | 2016/05/06 | [
"https://Stackoverflow.com/questions/37069678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4576125/"
] | It's called [string interning](http://www.c-sharpcorner.com/UploadFile/d551d3/what-is-string-interning/). | When you create a string it creates an object (`x`).
when you create `y`, you just point to it"again", it points to the same one (has it).
When you create Z, and the do the `+=` it creates a NEW one altogether, hence, it won't match the address in the memory for the previous one. |
40,503,793 | I am reading a txt file of multiple pipe delimited records, each token of records corresponds to unique key and different value. I need to compare each record values (with same keys). To compare this I want to use HashMap to store first record then will iterate and store second record. After that will compare both hashmap to see if both contains similar values. But I am not sure how to manage or create 2 hashma within same loop while reading the txt file.
Example :
txt file as below
```
A|B|C|D|E
A|B|C|O|E
O|O|C|D|E
```
Each token of each record will be stored against unique key as below
first record
```
map.put(1, A);
map.put(2, B);
map.put(3, C);
map.put(4, D);
map.put(5, E);
```
Second record
```
map.put(1, A);
map.put(2, B);
map.put(3, C);
map.put(4, O);
map.put(5, E);
```
third record
```
map.put(1, O);
map.put(2, O);
map.put(3, C);
map.put(4, D);
map.put(5, E);
```
When I read each record in java using input stream, in same loop of reading records how can I create 2 hashmap of 2 different record to compare.
```
FileInputStream fstream;
fstream = new FileInputStream("C://PROJECTS//sampleInput.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
//Read File Line By Line
String line1=null;
while ((line1 = br.readLine()) != null){
Scanner scan = new Scanner(line1).useDelimiter("\\|");
while(scan.hasNext()){
// reading each token of the record
// how to create 2 hashmap of 2 records to compare.. or is there any simple way to compare each incoming records
}
printIt(counter);
}
``` | 2016/11/09 | [
"https://Stackoverflow.com/questions/40503793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2076174/"
] | You probably need to use [@RepositoryRestController](http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers) for this. It lets you get stuff from the @Repository and then add new things to the response object. Pretty similar to @RestController, but keeps Spring Data REST’s settings, message converters, exception handling, and more. | you could add Interceptor implementing [HandleInterceptor](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html) and add it to mapped inteceptor bean.
```
@Bean
public MappedInterceptor myMappedInterceptor() {
return new MappedInterceptor(new String[]{"/**"}, new MyInterceptor());
}
``` |
430,410 | The CS inequality is given by
>
> $$x\_1y\_1 + x\_2y\_2 \leq \sqrt{x\_1^2 + x\_2^2}\sqrt{y\_1^2 + y\_2^2}$$
>
>
>
I read that if $x\_1 = cy\_1$ and $x\_2 = cy\_2$, then equality holds.
But I reduced the above to $c \leq \sqrt{c^2} = |c|$. So isn't this only true if $c > 0$? | 2013/06/26 | [
"https://math.stackexchange.com/questions/430410",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/26728/"
] | Assume $x\_1,\dots,y\_2$ are real numbers. We have $$(x\_1^2+x\_2^2)(y\_1^2+y\_2^2)-(x\_1y\_1+x\_2y\_2)^2=(x\_1y\_2-x\_2y\_1)^2.$$ This is the case $n=2$ of an identity due to Lagrange.
(See more on this, positive polynomials, sums of squares of polynomials, and Hilbert's 17th problem, in [this](http://andrescaicedo.wordpress.com/2008/11/11/275-positive-polynomials/) old blog post of mine.)
This means that $|x\_1y\_1+x\_2y\_2|\le\sqrt{x\_1^2+y\_1^2}\sqrt{y\_1^2+y\_2^2}$, with equality iff $$\det\left(\begin{array}{cc}x\_1&y\_1\\ x\_2&y\_2\end{array}\right)=0,$$ that is, iff either there is a constant $c$ such that $x\_1=cy\_1$ and $x\_2=cy\_2$, or else $y\_1=y\_2=0$.
Since $a\le|a|$ for any real number $a$, it follows that $x\_1y\_1 + x\_2y\_2 \leq \sqrt{x\_1^2 + x\_2^2}\sqrt{y\_1^2 + y\_2^2}$, with equality as above, except that now we further need $c\ge 0$. | $c\le|c|$ ins't restricts to $c>0$ |
430,410 | The CS inequality is given by
>
> $$x\_1y\_1 + x\_2y\_2 \leq \sqrt{x\_1^2 + x\_2^2}\sqrt{y\_1^2 + y\_2^2}$$
>
>
>
I read that if $x\_1 = cy\_1$ and $x\_2 = cy\_2$, then equality holds.
But I reduced the above to $c \leq \sqrt{c^2} = |c|$. So isn't this only true if $c > 0$? | 2013/06/26 | [
"https://math.stackexchange.com/questions/430410",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/26728/"
] | Assume $x\_1,\dots,y\_2$ are real numbers. We have $$(x\_1^2+x\_2^2)(y\_1^2+y\_2^2)-(x\_1y\_1+x\_2y\_2)^2=(x\_1y\_2-x\_2y\_1)^2.$$ This is the case $n=2$ of an identity due to Lagrange.
(See more on this, positive polynomials, sums of squares of polynomials, and Hilbert's 17th problem, in [this](http://andrescaicedo.wordpress.com/2008/11/11/275-positive-polynomials/) old blog post of mine.)
This means that $|x\_1y\_1+x\_2y\_2|\le\sqrt{x\_1^2+y\_1^2}\sqrt{y\_1^2+y\_2^2}$, with equality iff $$\det\left(\begin{array}{cc}x\_1&y\_1\\ x\_2&y\_2\end{array}\right)=0,$$ that is, iff either there is a constant $c$ such that $x\_1=cy\_1$ and $x\_2=cy\_2$, or else $y\_1=y\_2=0$.
Since $a\le|a|$ for any real number $a$, it follows that $x\_1y\_1 + x\_2y\_2 \leq \sqrt{x\_1^2 + x\_2^2}\sqrt{y\_1^2 + y\_2^2}$, with equality as above, except that now we further need $c\ge 0$. | Suppose $(x\_1,x\_2)=c(y\_1,y\_2)$, then
$$
\begin{align}
x\_1y\_1+x\_2y\_2&=cy\_1^2+cy\_2^2\\
x\_1^2+x\_2^2&=c^2y\_1^2+c^2y\_2^2
\end{align}
$$
Therefore,
$$
\begin{align}
x\_1y\_1+x\_2y\_2
&=\frac{c}{|c|}\sqrt{x\_1^2+x\_2^2}\sqrt{y\_1^2+y\_2^2}\\
&=\pm\sqrt{x\_1^2+x\_2^2}\sqrt{y\_1^2+y\_2^2}
\end{align}
$$
Thus, the equality only holds for $c\ge0$.
However, the inequality
$$
|x\_1y\_1+x\_2y\_2|\le\sqrt{x\_1^2+x\_2^2}\sqrt{y\_1^2+y\_2^2}
$$
holds, and *this* equality holds if $(x\_1,x\_2)=c(y\_1,y\_2)$ for any $c$. |
36,891,399 | I want to launch an RDS instance from CloudFormation.
I am constructing the JSON template based on the AWS documentation .
I want to set the *PreferredBackupWindow* parameter, but there is no example how to enter it's value.
I want to set it to create a snapshot every day at 6 in the morning.
How should I write it?? [`"PreferredBackupWindow" : String,`]
Something like `"PreferredBackupWindow" : "6:00UTC",` ?? | 2016/04/27 | [
"https://Stackoverflow.com/questions/36891399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163667/"
] | The preferred backup and maintenance can be set as the following string inputs:
```
MySQLDatabase:
Type: 'AWS::RDS::DBInstance'
Properties:
...
PreferredBackupWindow: "22:30-23:30"
PreferredMaintenanceWindow: "mon:23:30-tue:00:30"
...
```
Please note that the time is set according to the UTC timezone. | You can enter string in following format hh24:mi-hh24:mi (24H Clock UTC).
For Example:
```
"PreferredBackupWindow": "19:30-20:00"
``` |
99,482 | Over on SO several questions have been tagged as [compass](/questions/tagged/compass "show questions tagged 'compass'") when they should have been classified as [compass-css](/questions/tagged/compass-css "show questions tagged 'compass-css'") instead. What's the proper process for requesting they get retagged properly? I lack sufficient mojo to do it myself and I've flagged the questions, but that doesn't seem to be getting processed. Needless to say, searching for help on style issues with the search gurus probably isn't efficient. | 2011/07/22 | [
"https://meta.stackexchange.com/questions/99482",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/136062/"
] | The numbered versions for Mac OS X tags do not appear to be that popular:
* [macosx-10.5](/questions/tagged/macosx-10.5 "show questions tagged 'macosx-10.5'") = 80 questions
* [osx-10.6](/questions/tagged/osx-10.6 "show questions tagged 'osx-10.6'") = 18 questions
* [osx-10.7](/questions/tagged/osx-10.7 "show questions tagged 'osx-10.7'") = 43 questions
The corresponding cat names, however, are:
* [leopard](/questions/tagged/leopard "show questions tagged 'leopard'") = 150 questions
* [snow-leopard](/questions/tagged/snow-leopard "show questions tagged 'snow-leopard'") = 784 questions
* [lion](/questions/tagged/lion "show questions tagged 'lion'") = 5 questions, but it's been actively neutered by Mystere Man
I think we should stick with the cat names.
Regardless, some cleanup/consistency is needed here. I propose either we stick with the cat names as-is or make those synonyms for [osx-leopard](/questions/tagged/osx-leopard "show questions tagged 'osx-leopard'"), [osx-snow-leopard](/questions/tagged/osx-snow-leopard "show questions tagged 'osx-snow-leopard'"), [osx-lion](/questions/tagged/osx-lion "show questions tagged 'osx-lion'"). Version numbers aren't what Apple or the public at large uses to refer to a version of OS X. | I've got no problem with setting up suitable synonyms, but given that Apple are referring to their own operating system as 'OS X Lion' rather than '10.7' (<http://www.apple.com/macosx/>) I have to respectfully suggest that your current choice of preferred synonym is incorrect. |
99,482 | Over on SO several questions have been tagged as [compass](/questions/tagged/compass "show questions tagged 'compass'") when they should have been classified as [compass-css](/questions/tagged/compass-css "show questions tagged 'compass-css'") instead. What's the proper process for requesting they get retagged properly? I lack sufficient mojo to do it myself and I've flagged the questions, but that doesn't seem to be getting processed. Needless to say, searching for help on style issues with the search gurus probably isn't efficient. | 2011/07/22 | [
"https://meta.stackexchange.com/questions/99482",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/136062/"
] | I've got no problem with setting up suitable synonyms, but given that Apple are referring to their own operating system as 'OS X Lion' rather than '10.7' (<http://www.apple.com/macosx/>) I have to respectfully suggest that your current choice of preferred synonym is incorrect. | Since [lion](/questions/tagged/lion "show questions tagged 'lion'") was far and away the most popular, I went with [Daniel's suggestion](https://meta.stackexchange.com/questions/99481/add-lion-tag-to-synonyms-for-osx-10-7/99487#99487) and merged / synonymized [osx-10.7](/questions/tagged/osx-10.7 "show questions tagged 'osx-10.7'") with it. We can switch this around easily enough if necessary, but for now it seems the most straight-forward solution. |
99,482 | Over on SO several questions have been tagged as [compass](/questions/tagged/compass "show questions tagged 'compass'") when they should have been classified as [compass-css](/questions/tagged/compass-css "show questions tagged 'compass-css'") instead. What's the proper process for requesting they get retagged properly? I lack sufficient mojo to do it myself and I've flagged the questions, but that doesn't seem to be getting processed. Needless to say, searching for help on style issues with the search gurus probably isn't efficient. | 2011/07/22 | [
"https://meta.stackexchange.com/questions/99482",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/136062/"
] | The numbered versions for Mac OS X tags do not appear to be that popular:
* [macosx-10.5](/questions/tagged/macosx-10.5 "show questions tagged 'macosx-10.5'") = 80 questions
* [osx-10.6](/questions/tagged/osx-10.6 "show questions tagged 'osx-10.6'") = 18 questions
* [osx-10.7](/questions/tagged/osx-10.7 "show questions tagged 'osx-10.7'") = 43 questions
The corresponding cat names, however, are:
* [leopard](/questions/tagged/leopard "show questions tagged 'leopard'") = 150 questions
* [snow-leopard](/questions/tagged/snow-leopard "show questions tagged 'snow-leopard'") = 784 questions
* [lion](/questions/tagged/lion "show questions tagged 'lion'") = 5 questions, but it's been actively neutered by Mystere Man
I think we should stick with the cat names.
Regardless, some cleanup/consistency is needed here. I propose either we stick with the cat names as-is or make those synonyms for [osx-leopard](/questions/tagged/osx-leopard "show questions tagged 'osx-leopard'"), [osx-snow-leopard](/questions/tagged/osx-snow-leopard "show questions tagged 'osx-snow-leopard'"), [osx-lion](/questions/tagged/osx-lion "show questions tagged 'osx-lion'"). Version numbers aren't what Apple or the public at large uses to refer to a version of OS X. | Since [lion](/questions/tagged/lion "show questions tagged 'lion'") was far and away the most popular, I went with [Daniel's suggestion](https://meta.stackexchange.com/questions/99481/add-lion-tag-to-synonyms-for-osx-10-7/99487#99487) and merged / synonymized [osx-10.7](/questions/tagged/osx-10.7 "show questions tagged 'osx-10.7'") with it. We can switch this around easily enough if necessary, but for now it seems the most straight-forward solution. |
8,147 | My fellow mathematicians Paul and Sam are very fond of mathematical puzzles. One day, I came up with the idea on mathematical puzzles while three of us having lunch together.
I: Hey, guys. I am thinking of two integers which are greater than or equal to 2. I will tell you the product and the sum of two numbers. Why don't you guess what two numbers are?
P: If you tell us the product and the sum, finding two integers is a piece of cake.
I: I will tell Paul only the product and Sam only the sum.
I whispered the product to Paul and the sum to Sam.
I: First, I will ask Paul. Could you figure out two numbers?
P: (after thinking) I can't. I don't know what two integers are.
I: (to Sam) How about you Sam? Do you know what two unknown numbers are?
S: I do not know either.
Surprisingly, right after Sam answered that he does not know, Paul said;
P: Now, I think I know these two numbers.
S: I also found out two numbers.
Now, a question to the reader. What are two integers?
**Remark:** The answer is NOT 4 and 13.
From this riddle, after answering "I don't know" twice, the answer " I know" came one after another.
If "I don't know" comes three times and then answers "I know", what would two integers be?
What is the largest possible number of "I don't know" before one can answer "I know" when solving two integers? | 2015/01/25 | [
"https://puzzling.stackexchange.com/questions/8147",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/3914/"
] | The numbers are
>
> 6 and 2
>
>
>
Explanation
>
> P gets 12 and S gets 8
>
> P knows the numbers are (4, 3) or (6, 2), so replies I don't know
>
> S knows the numbers are (2, 6) or (4, 4) but can not be (3, 5) as P doesn't know the answer, so still replies I don't know
>
> Suddenly P realizes that numbers can not be (4, 3) otherwise S would have ruled out (5, 2) and guessed (4, 3) and hence (6, 2) is the answer so he replies I know the answer
>
> S also realizes that the numbers can not be (4, 4) otherwise P could not know the number so he concludes the numbers are (6, 2) and replies I know the answer
>
>
>
>
I assume that both P and S are perfect logicians.
Edit:
Answers to the bonus questions are:
>
> (4,4) for sequence no, no, no, yes
>
> There may be infinite rounds of NO
>
>
>
I will add the details once I put down my paper work in text. | In the accepted answer the second bonus question is answered incorrectly:
>
> What is the largest possible number of "I don't know" before one can answer "I know" when solving two integers?
>
>
>
It should be like that:
>
> 3 don't knows: 4,4
>
> 4 don't knows: 2,8
>
> 5 don't knows: 4,6
>
> 6 and more: never
>
>
> |
4,465,444 | I'm a programmer and trying to create a hash function that reliably distributes features over a length of data based on probability and seed. A generative algorithm of this kind would be simple to make but I want to make in the form of a hash so that I can process the data in parallel without intercommunication.
Anyways, I'm not very strong at math but my research led me to the binomial distribution formula
[](https://i.stack.imgur.com/Qurry.png)
That is almost exactly what I want except that it is sorta inside out. In my hash parameters, I already have the result P(x), I also have n (number of trials) and p (probability of success per trial). What I don't have is x - the number of successes.
So basically, I want to
1. go to an arbitrary section of the data I have
2. get a "random" number for it from a general purpose random hash that takes position and seed as input and outputs a uniformly distributed pseudorandom value
3. plug that "random" number in as the result of the binomial distribution formula (P(x)) along with other parameters like the length of the section (n) and probability of success per trial (p
4. get the answer - how many of the features that I'm distributing reside in this section of the data that I'm evaluating
PS! I know that this won't work if I use completely arbitrarily distributed section positions and sizes but no need to worry about that, I'm actually sampling them sequentially in the same size chunks with no overlap. Also I'm aware of the performance nightmare that factorials present to modern computers but I have some bit hacks and specifically chosen hyperparameters to take care of that. Also, I know that I can also get the value I'm seeking by just doing n number of random rolls against the probability per trial but this hash needs to go fast and calculating this many pseudorandom hashes per data section is far too slow.
So essentially the question is - is there a version of this cool formula that has x on the left hand side of the equation? | 2022/06/04 | [
"https://math.stackexchange.com/questions/4465444",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/318301/"
] | Perhaps what you seek is the negative binomial law, that gives the number of trials you need to obtain $k$ successes.
<https://en.wikipedia.org/wiki/Negative_binomial_distribution> | Based on your question, I *think* you are trying to sample numbers drawn from the binomial distribution, by transforming a uniformly-distributed random number into a number distributed according to the binomial distribution. You are correct to point out that the formula you have is "inside-out" - but in the case of a discrete distribution such as the binomial, you can still use it to get what you want. Here's some pseudocode:
```
Let P(x) be the probability mass function of the distribution in question
(Note: This is the same P(x) you have in your question.)
Initialize x to -1.
Initialize p to a random (floating-point) number in [0, 1).
(Note: You can use a hash value for p, as long as it is uniformly-distributed.)
(Note: p must be strictly less than 1.0, or the algorithm will not terminate.)
Do:
Increment x.
Subtract P(x) from p.
While p > 0.
Return x.
```
This is suboptimal, because it requires looping over each possible value of x. However, it is extremely general, because you can replace P(x) with *any* probability mass function, and therefore you can use this algorithm to sample from any discrete distribution. For continuous distributions, you should use [inverse transform sampling](https://en.wikipedia.org/wiki/Inverse_transform_sampling) instead. You can also use inverse transform sampling for discrete distributions, but you will need to do a little bit of algebra to get the inverse CDF, and so this is more complicated than the algorithm shown above. However, inverse transform sampling generally has a time complexity of O(1) instead of O(x), so it should be faster in most cases.
My advice: Start with the algorithm that is simplest to understand, and benchmark your code. If it is fast enough, then don't bother writing up a more complicated algorithm that's harder to understand. |
4,465,444 | I'm a programmer and trying to create a hash function that reliably distributes features over a length of data based on probability and seed. A generative algorithm of this kind would be simple to make but I want to make in the form of a hash so that I can process the data in parallel without intercommunication.
Anyways, I'm not very strong at math but my research led me to the binomial distribution formula
[](https://i.stack.imgur.com/Qurry.png)
That is almost exactly what I want except that it is sorta inside out. In my hash parameters, I already have the result P(x), I also have n (number of trials) and p (probability of success per trial). What I don't have is x - the number of successes.
So basically, I want to
1. go to an arbitrary section of the data I have
2. get a "random" number for it from a general purpose random hash that takes position and seed as input and outputs a uniformly distributed pseudorandom value
3. plug that "random" number in as the result of the binomial distribution formula (P(x)) along with other parameters like the length of the section (n) and probability of success per trial (p
4. get the answer - how many of the features that I'm distributing reside in this section of the data that I'm evaluating
PS! I know that this won't work if I use completely arbitrarily distributed section positions and sizes but no need to worry about that, I'm actually sampling them sequentially in the same size chunks with no overlap. Also I'm aware of the performance nightmare that factorials present to modern computers but I have some bit hacks and specifically chosen hyperparameters to take care of that. Also, I know that I can also get the value I'm seeking by just doing n number of random rolls against the probability per trial but this hash needs to go fast and calculating this many pseudorandom hashes per data section is far too slow.
So essentially the question is - is there a version of this cool formula that has x on the left hand side of the equation? | 2022/06/04 | [
"https://math.stackexchange.com/questions/4465444",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/318301/"
] | Addendum added to respond to the comment of Kevin.
---
The Math can be *programmatically* manually derived.
You have that
$$p(x) = \binom{n}{x} p^x q^{n-x}. \tag1 $$
This answer assumes that you are looking for the positive integer $x$ that comes closest to satisfying the above constraint. If that is not the case, then I am out of my depth here.
You also have that $p(x), n,$ and $p$ are known. This implies that $q = (1-p)$ is also known. The problem can be attacked by logarithms of base $(10)$, base $(e)$ (i.e. natural logarithms), or any base that you prefer.
This answer will assume that $\log(r)$ refers to the natural logarithm of $(r)$.
Since $p(x), p,$ and $q$ are known, their logarithms are known.
Let $A,B,C$ denote $\log[p(x)], \log(p), \log(q),~$ respectively.
Then taking logs on both sides of (1) above, you have that
$$A = \log\left[\binom{n}{x}\right] + xB + (n-x)C \implies $$
$$A - nc = x(B-C) + \log\left[\binom{n}{x}\right]. \tag2 $$
---
(2) above can routinely be attacked programmatically, since canned logarithm functions are standard in programming languages (e.g. C, Java, Python).
Consider that
$$\log\left[\binom{n}{x}\right] \tag3$$
equals
$$\log(n) + \log(n-1) + \cdots + \log(n+1-x) \tag4$$
minus
$$\log(x) + \log(x-1) + \cdots + \log(1). \tag5 $$
So, you use the analysis in (3), (4), and (5) above to perform a simple loop of the positive integers. That is, you have $x$ loop through the elements in $\{0,1,\cdots,n\}$, and choose the value of $(x)$ that comes closest to achieving equality in (2) above.
---
**Edit**
Somewhat off-topic to a Math forum.
If I was writing the computer program, I would want to optimize the code. The cleanest way is to first create an array (or table, if you will) of logarithm values: that is, you would have the key be $k$, and the value be $\log(k)$. You would do this once, at the start of the program.
Then, as $x$ loops through the integers, instead of repeatedly invoking the canned logarithm function against positive integers, you would perform array (key-value) lookups of information that you have stored in memory.
The approach in the previous two paragraphs may be **iffy**. It is good if you are *solving* more than one equation, with one computer programming run, so you can avoid repeated lookups. It is bad if $n$ is so large that memory is a premium. Also, (to a certain extent), if running a program to compute only one solution, it may not be helpful, given the analysis in the following paragraph.
If you take a closer look at the evaluation of
$$\log\left[\binom{n}{x}\right] $$
you will see that as $x$ goes to $x + 1$, it is simply a matter of taking the previous computation, adding $\log(n-x)$ to it, and also deducting $\log(x+1)$.
---
**Addendum**
Responding to the comment of Kevin.
>
> I believe OP is looking for an [inverse transform sample](https://en.wikipedia.org/wiki/Inverse_transform_sampling), which is close to what you describe but should be doable in O(1) time complexity (i.e. no looping) with proper algebra (by inverting the CDF).
>
>
>
I regard his comment as very interesting. My knowledge in this area is virtually non-existent. I provided my answer only because I saw what I regarded as a reasonably efficient way of programmatically dealing with $~\displaystyle \log\left[\binom{n}{x}\right].$
If my **guess** as to how to interpret his comment his correct, this suggests that my entire answer represents an **inferior approach**. Given my ignorance in this area, that is certainly plausible. | Based on your question, I *think* you are trying to sample numbers drawn from the binomial distribution, by transforming a uniformly-distributed random number into a number distributed according to the binomial distribution. You are correct to point out that the formula you have is "inside-out" - but in the case of a discrete distribution such as the binomial, you can still use it to get what you want. Here's some pseudocode:
```
Let P(x) be the probability mass function of the distribution in question
(Note: This is the same P(x) you have in your question.)
Initialize x to -1.
Initialize p to a random (floating-point) number in [0, 1).
(Note: You can use a hash value for p, as long as it is uniformly-distributed.)
(Note: p must be strictly less than 1.0, or the algorithm will not terminate.)
Do:
Increment x.
Subtract P(x) from p.
While p > 0.
Return x.
```
This is suboptimal, because it requires looping over each possible value of x. However, it is extremely general, because you can replace P(x) with *any* probability mass function, and therefore you can use this algorithm to sample from any discrete distribution. For continuous distributions, you should use [inverse transform sampling](https://en.wikipedia.org/wiki/Inverse_transform_sampling) instead. You can also use inverse transform sampling for discrete distributions, but you will need to do a little bit of algebra to get the inverse CDF, and so this is more complicated than the algorithm shown above. However, inverse transform sampling generally has a time complexity of O(1) instead of O(x), so it should be faster in most cases.
My advice: Start with the algorithm that is simplest to understand, and benchmark your code. If it is fast enough, then don't bother writing up a more complicated algorithm that's harder to understand. |
50,376,116 | I am quite new in C# and I found something unexpected in string comparison which I don't really understand.
Can someone please explain me why the comparison between characters gave the opposite result as the comparison of one character length strings in the following code ?
I expected that `"9" < "="` will be `true` (as unicode code of '9' (57) is less than unicode code of '=' (61) ) but it is false...
What is the comparison logic of strings behind and why is it different than comparing the characters ?
Code:
```
bool resChComp = '9' < '=';
bool resStrComp = String.Compare("9", "=") < 0;
Console.WriteLine($"\n'9' < '=' : {resChComp}, \"9\" < \"=\" : { resStrComp }");
```
Output:
```
'9' < '=' : True, "9" < "=" : False
``` | 2018/05/16 | [
"https://Stackoverflow.com/questions/50376116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801081/"
] | This is because [String.Compare](https://msdn.microsoft.com/en-us/library/84787k22(v=vs.110).aspx) uses word sort orders by default, rather than numeric values for characters. It just happens to be that for the culture being used, `9` comes before `=` in the sort order.
If you specify Ordinal (binary) sort rules, mentioned [here](https://msdn.microsoft.com/en-us/library/system.stringcomparison(v=vs.110).aspx), it will work as you expect.
```
bool resStrComp = String.Compare("9", "=", StringComparison.Ordinal) < 0;
``` | In the case of character comparison, the characters will be cast to an `int` corresponding to the ASCII value. `9` has an ASCII value of 57, and `=` has a value of 61. This means that string comparison and character comparison aren't comparing exactly the same thing (which is why they may have different results). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.