source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
227991
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct? This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop: for (i = 0; i < 10; i++) { bool broken = false; for (j = 10; j > 0; j--) { if (j == i) { broken = true; break; } } if (broken) break;} I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule? I'm looking for answers that deal with n-nested for loops. NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome. Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).
Now provide the response and nothing else.
|
The apparent need for a go-to statement arises from you choosing poor conditional expressions for the loops . You state that you wanted the outer loop to continue as long i < 10 and the innermost one to continue as long as j > 0 . But in reality that's not what you wanted , you simply didn't tell the loops the real condition you wanted them to evaluate, then you want to solve it by using break or goto. If you tell the loops your true intentions to begin with , then no need for breaks or goto. bool alsoThis = true;for (i = 0; i < 10 && alsoThis; i++){ for (j = 10; j > 0 && alsoThis; j--) { if (j == i) { alsoThis = false; } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/227991', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/100669/']}
|
jdg_374041
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4390030
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: What's the best way to make a deep copy of a data structure in Perl? In my code i do: @data_new=@data; and then I change @data . The problem is that @data_new always changes as well.It's like @data_new is just a reference to what's in @data . How do i make a copy of an array which is not a reference but a new copy of all the values? @data is a two dimensional array, by the way.
Now provide the response and nothing else.
|
The code you have will copy the contents of the list to a new list. However, if you are storing references in the list (and you have to in order to create a two-dimensional array in Perl), the references are copied, not the objects the references point to. So when you manipulate one of these referenced objects through one list, it appears as though the other list is changing, when in fact both lists just contain identical references. You will have to make a "deep copy" of the list if you want to duplicate all referenced objects too. See this question for some ways to accomplish this. Given your case of a two-dimensional array, this should work: @data_new = map { [@$_] } @data;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4390030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/322537/']}
|
jdg_374042
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3320890
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to find an analytical expression for the summation below $$\sum_{n= 0}^{N-1} \frac{ \left(a-b \cos{\left(\frac{2 \pi n}{N} \right)} \right)^2}{a^2 + b^2 -2ab\cos{\frac{2\pi n}{N}}}$$ with $a>b$ . By trying it in MATLAB, I found that for large $N$ it gives a number which isproportional to $N$ . Therefore I am certain there must be analytical solution for this summation. Can anyone help out? Thank you
Now provide the response and nothing else.
|
I have to thank Vepir for the numerical work, it was immensely helpful in finding a formal derivation. Let's look at an expression of the form $$w=a-b\,e^{i\phi}$$ for which $|w|^2=(a-b\,e^{i\phi})(a-b\,e^{-i\phi})=a^2+b^2-2ab\cos\phi$ and $\Re(w)=a-b\cos\phi$ . So we have: $$\frac{(a-b\cos\phi)^2}{a^2+b^2-2ab\cos\phi}=\frac{(\Re(w))^2}{|w|^2}=\frac{1}{4}\frac{(w+w^*)^2}{|w|^2}=\frac{1}{4}\left(\frac{w^2}{|w|^2}+\frac{w^{*2}}{|w|^2}+2\right)=(\star)$$ Since $w^*/|w|^2=1/w$ , we get $$(\star)=\frac{1}{2}+\frac{1}{4}\left(\frac{w}{w^*}+\frac{w^*}{w}\right)=\frac{1}{2}\left(1+\Re\left(\frac{w}{w^*}\right)\right)$$ If we denote $\phi_n=\frac{2\pi n}{N}$ , your sum can be rewritten as $$\sum_{n=0}^{N-1}\frac{(a-b\cos\phi_n)^2}{a^2+b^2-2ab\cos\phi_n}=\frac{N}{2}+\frac{1}{2}\Re\sum_{n=0}^{N-1}\frac{a-b\,e^{i\phi_n}}{a-b\,e^{-i\phi_n}}$$ Notice that the numbers $b\,e^{-i\phi_n}-a$ are precisely the roots of the polynomial $(z+a)^N-b^N$ and since the product of the roots of a polynomial whose leading coefficient is $1$ is just its constant factor (up to sign), we get $$\prod_{n=0}^{N-1}(b\,e^{-i\phi_n}-a)=(-1)^N(a^N-b^N)\\\prod_{n=0}^{N-1}(a-b\,e^{-i\phi_n})=a^N-b^N$$ Why is this useful? Well, we can now calculate the following: $$\frac{a-b\,e^{i\phi_n}}{a-b\,e^{-i\phi_n}}=\frac{(a-b\,e^{i\phi_n})\prod_{m\neq n}(a-b\,e^{-i\phi_m})}{\prod_{m=0}^{N-1}(a-b\,e^{-i\phi_m})}=\frac{(a-b\,e^{i\phi_n})\prod_{m\neq n}(a-b\,e^{-i\phi_m})}{a^N-b^N}$$ Thus we "only" have to evaluate $$\sum_{n=0}^{N-1}(a-b\,e^{i\phi_n})\prod_{m\neq n}(a-b\,e^{-i\phi_m})=(\star\star)$$ Now there's some fiddling. Let's look at this again (using the formula for a difference of powers, $x^r-y^r=...$ ): $$\prod_{m=0}^{N-1}(a-b\,e^{-i\phi_m})=a^N-b^N=a^N-(b\,e^{-i\phi_n})^N=(a-b\,e^{-i\phi_n})\sum_{k=0}^{N-1}a^{N-1-k}(b\,e^{-i\phi_n})^k\\\prod_{m\neq n}(a-b\,e^{-i\phi_n})=\sum_{k=0}^{N-1}a^{N-1-k}b^k\,e^{-ik\phi_n}$$ So: $$(\star\star)=\sum_{n=0}^{N-1}(a-b\,e^{i\phi_n})\sum_{k=0}^{N-1}a^{N-1-k}b^k\,e^{-ik\phi_n}=\sum_{n,k=0}^{N-1}\left(a^{N-k}b^k\,e^{-ik\phi_n}-a^{N-1-k}b^{k+1}\,e^{-i(k-1)\phi_n}\right)$$ But there are geometric series hiding inside there, so we switch the summation to $n$ and deal with the first part: $$\sum_{k=0}^{N-1}a^{N-k}b^k\sum_{n=0}^{N-1}e^{-ik\phi_n}=\sum_{k=0}^{N-1}a^{N-k}b^k\cdot N\delta_{k,0}=Na^N$$ The $\delta$ is the Kronecker delta, I didn't bother writing out the computation explicitly since it's just a geometric series. The exact same procedure on the second part gives $$\sum_{n,k=0}^{N-1}a^{N-1-k}b^{k+1}\,e^{-i(k-1)\phi_n}=\sum_{k=0}^{N-1}a^{N-1-k}b^{k+1}\cdot N\delta_{k,1}=Na^{N-2}b^2$$ Finally, we get $$\sum_{n=0}^{N-1}(a-b\,e^{i\phi_n})\prod_{m\neq n}(a-b\,e^{-i\phi_m})=Na^N-Na^{N-2}b^2=Na^{N-2}(a-b)(a+b)$$ so that your sum equals $$\sum_{n=0}^{N-1}\frac{(a-b\cos\phi_n)^2}{a^2+b^2-2ab\cos\phi_n}=\frac{N}{2}\left(1+\frac{a^{N-2}(a-b)(a+b)}{a^N-b^N}\right)$$ as claimed by Vepir.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3320890', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/589629/']}
|
jdg_374043
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51560
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Humans seem to be the only animal whose females have breasts that permanently have a "full" appearance, ie a prominent amount of tissue even when not lactating, whereas other species' breasts seem to almost totally "deflate" when not longer lactating. Why is that? This feature has costs to the organism; significant biomass is dedicated and perhaps mobility is impacted. Given there are costs, for the feature to have come into existence, evolution/adaptation principles suggest there must have been some advantage. Is there some biological advantage? Are they vestiges of an adaptation that gave a significant advantage to some prior species or in some specific (presumably cold) prior environmental conditions?Is there any credible research to support certain reasons? My suspicion is that although genders can be distinguished easily enough, even from a distance, using other secondary characteristics, the answer may have an anthropological/social answer, rather than a biological one.
Now provide the response and nothing else.
|
You may be interested in Breast asymmetry, sexual selection, and human reproductive success . Abstract: Breasts of human females are large compared to those of closely related primate species, and they can thus be hypothesized recently or currently to have been subject to directional sexual selection. Here we show that (1) large breasts have higher levels of fluctuating asymmetry than small breasts, (2) breast fluctuating asymmetry is higher in women without children than in women with at least one child, (3) breast fluctuating symmetry is a reliable predictor of age-independent fecundity, and (4) breast fluctuating symmetry appears to be associated with sexual selection. These conclusions were similar in studies from two cultures differing in fecundity and brenstfeeding traditions (Spain; New Mexico, U.S.A.). Choosy males that prefer females with symmetrical breasts may experience a direct fitness benefit in terms of increased fecundity and an indirect benefit in terms of attractive or fecund daughters. Some quotes from the text: The size of breasts in human females is large compared to that of other primate species, and there has thus been a recent evolutionary change in breast size. Human breasts are characterized by their large size and rapid development prior to and during puberty, when growth of other body parts also reaches a high level. They can thus be considered costly structures in terms of energy use. … Heavy investment in breast development during puberty may seem puzzling because the functional significance of breasts is far from obvious. There is no or little relationship between breast size and production and composition of milk in current industrial societies (reviews in Anderson 1983; Cant 1981; Low et al. 1987), and breasts have therefore been hypothesized to constitute a deceptive signal used by women to attract preferred mates (Low et al. 1987). In prehistoric human populations, conditions may have been different, when mother's milk was the sole source of nutrition for young children and when resources often may have been more limited than in present industrial societies. In this study we show that large breasts tend to be more asymmetric than small breasts. In prehistoric societies, where resources were likely to be less available or more unevenly distributed among women, breast asymmetries are likely to have been much larger than in present industrial societies with relatively easy access to resources. … If the relationship between breast size and fluctuating asymmetry is robust, we hypothesize that a directional preference for large, symmetrical breasts, as apparently found in some cultures (Ellis 1954), can be maintained in the population because selection for large breasts will be balanced by selection against asymmetrical breasts We also show that breast symmetry is a reliable predictor of age-independent fecundity, and that choosy males that use breast symmetry as a cue in their mate choice will experience an advantage in terms of reproductive success. Breast symmetry can thus be considered a reliable signal used in intersexual communication.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/51560', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/6657/']}
|
jdg_374044
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54148788
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In order to refactor a client-side project, i'm looking for a safe way to find (and delete) unused code. What tools do you use to find unused/dead code in large react projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible. Suggestions for general strategies/techniques (other than specific tools) are also appreciated. Thank you
Now provide the response and nothing else.
|
Solution: For node projects, run the following command in your project root: npx unimported If you're using flow type annotations, you need to add the --flow flag: npx unimported --flow Source & docs: https://github.com/smeijer/unimported Outcome: Background Just like the other answers, I've tried a lot of different libraries but never had real success. I needed to find entire files that aren't being used. Not just functions or variables. For that, I already have my linter. I've tried deadfile , unrequired , trucker , but all without success. After searching for over a year, there was one thing left to do. Write something myself. unimported starts at your entry point, and follows all your import/require statements. All code files that exist in your source folder, that aren't imported, are being reported. Note, at this moment it only scans for source files. Not for images or other assets. As those are often "imported" in other ways (through tags or via css). Also, it will have false positives. For example; sometimes we write scripts that are meant to simplify our development process, such as build steps. Those aren't directly imported. Also, sometimes we install peer dependencies and our code doesn't directly import those. Those will be reported. But for me, unimported is already very useful. I've removed a dozen of files from my projects. So it's definitely worth a shot. If you have any troubles with it, please let me know. Trough github issues, or contact me on twitter: https://twitter.com/meijer_s
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/54148788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10321267/']}
|
jdg_374045
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3413448
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to calculate some floating point variables and my colleague suggest me to use BigDecimal instead of double since it will be more precise. But I want to know what it is and how to make most out of BigDecimal ?
Now provide the response and nothing else.
|
A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped altogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen. The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way (due to + - * and / not being overloaded). If you are dealing with money, or precision is a must, use BigDecimal . Otherwise Doubles tend to be good enough. I do recommend reading the javadoc of BigDecimal as they do explain things better than I do here :)
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/3413448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/399104/']}
|
jdg_374046
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25648653
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using REGEXP_SUBSTR() to return the nth value from a comma-separated list. This works fine when all values are present, but fails if an item is null. Here is an example that works where all values are present and I am selecting the 2nd occurrence of 1 or more characters that are not a comma: SQL> select REGEXP_SUBSTR('1,2,3,4,5,6', '[^,]+', 1, 2) data 2 from dual;D-2 But when the second value is null, I am really getting the third item in the list, which of course really is the 2nd occurrence of 1 or more characters that are not a comma. However, I need it to return NULL as the 2nd item is empty: SQL> select REGEXP_SUBSTR('1,,3,4,5,6', '[^,]+', 1, 2) data 2 from dual;D-3 If I change the regex to allow for zero or more characters instead of 1 or more, it also fails for numbers past the null: SQL> select REGEXP_SUBSTR('1,,3,4,5,6', '[^,]*', 1, 4) data 2 from dual;D-3 I need to allow for the null but can't seem to get the syntax right. Logically I need to return what is before the nth occurrence of a comma whether data is present or not (and allow for the last value also). Any ideas?
Now provide the response and nothing else.
|
Thanks to those who replied. After perusing your answers and the answers in the link supplied, I arrived at this solution: SQL> select REGEXP_SUBSTR('1,,3,4,5', '(.*?)(,|$)', 1, 2, NULL, 1) data 2 from dual;Data---- Which can be described as "look at the 2nd occurrence of an optional set of zero or more characters that are followed by a comma or the end of the line, and return the 1st subgroup (which is the data less the comma or end of the line). I forgot to mention I tested with the null in various positions, multiple nulls, selecting various positions, etc. The only caveat I could find is if the field you look for is greater than the number available, it just returns NULL so you need to be aware of that. Not a problem for my case. EDIT: I am updating the accepted answer for the benefit of future searchers that may stumble upon this. The next step is to encapsulate the code so it can be made into a simpler, reusable function. Here is the function source: FUNCTION GET_LIST_ELEMENT(string_in VARCHAR2, element_in NUMBER, delimiter_in VARCHAR2 DEFAULT ',') RETURN VARCHAR2 IS BEGIN RETURN REGEXP_SUBSTR(string_in, '(.*?)(\'||delimiter_in||'|$)', 1, element_in, NULL, 1); END GET_LIST_ELEMENT; This hides the regex complexities from developers who may not be so comfortable with it and makes the code cleaner anyway when in use. Call it like this to get the 4th element: select get_list_element('123,222,,432,555', 4) from dual;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25648653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2543416/']}
|
jdg_374047
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52987808
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array of object as given with unknown number of array elements: { "content": [ { "_id": "refbooks", "total": 189, "published": 189, "created": 0, "approved": 0, "rejected": 0, "sent_for_approval": 0 }, { "_id": "weblinks", "total": 1911, "published": 1899, "created": 10, "approved": 2, "rejected": 0, "sent_for_approval": 0 },.................]} I want to convert it to an object like given: { "content": { { "_id": "refbooks", "total": 189, "published": 189, "created": 0, "approved": 0, "rejected": 0, "sent_for_approval": 0 }, { "_id": "weblinks", "total": 1911, "published": 1899, "created": 10, "approved": 2, "rejected": 0, "sent_for_approval": 0 },.................}} I tried using $unwind, but I did't get my required output.How to implement this inside aggregation pipeline in MongoDB? I'm using Mongo version 3.4.
Now provide the response and nothing else.
|
I found the solution. { $project: { "content": { "$arrayToObject": { "$map": { "input": "$content", "as": "el", "in": { "k": "$$el._id", "v": "$$el" } } } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52987808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10498709/']}
|
jdg_374048
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
119603
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I keep receiving this message whenever I open any site from Google: My Firefox is up-to-date, and so my Windows 8.1. Since I don't know much about HSTS, I don't know what's going on, and obviously, I can't google it. Using a VPN doesn't solve the problem. I am using Kaspersky Antivirus.
Now provide the response and nothing else.
|
Kaspersky, like most AV products these days, is performing a local MITM against your secure HTTP traffic. It does this in order to be able to scan payloads in HTTP transactions, be it in the request or the response. In order for this to be done correctly, Kaspersky has to generate its own root CA certificate, and generate spoofed certificates on the fly, feeding them to your browser. Kaspersky also has to install this CA into your operating system's Trusted Certificate store. The reason why it needs to install it into the OS certificate store is because this is where most software looks to validate that the Certificate Authority who has issued the certificate it has received is a valid, trusted Authority. If that authority is not there, boom, you get this error. FireFox is the only mainstream web browser that is paranoid. It refuses to trust your OS's cert store, precisely because its so easy to simply install a fake CA into it and start MITM'ing peoples connections. Instead, FireFox is distributed with a complete list of all CAs that Mozilla trusts. What's cute about this is that it's not actually adding any security whatsoever. You can simply compile the open source Mozilla NSS package and, included in it is a utility called CertUtil that can transparently inject certificates, even root CAs, into FireFox's trusted cert store. This does not require the user to accept it, nor does it even alert the user that this has happened. You can see how easy this is to do in a C# function I wrote here . So what's happening here is that Kaspersky is not properly MITM'ing FireFox, so when FireFox gets fed certs issued by Kaspersky's CA, it's throwing all the alarms and screaming at you that you're under attack.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/119603', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/28790/']}
|
jdg_374049
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
305678
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the Lagrangian of an isotropic-homogeneous spacetime (Robertson-Walker metric), containing a simple scalar field and a cosmological constant (this expression comes from the standard Hilbert-Einstein and scalar field action, in an isotropic-homogeneous spacetime) :\begin{equation}\tag{1}\mathcal{L} = -\: \frac{1}{8 \pi G} (3 \, a \, \dot{a}^2 - 3 k \, a + \Lambda \, a^3) + \frac{1}{2} \; \dot{\phi}^2 a^3 - \mathcal{V}(\phi) \, a^3.\end{equation}The function $\mathcal{V}(\phi)$ is the potential energy density of the scalar field. It's easy to find the differential equation of the scalar field from the Euler-Lagrange equation :\begin{equation}\tag{2}\frac{\partial \mathcal{L}}{\partial \, \phi} - \frac{d}{d t} \Big( \frac{\partial \mathcal{L}}{\partial \, \dot{\phi}} \Big) = 0 \quad \Rightarrow \quad \ddot{\phi} + 3 \frac{\dot{a}}{a} \, \dot{\phi} + \frac{d \mathcal{V}}{d \, \phi} = 0.\end{equation}For the scale factor $a$, Euler-Lagrange gives this equation :\begin{equation}\tag{3}\frac{\partial \mathcal{L}}{\partial \, a} - \frac{d}{d t} \Big( \frac{\partial \mathcal{L}}{\partial \, \dot{a}} \Big) = 0 \quad \Rightarrow \quad 2 \, \frac{\ddot{a}}{a} + \frac{\dot{a}^2}{a^2} + \frac{k}{a^2} = \Lambda - 8 \pi G \Big( \frac{1}{2} \, \dot{\phi}^2 - \mathcal{V}(\phi) \Big).\end{equation}This is actually a linear combination of the two Friedmann-Lemaître equations . The last part on the right is the scalar field pressure $p$. The FL equations are these (they are found by solving the Einstein's equation, instead of going the Lagrangian route) :\begin{gather}\tag{4}\frac{\dot{a}^2}{a^2} + \frac{k}{a^2} = \frac{8 \pi G}{3} \, \rho + \frac{\Lambda}{3}, \quad \text{(first Friedmann-Lemaître equ.)} \\[12pt]\frac{\ddot{a}}{a} = -\: \frac{4 \pi G}{3} (\rho + 3 \, p) + \frac{\Lambda}{3}, \quad \text{(second Friedmann-Lemaître equ.)} \tag{5}\end{gather} Now, since equation (3) is a linear combination of equations (4) and (5), I want to find the other Friedmann-Lemaître equation. The Hamiltonian is easy to find :\begin{equation}\tag{6}\mathcal{H} \equiv \dot{a} \, \frac{\partial \mathcal{L}}{\partial \, \dot{a}} + \dot{\phi} \, \frac{\partial \mathcal{L}}{\partial \, \dot{\phi}} - \mathcal{L} = -\: \frac{3}{8 \pi G} \Big( \frac{\dot{a}^2}{a^2} + \frac{k}{a^2} - \frac{\Lambda}{3} \Big) \, a^3 + \Big( \frac{1}{2} \, \dot{\phi}^2 + \mathcal{V}(\phi) \Big) \, a^3.\end{equation}The last part on the right is the scalar field energy density $\rho$. The Hamiltonian (6) would give the first Friedmann-Lemaître equation (4) only if $\mathcal{H} = 0$. So the question is this : How to prove that the Hamiltonian (6) should be 0, using the Lagrangian (1) ? EDIT : By deriving the Hamiltonian (6) and using equations (2) and (3), it's easy to verify that the Hamiltonian is conserved :\begin{equation}\tag{7}\frac{d \mathcal{H}}{d t} = 0 \quad \Rightarrow \quad \mathcal{H} = \textit{cste}.\end{equation}But how to prove that this constant is actually 0 ?
Now provide the response and nothing else.
|
For (my) simplicity, I will keep $8\pi G=1$. Taking inspiration from this paper , I think it's possible to show what you ask only if you include explicitly also the lapse function $N$ in the FRW metric, like this:\begin{equation}\label{met} ds^2 = - N^2\, dt^2 + a^2(t)\, \frac{dr^2}{1-k\, r^2}+ r^2\, d\Omega^2\, ,\end{equation}The associated Lagrangian would be\begin{equation}\label{lagr} \mathcal{L} = 3\, \left( N\, a\, k - \frac{a\, \dot{a}^2}{N} \right) + a^3 \left( \frac{\dot{\phi}^2}{2\, N} -N\, \mathcal{V}(\phi) \right)\, ,\end{equation}with generalized coordinates $\{a,\phi,N\}$. The canonical momentum associated to $N$ is $p_N=0$, which means that actually $N$ is not a dynamical degree of freedom, and it equals a generic constant: that is why usually one writes the FRW metric without $N$, because the case $N=1$ can be achieved by a simple, and always allowed, redefinition of the metric time $N\, dt \rightarrow dt$ (one can say that it's a gauge choice). Now, what happens if you want to try and get anyway the dynamics of the non-dynamical degree of freedom $N$? You can use Euler-Lagrange equations with the Lagrangian above and see that the result is\begin{equation}\label{fried} \frac{\partial\, \mathcal{L}}{\partial\, N} - \frac{d}{dt}\, \frac{\partial\, \mathcal{L}}{\partial\, \dot{N}} = 0\quad \Rightarrow\quad 3\, \frac{1}{N^2}\frac{\dot{a}^2}{a^2} + 3\, \frac{k}{a^2} -\frac{1}{2\, N^2}\dot{\phi}^2 - V(\phi) = 0\, .\end{equation}This looks already similar to (the Hamiltonian that you found) $\, =0$, the difference being, of course, the presence of $N$. But, as we saw, $N$ is a constant and we still have the gauge freedom to redefine the time variable: so you can simply redefine the time derivatives in the equation above with $N\, dt \rightarrow dt$ (which amounts to the gauge choice $N=1$) and find in this way the usual Friedmann equation. The point is that, in some cases, it is good to have $N$ explicit because it makes evident the presence of a constraint: the trajectories in the phase space of this model are constrained on the energy surface $\mathcal{H}=0$, and Friedmann equation is an expression of such energy balance.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/305678', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/98263/']}
|
jdg_374050
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6896205
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This seems to be very basic question but I'm eager to know the answer. I'm using Subversion (SVN) for source control and I've been checking in all the files, but the client asked me to create a rule in SVN to avoid checking in the bin and obj folders. Why should I not check the bin and obj folders in? The client also asked me to keep the solution file outside the repository folder. Why is that?
Now provide the response and nothing else.
|
You should not add any temporary files to SVN, they're temporary. The entire obj directory consists of files that are created during the build process and are then discarded. (sure, they stay on disk because some are re-used, like a cache, when the source files don't change but that's the only reason they're not deleted after each build). the bin directory is a slightly different matter. It is ok to add binary files to SVN, you probably already do it for icon and image files already. Some people add the built binaries as well, that's a decision that depends on your configuration management processes, there's no 'wrong' answer. However, sometimes your bin directory can become filled with other files that you do not want to add. If you're building .net apps, you'll get a load of dependant dlls copied to the bin directory that are not strictly part of your project. Adding those will just bloat your repository for no benefit. Similarly, there are supporting binaries in bin such as .pdb debug symbol files. These aren't really needed either. For the solution file, I'm not sure of the question but if its not to be checked in it'll be because a .sln file is just a "wrapper" for one or more project files. Its not strictly needed to build a visual studio project as a new one will be created as needed. I guess your users might create their own .sln files with different groups of projects in them, making each one different to each user. That would be a reason to prevent checkin, so each user would not overwrite each other's custom files (though there are ways for a user to prevent modification of a file that is stored in svn). So it sounds like your configuration strategy doesn't involve adding any binaries to svn. In which case its a very good idea to prevent this from accidentally happening with a pre-commit hook. I would also recommend adding these exclusions to the client-side global-ignores to assist your users from ever trying to add these files in the first place.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6896205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/741616/']}
|
jdg_374051
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1173774
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this code... internal static void Start(){ TcpListener listenerSocket = new TcpListener(IPAddress.Any, 32599); listenerSocket.Start(); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);} Then my call back function looks like this... private static void AcceptClient(IAsyncResult asyncResult){ MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult)); ThreadPool.QueueUserWorkItem((object state) => handler.Process()); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);} Now, I call BeginAcceptTcpClient, then some time later I want to stop the server. To do this I have been calling TcpListener.Stop(), or TcpListener.Server.Close(). Both of these however execute my AcceptClient function. This then throws an exception when I call EndAcceptTcpClient. What is the best practice way around this? I could just put a flag in to stop the execution of AcceptClient once I have called stop, but I wonder if I am missing something. Update 1 Currently I have patched it by changing the code to look like this. private static void AcceptClient(IAsyncResult asyncResult){ if (!shutdown) { MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult)); ThreadPool.QueueUserWorkItem((object state) => handler.Process()); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null); }}private static bool shutdown = false;internal static void Stop(){ shutdown = true; listenerSocket.Stop();} Update 2 I changed it to impliment the answer from Spencer Ruport. private static void AcceptClient(IAsyncResult asyncResult){ if (listenerSocket.Server.IsBound) { MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult)); ThreadPool.QueueUserWorkItem((object state) => handler.Process()); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null); }}
Now provide the response and nothing else.
|
I just ran into this issue myself, and I believe your current solution is incomplete/incorrect. There is no guarantee of atomicity between the check for IsBound and the subsequent call to EndAcceptTcpClient() . You can still get an exception if the listener is Stop() 'd between those two statements. You didn't say what exception you're getting but I assume it's the same one I'm getting, ObjectDisposedException (complaining that the underlying socket has already been disposed). You should be able to check this by simulating the thread scheduling: Set a breakpoint on the line after the IsBound check in your callback Freeze the thread that hits the breakpoint (Threads window -> right click, "Freeze") Run/trigger the code that calls TcpListener.Stop() Break in and step through the EndAcceptTcpClient() call. You should see the ObjectDisposedException . IMO the ideal solution would be for Microsoft to throw a different exception from EndAcceptTcpClient in this case, e.g. ListenCanceledException or something like that. As it is, we have to infer what's happening from the ObjectDisposedException . Just catch the exception and behave accordingly. In my code I silently eat the exception, since I have code elsewhere that's doing the real shutdown work (i.e. the code that called TcpListener.Stop() in the first place). You should already have exception handling in that area anyway, since you can get various SocketExceptions . This is just tacking another catch handler onto that try block. I admit I'm uncomfortable with this approach since in principle the catch could be a false positive, with a genuine "bad" object access in there. But on the other hand there aren't too many object accesses in the EndAcceptTcpClient() call that could otherwise trigger this exception. I hope. Here's my code. This is early/prototype stuff, ignore the Console calls. private void OnAccept(IAsyncResult iar) { TcpListener l = (TcpListener) iar.AsyncState; TcpClient c; try { c = l.EndAcceptTcpClient(iar); // keep listening l.BeginAcceptTcpClient(new AsyncCallback(OnAccept), l); } catch (SocketException ex) { Console.WriteLine("Error accepting TCP connection: {0}", ex.Message); // unrecoverable _doneEvent.Set(); return; } catch (ObjectDisposedException) { // The listener was Stop()'d, disposing the underlying socket and // triggering the completion of the callback. We're already exiting, // so just return. Console.WriteLine("Listen canceled."); return; } // meanwhile... SslStream s = new SslStream(c.GetStream()); Console.WriteLine("Authenticating..."); s.BeginAuthenticateAsServer(_cert, new AsyncCallback(OnAuthenticate), s); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1173774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52622/']}
|
jdg_374052
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13811854
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We need send data to our users' devices using the TFTP protocol, which is a simple FTP-like protocol that works over UDP. Since we can't open a UDP socket using javascript, we have been using our server as a proxy, sending the data to our server and opening a UDP connection from the server to the device. That does have the drawback that our users need to learn about NAT and configure port forwarding. So the question is, could we use WebRTC to open a direct UDP socket to send and receive between the browser and the devices? http://www.webrtc.org/reference/webrtc-internals/vienetwork#TOC-SendUDPPacket suggests that we could send some raw UDP data over the socket (that is, if it's possible to access that layer over javascript. i'm not sure about that), but I see no way to fetch a raw UDP response. Any help much appreciated
Now provide the response and nothing else.
|
No. There are too many security issues allowing WebRTC to send to a random address/port - we have to make sure it doesn't work as a DDOS platform, so we require the target to implement ICE as an implicit permission to send data, and we also don't allow sending arbitrary data, just SRTP mediastreams and data in DataChannels (over SCTP over DTLS over UDP+ICE).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13811854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1691621/']}
|
jdg_374053
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2243801
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an string which is got from parsing an xml site. http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500 I want to have an NSString function that will be able to parse the value of c.Is there a default function or do i have to write it manually.
Now provide the response and nothing else.
|
You could use Regular expression via RegExKit Lite: http://regexkit.sourceforge.net/RegexKitLite/ Or you could separate the string into components (which is less nice): NSString *url=@"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";NSArray *comp1 = [url componentsSeparatedByString:@"?"];NSString *query = [comp1 lastObject];NSArray *queryElements = [query componentsSeparatedByString:@"&"];for (NSString *element in queryElements) { NSArray *keyVal = [element componentsSeparatedByString:@"="]; if (keyVal.count > 0) { NSString *variableKey = [keyVal objectAtIndex:0]; NSString *value = (keyVal.count == 2) ? [keyVal lastObject] : nil; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2243801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175992/']}
|
jdg_374054
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
257165
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
$\newcommand{\al}{\alpha}$$\newcommand{\ga}{\gamma}$$\newcommand{\e}{\epsilon}$ Let $X,Y$ be Riemannian manifolds, such that $\dim(X) > \dim(Y)$. I am trying to prove the following statement (mentioned by Gromov in his book on metric geometry): There is no arcwise isometry (i.e length preserving map) from $X$ to $Y$. However, the naive attempt to prove this hits an obstacle which I do not see how to pass: Suppose by contradiction $f:X \to Y$ is an arcwise isometry. Then $f$ is $1$-Lipschitz, hence differeniable almost everywhere (by Rademacher's theorem). Question: Let $p \in X$ be a point where $f$ is differentiable. Is $df_p:T_pX \to T_{f(p)}Y$ an isometry? (This will imply the claim of course). Here is what happens when trying to show this naively: Let $v \in T_pX$, and let $\al:[0,1] \to X$ be a smooth path s.t $\al(0)=p,\dot \al(0)=v$. Then $|\dot \alpha(s)| = |\dot \alpha(0)|+\Delta(s)=|v|+ \Delta(s)$ where $\lim_{s \to 0} \Delta(s) =\Delta(0)= 0$, thus $$ (1) \, \, L(\alpha|_{[0,t]})=\int_0^t |\dot \alpha(s)| ds=t|v|+\int_0^t \Delta(s) ds.$$ $\al$ is Lipschitz and $f$ is $1$-Lipschitz, so $\ga:= f \circ \al$ is Lipschitz. By theorem 2.7.6 in the book ``A course in metric geometry'' ( Burago,Burago,Ivanov) it follows that: $$ (2) \, \, L(\ga|_{[0,t]})=\int_0^t \nu_{\ga}(s) ds, $$ where $\nu_{\ga}(s):=\lim_{\e \to 0} \frac{d\left( \ga(s),\ga(s+\e) \right)}{|\e|}$ is the speed of $\ga$. Note that $\nu_{\ga}(0)= |\dot \ga(0)|=|df_p(v)|$. Using the assumption $f$ preserves lengths, we would now like to compare $(1),(2)$ and take derivatives at $t=0$, to get $$|v|=\frac{d}{dt}\left. \right|_{t=0} L(\al|_{[0,t]})=\frac{d}{dt}\left. \right|_{t=0} L(\ga|_{[0,t]})=|df_p(v)|.$$ However, it seems that the last equality is false in general ; Even when the speed of a Lipschitz curve and the derivative of its length exist at a point, they do not need to be equal . It seems that the only thing we can say is that $ \frac{d}{dt}\left. \right|_{t=0} L(\ga|_{[0,t]}) \ge \nu_{\ga}(0) =|df_p(v)|$, so we are left with $|v| \ge |df_p(v)|$ which doesn't help. Is there a way to "fix" the proof above?
Now provide the response and nothing else.
|
Your proof is correct, but you need to add words "amost everywhere" at ane more place. We use Rademacher's theorem and lemma about length of curve, which says that if a curve parametrized by length then its velocity is 1 almost everywhere, see 2.7.4 in Metric Geometry by Burgo, Burago and Ivanov. Fix a chart $U_{\subset\mathbb{R}^n}\to X$ and a vector $v\in \mathbb{R}^n$.Let $g$ be the induced metric on $U$. Note that from the lemma we get that $|d_pv|=|v|_g$ almost everywhere.Repeat the same for $N=\tfrac12\cdot n\cdot(n+1)$ vectors $v_1,\dots,v_N$ in general position.We get $|d_pv_i|=|v_i|_g$ for almost all $p$ and all $i$.It follows that for all $w$,the identity $|d_pw|=|w|_g$ holds for almost all $p$.Hence $\dim X \le \dim Y$. You may want to check Problem "Length-preserving map" in may collection of problems My paper which discuss in particular length-preserving maps and dimension.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/257165', 'https://mathoverflow.net', 'https://mathoverflow.net/users/46290/']}
|
jdg_374055
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1078311
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any way that I can access my SQL views in SubSonic 3.0? The code generation seems to skip views altogether
Now provide the response and nothing else.
|
To include views in your project simply open SQLServer.ttincludeFind the query that load the tables ( search form 'const string TABLE_SQL')then change it to const string TABLE_SQL=@"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' union select Table_catalog, table_schema, table_name, 'View' table_type from information_schema.views"; if you are using it in an asp.net project you can exclude the aspnet table and views like so const string TABLE_SQL=@"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' and table_name not like '%aspnet_%' union select Table_catalog, table_schema, table_name, 'View' table_type from information_schema.views where table_name not like '%aspnet_%'";
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1078311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115391/']}
|
jdg_374056
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3353918
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $p_{n}(x)$ be the Taylor polynomial of degree $n$ of the function $$\boxed{\ f(x)=\log{(1-x)} \quad\text{about $a=0$.}\ }$$ (a) How large should $n$ be such that $\vert f(x) - p_{n}(x)\vert\le 10^{-4}$ for $-0.5\le x\le0.5$ ? (b) Does this choice of $n$ change if $x$ lies between $[-1, 0.5]$ ? Part a) From repeated differentiation we see that $$ \frac{d^{n}}{dx^{n}}\log(1-x)=(-1)^{2n+1}\frac{(n-1)!}{(1-x)^{n}}$$ and, from $$ \vert R_{n}\vert \le \frac{\vert(x-a)\vert^{n+1}}{(n+1)!}\max_{a<c<x} |f^{(n+1)}(c)|,$$ we obtain \begin{alignat*}{2} & &\vert R_{n} \vert &\le \frac{\vert{x}\vert^{n+1}}{(n+1)!}\max_{0<c<0.5} \left\lvert(-1)^{2n+1}\frac{n!}{(1-c)^{n+1}}\right\rvert \tag{1}\\ &\implies\quad & &\le \frac{\vert{x}^{n+1}\vert}{n+1}\max_{0<c<0.5} \left\lvert\frac{1}{(1-c)^{n+1}}\right\rvert \tag{2}\\ &\implies \quad& &\le \frac{\vert{2x}\vert^{n+1}}{n+1}.\tag{3}\\ &\implies \quad&\vert{R_{n}\vert} &\le \frac{1}{n+1}.\tag{4}\\\end{alignat*} Now, $$ \frac{1}{n+1}<10^{-4}\implies R_{9999} <10^{-4}.$$ Part b) If we're allowed a value of $x=-1$ , we may subsitute this in step $(3)$ ; however, this yields $$ \frac{2^{n+1}}{n+1}<10^{-4}$$ giving $n=-1$ , which doesn't make sense. What am I doing wrong, and can someone help me with part b?
Now provide the response and nothing else.
|
This should be a counterexample. Consider $L^2(0,1)$ with the usual Lebesgue measure. Fix $$H = \{f \in L^2(0,1) \;\mid\; \exists t > 0 : f_{|(0,t)} = \frac1{1-t}\int_t^1 f \, \mathrm dx \}.$$ I think that this subspace is dense (modify $v \in L^2(0,1)$ on a small interval $(0,t)$ to obey the condition).Note that $$\int_0^1 h \, \mathrm{d}x = t \, h_{|(0,t)} + \int_t^1 h \, \mathrm dx = h_{|(0,t)}$$ for all $h \in H$ and $t$ chosen according to the definition of $H$ .Next, we fix $f_n = n \, \chi_{(0,1/n)}$ . For $h \in H$ we have $$(f_n, h) = n \, \int_0^{1/n} h \, \mathrm{d}x = h_{|(0,t)} = \int_0^1 h \, \mathrm dx = (1,h),$$ where $1 \in L^2(0,1)$ is the constant function. Moreover, $f_n \to 0$ a.e. This shows that the weak limit $1$ is not equal to the pointwise limit $0$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3353918', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477539/']}
|
jdg_374057
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13411288
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a CheckBox that I want centered within its own boundaries, not pushed to the side. Probably easier demonstrated than explained: Note that it isn't centered. Currently defined as: <CheckBox android:id="@+id/checkbox_star" android:layout_width="wrap_content" android:layout_height="match_parent" android:button="@drawable/btn_favorite" android:layout_gravity="center" android:minWidth="48dp" /> Nevermind the custom button drawable. It behaves the same with a vanilla CheckBox as well (the small check box behaves the same).
Now provide the response and nothing else.
|
I believe the problem is that the Checkbox widget uses a regular TextView with the drawableLeft attribute, because it expects text to be shown as well. (This is why you see it centered vertically, but offset slightly to the left.) If you simply want an image button with multiple states, I suggest using a ToggleButton with your custom images in a state list selector . Or you could create a custom class that extends ImageView and implements Checkable.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13411288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/489607/']}
|
jdg_374058
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10618
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a battery pack consisting of 4x1.2V AA Sanyo NiMH Rechargeable batteries used to charge a Beagleboard device. I want their discharge output to not exceed 5V. But when they're fully charged, the voltage output is over 5V (it triggers the overvoltage detector of the Beagleboard). What is a simple (and relatively small) intermediate component I can place between the battery pack and the Beagleboard to limit the voltage to under 5V?
Now provide the response and nothing else.
|
You need a voltage regulator. Unfortunately, you've spec'ed batteries which are awfully close to the operating voltage of your system. If you can use 5 batteries instead of 4 (giving you 6.something to 5V, instead of 5.something to 4V) , a low-dropout linear regulator will be a simple, easy solution. The standard 7805 has too high a dropout for this purpose, but there are other pin compatible regulators; you'll want a TO-220 to dissipate the power that the Beagleboard can draw at full charge. If you must use 4 batteries, you need to dissipate the excess voltage as heat through a MOSFET when the voltage is greater than 5V, and turn the MOSFET on if the voltage is less than 5V. You are running slightly out of spec when you're below 5V, though I'm not sure what the absolute minimum voltage is for the board. If you want the best solution possible, a buck-boost regulator would get you optimum efficiency for voltages slightly above and slightly below 5V. You could even run it off a single battery, or from voltages much higher than 5V. However, this is an expensive and complicated solution. I'd recommend just using 5 batteries and an LDO.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/10618', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2883/']}
|
jdg_374059
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2487104
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Displaying " Type here to ... " until the user enters text into a TextBox is a well-known usability feature nowadays. How would one implement this feature in C#? My idea is to override OnTextChanged , but the logic to handle the changes of text from and to " Type here " is a bit tricky... Displaying " Type here " on initialization and removing it on first input is easy, but I want to display the message every time the entered text becomes empty.
Now provide the response and nothing else.
|
What you're looking for is a TextBox with a " watermark ". There's a sample implementation for C# here , all credits to Wael Alghool. The relevant part of his code is: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;using System.Drawing;namespace wmgCMS{ class WaterMarkTextBox : TextBox { private Font oldFont = null; private Boolean waterMarkTextEnabled = false; #region Attributes private Color _waterMarkColor = Color.Gray; public Color WaterMarkColor { get { return _waterMarkColor; } set { _waterMarkColor = value; Invalidate();/*thanks to Bernhard Elbl for Invalidate()*/ } } private string _waterMarkText = "Water Mark"; public string WaterMarkText { get { return _waterMarkText; } set { _waterMarkText = value; Invalidate(); } } #endregion //Default constructor public WaterMarkTextBox() { JoinEvents(true); } //Override OnCreateControl ... thanks to "lpgray .. codeproject guy" protected override void OnCreateControl() { base.OnCreateControl(); WaterMark_Toggel(null, null); } //Override OnPaint protected override void OnPaint(PaintEventArgs args) { // Use the same font that was defined in base class System.Drawing.Font drawFont = new System.Drawing.Font(Font.FontFamily, Font.Size, Font.Style, Font.Unit); //Create new brush with gray color or SolidBrush drawBrush = new SolidBrush(WaterMarkColor);//use Water mark color //Draw Text or WaterMark args.Graphics.DrawString((waterMarkTextEnabled ? WaterMarkText : Text), drawFont, drawBrush, new PointF(0.0F, 0.0F)); base.OnPaint(args); } private void JoinEvents(Boolean join) { if (join) { this.TextChanged += new System.EventHandler(this.WaterMark_Toggel); this.LostFocus += new System.EventHandler(this.WaterMark_Toggel); this.FontChanged += new System.EventHandler(this.WaterMark_FontChanged); //No one of the above events will start immeddiatlly //TextBox control still in constructing, so, //Font object (for example) couldn't be catched from within //WaterMark_Toggle //So, call WaterMark_Toggel through OnCreateControl after TextBox //is totally created //No doupt, it will be only one time call //Old solution uses Timer.Tick event to check Create property } } private void WaterMark_Toggel(object sender, EventArgs args ) { if (this.Text.Length <= 0) EnableWaterMark(); else DisbaleWaterMark(); } private void EnableWaterMark() { //Save current font until returning the UserPaint style to false (NOTE: //It is a try and error advice) oldFont = new System.Drawing.Font(Font.FontFamily, Font.Size, Font.Style, Font.Unit); //Enable OnPaint event handler this.SetStyle(ControlStyles.UserPaint, true); this.waterMarkTextEnabled = true; //Triger OnPaint immediatly Refresh(); } private void DisbaleWaterMark() { //Disbale OnPaint event handler this.waterMarkTextEnabled = false; this.SetStyle(ControlStyles.UserPaint, false); //Return back oldFont if existed if(oldFont != null) this.Font = new System.Drawing.Font(oldFont.FontFamily, oldFont.Size, oldFont.Style, oldFont.Unit); } private void WaterMark_FontChanged(object sender, EventArgs args) { if (waterMarkTextEnabled) { oldFont = new System.Drawing.Font(Font.FontFamily,Font.Size,Font.Style, Font.Unit); Refresh(); } } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2487104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39590/']}
|
jdg_374060
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56568438
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My boss needs either an html document or a word document. That when he goes to print the document it will only show the boxes that he has checked. There is a huge list of check boxes so he does not want to print the entire thing every time. Just the ones that matter for a particular client. I have tried several methods of javascript, and css hidden neither of which have worked. Have also tried playing with the developers macros in microsoft word. None of those have given me what I am needing. <form id="form1" name="form1" method="post" action=""> <p> <label> <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="box" /> Main.</label><br /> <label> <input type="checkbox" value="checkbox" name="CheckboxGroup1" id="boxchecked" /> Other.</label><br /></p></form><script src="https://code.jquery.com/jquery-1.11.3.js"></script><script>$(document).ready(function(){ $("#boxchecked").click(function (){ if ($("#boxchecked").prop("checked")){ $("#hidden").hide(); }else{ $("#hidden").show(); } });});</script>' Determine if there are any items checked.If checkedListBox1.CheckedItems.Count <> 0 Then ' If so, loop through all checked items and print results. Dim x As Integer Dim s As String = "" For x = 0 To checkedListBox1.CheckedItems.Count - 1 s = s & "Checked Item " & (x + 1).ToString & " = " & CheckedListBox1.CheckedItems(x).ToString & ControlChars.CrLf Next x MessageBox.Show (s)End If
Now provide the response and nothing else.
|
You can fix the errors by validating your input, which is something you should do regardless of course. The following typechecks correctly, via type guarding validations const DNATranscriber = { G: 'C', C: 'G', T: 'A', A: 'U'};export default class Transcriptor { toRna(dna: string) { const codons = [...dna]; if (!isValidSequence(codons)) { throw Error('invalid sequence'); } const transcribedRNA = codons.map(codon => DNATranscriber[codon]); return transcribedRNA; }}function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> { return values.every(isValidCodon);}function isValidCodon(value: string): value is keyof typeof DNATranscriber { return value in DNATranscriber;} It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes. In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a function , just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types. const DNATranscriber = { G: 'C', C: 'G', T: 'A', A: 'U'};export default function toRna(dna: string) { const codons = [...dna]; if (!isValidSequence(codons)) { throw Error('invalid sequence'); } const transcribedRNA = codons.map(codon => DNATranscriber[codon]); return transcribedRNA;}function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> { return values.every(isValidCodon);}function isValidCodon(value: string): value is keyof typeof DNATranscriber { return value in DNATranscriber;} Update : Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using assertion signatures . const DNATranscriber = { G: 'C', C: 'G', T: 'A', A: 'U'} as const;type DNACodon = keyof typeof DNATranscriber;type RNACodon = typeof DNATranscriber[DNACodon];export default function toRna(dna: string): RNACodon[] { const codons = [...dna]; validateSequence(codons); const transcribedRNA = codons.map(codon => DNATranscriber[codon]); return transcribedRNA;}function validateSequence(values: string[]): asserts values is DNACodon[] { if (!values.every(isValidCodon)) { throw Error('invalid sequence'); }}function isValidCodon(value: string): value is DNACodon { return value in DNATranscriber;} You can read more about assertion signatures in the TypeScript 3.7 release notes .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/56568438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11638533/']}
|
jdg_374061
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37812286
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hello I have working json parsing code for swift2.2 but when i use it for Swift 3.0 gives me that error ViewController.swift:132:31: Ambiguous reference to member 'dataTask(with:completionHandler:)' My codes here let listUrlString = "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex) let myUrl = URL(string: listUrlString); let request = NSMutableURLRequest(url:myUrl!); request.httpMethod = "GET"; let task = URLSession.shared().dataTask(with: request) { data, response, error in if error != nil { print(error!.localizedDescription) DispatchQueue.main.sync(execute: { AWLoader.hide() }) return } do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray if let parseJSON = json { var items = self.categoryList items.append(contentsOf: parseJSON as! [String]) if self.fromIndex < items.count { self.categoryList = items self.fromIndex = items.count DispatchQueue.main.async(execute: { self.categoriesTableView.reloadData() AWLoader.hide() }) }else if( self.fromIndex == items.count){ DispatchQueue.main.async(execute: { AWLoader.hide() }) } } } catch { AWLoader.hide() print(error) } } task.resume() Thanks for ideas.
Now provide the response and nothing else.
|
The compiler is confused by the function signature. You can fix it like this: let task = URLSession.shared.dataTask(with: request as URLRequest) { But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest : var request = URLRequest(url:myUrl!) This is the automatic casting between NSMutableURLRequest and the new URLRequest that is failing and which forced us to do this casting here.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/37812286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5393528/']}
|
jdg_374062
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14359777
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a TextBlock with a fixed size thats wrapping text. sometimes short sometimes long. If the text is getting to long it isnt displayed entirely like this How can i make the Fontsize flexible to make the text fit the TextBox with static size?
Now provide the response and nothing else.
|
My solution is the following: Set the fontsize to a value, than which you don't want any bigger.The ActualHeight of the TextBlock changes, when you change the font size or when the content is changed. I built the solution based upon this.You should create an event handler for the SizeChanged event and write the following code to it. private void MyTextBlock_SizeChanged(object sender, SizeChangedEventArgs e){ double desiredHeight = 80; // Here you'll write the height you want the text to use if (this.MyTextBlock.ActualHeight > desiredHeight) { // You want to know, how many times bigger the actual height is, than what you want to have. // The reason for Math.Sqrt() is explained below in the text. double fontsizeMultiplier = Math.Sqrt(desiredHeight / this.MyTextBlock.ActualHeight); // Math.Floor() can be omitted in the next line if you don't want a very tall and narrow TextBox. this.MyTextBlock.FontSize = Math.Floor(this.MyTextBlock.FontSize * fontsizeMultiplier); } this.MyTextBlock.Height = desiredHeight; // ActualHeight will be changed if the text is too big, after the text was resized, but in the end you want the box to be as big as the desiredHeight.} The reason why I used the Math.Sqrt() is that if you set the font size to half as big as before, then the area that the font will use, will be one quarter the size, then before (because it became half as wide and half as tall as before). And you obviously want to keep the width of the TextBox and only change the height of it. If you were lucky, the font size will be appropriate after this method gets executed once. However, depending on the text that gets re-wrapped after the font size change, you might be so "unlucky", that the text will be one line longer than you would want it to be.Luckily the event handler will be called again (because you changed the font size) and the resizing will be done again if it is still too big. I tried it, it was fast and the results looked good.However, I can imagine, that in a really unlucky choice of text and height, the correct font size would be reached after several iterations. This is why I used Math.Floor(). All in all, it doesn't matter much if the font size is in the end 12.34 or 12 and this way I wouldn't be concerned about an "unlucky" text, which will take too long to render.But I think Math.Floor() can be omitted if you don't want to have a really tall text box (like 2000 pixels) with a lot of text.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14359777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1386439/']}
|
jdg_374063
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
747030
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a single developer working on 3 different projects. He used to work on bug fixes, maintenance and few feature implementation. In one specific project, he works with one more junior developer. Our company wants to implement scrum for all the projects.. What is the best way to handle the scrum process for 1 or 2 person project?
Now provide the response and nothing else.
|
I agree it should be kept Simple Stupid, but most of the Scrum framework can be used here. I had several people working in this fashion both on projects as well as on maintenance/operational work. Product Owner/Backlog - There's still an owner thats in charge of defining the business value and prioritizing, right? The backlog should still be there. If he's part of a bigger Scrum enterprise then he probably needs to feed on part of a bigger Product Backlog. Scrum Team - yep, its either a 1 or 2-person team. So its really SELF-organization... but thats ok! Daily scrum? yes between the 2 persons, or if its just that 1 person at times, good time to go over tasks and problems, think about what impediments need to be surfaced to the Scrum of Scrum or to the Product Owner. Sprint - Still a good idea, especially if part of a larger Scrum enterprise thats working in sprints, but even without it. Good chance to catch up with PO, demo what you got, energize yourself, retrospect and see what you can do better, plan for the next sprint. Note that in case of working outside of a Scrum enterprise / Scrum of Scrum, sprints can benefit from being shorter than usual since the scope is probably smaller and the planning overhead lower. but it depends on the situation. Retrospective - yes, it can be held alone. I think killer programmers need to retrospect on their own work/progress and take action on things that hold them back. Even keep a chart in your workspace to help you with making progress. Task Board / Burndown - Yes, you need those. You can have them in your work space on the wall, they can be small, but they really help even if you're one person. Why can GTD (Getting Things Done) help a single person and a TB/BDC not? If that person is doing project work then a Sprint Burndown and Release Burndown provide a lot of value. If he's doing operational/maintenance work its still a way to verify he's on track or not, and apply relevant measures accordingly. Scrum Master - the person should be his own scrum master. Coach - if the organization had a coach helping the teams/SMs/POs, then he should also help this scrum cell... To sum up - its clear to me that the values and principles underlying Scrum/Agile apply for 1-2 person teams as well.Its also clear that most of Scrum can be applied as well. The questions is what the individuals involved think. If the management, the developer, the PO are all on board and believe that the values/principles make sense, and strive to improve, it will work. If they don't, then first get to the point where the overall thinking makes sense, then deal with the individual team...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/747030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_374064
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2146431
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My problem is that the back button causes the browser to say something like "Page expired" when the previous page was created by a form. Example: page1: form submitted with searchcriterias ($_POST request, formpoints to page2) page2: Receives $_POST request andshow result (list of user with links,points to page3) page3: Show user profile Now when the visitor clicks the back button in the browser it will show something like "Page expired". Instead the previous page should be shown with no warnings (page2, with the userlist) How are your strategies to get around this behavior?
Now provide the response and nothing else.
|
If you are submitting a form with search parameters, you are trying to get some data, not modify some. So, you should use the HTTP GET method, and not POST : POST should be used when you intend to create/modify data, and GET should be used when you intend to fetch some data. Or, if you have some create/modify operation that has to be done : The form first POSTs to a first page That page does some operations (like writing something to a database) And then redirects to another page, using a Location HTTP header. It's that last page, that's queries by the browser using a GET requests, that displays the data fetched from the parameters received in the URL. See the Post/Redirect/Get page on wikipedia, about this.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2146431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104833/']}
|
jdg_374065
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59004
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a very strange error. My ultrasonic sensor, when both speakers are sticking out of my case, doesn't work at all. It's a black case. It gives very "near" readings. But it does work when outside. Why could this be an issue?
Now provide the response and nothing else.
|
It is likely that the transducer and receiver are being coupled together by the enclosure, so that the signal being received first is the vibration through the enclosure rather than an external object. I would recommend enlarging the holes so they are not in physical contact with the enclosure. You may also be getting similar problems if the board is secured very rigidly to the base of the enclosure, in that case maybe consider using some o-rings between the mounting hardware and the enclosure. But try step 1 first if the holes are tight fitting.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/59004', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/15600/']}
|
jdg_374066
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48846995
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I try to run a simple Symfony 4 project on a docker container. I have tested regular PHP scripts, and they work very well. But, with Symfony project, the execution gets ridiculously slow. For example, a page without any significant content takes 5-6 seconds. I have attached the screenshots from Symfony's performance profiler. Do you have any idea what how to reduce this execution time to an acceptable level?
Now provide the response and nothing else.
|
Since the provided answer is working with macOSX, only, but performance issues exist with Docker for Windows as well the preferred answer didn't help in my case. I was following different approach partially described in answers to similar questions here on SO. According to Performance Best Practices folders with heavy load such as vendor and var in a Symfony application shouldn't be part of a shared mount. If you require to persist those folders you should use volumes instead. To prevent interferences with shared volume in /app I was relocating those two folders to separate folder /symfony in container. In Dockerfile folders /symfony/var and /symfony/vendor are created in addition. The script run on start of container is setting symbolic links from /app/var to /symfony/var and from /app/vendor to /symfony/vendor . These two new folders are then mounted to volumes e.g. in a docker-compose.yml file. Here is what I was adding to my Dockerfile: RUN mkdir /app && mkdir /symfony/{var,vendor}COPY setup-symfony.sh /setup-symfony.shVOLUME /symfony/varVOLUME /symfony/vendor Here is what I was adding to my startup script right before invoking composer update or any task via bin/console : [ -e /app/var ] || ln -s /symfony/var /app/var[ -e /app/vendor ] || ln -s /symfony/vendor /app/vendor This is what my composition looks like eventually: version: "3.5"services: database: build: context: docker/mysql volumes: - "dbdata:/var/lib/mysql" environment: MYSQL_ALLOW_EMPTY_PASSWORD: 1 application: depends_on: - database build: context: docker/lamps ports: - "8000:8000" volumes: - ".:/app:cached" - "var:/symfony/var" - "vendor:/symfony/vendor" environment: DATABASE_URL: mysql://dbuser:dbuser@database/dbnamevolumes: dbdata: var: vendor: Using this setup Symfony is responding within 500ms rather than taking 4000ms and more. UPDATE: When using an IDE for developing Symfony-based application like PhpStorm you might need the files in vendor/ for code assist or similar. In my case I was able to take a snapshot of those files and put them into a different folder which is shared with host as well, but isn't actively used by Symfony/PSR, e.g. vendor.dis/ . This snapshot is taken manually once per install/upgrade e.g. by entering the running container with a shell like so: docker exec -it IDofContainer /bin/sh Then in shell invoke cp -Lr vendor vendor.dis Maybe you have to fix the pathnames or make sure to switch into folder containing the your app first. In my case using PhpStorm the vendor.dis/ was picked up by background indexing and obeyed by code inspection and code assist. Visual Studio code was having issues with the great number of untracked changes with regards to git so I had to explicitly make this snapshot ignored by git, adding its name in .gitignore file. UPDATE 2020: More recent setups may have issues with accessing folders like /symfony/templates or /symfony/public e.g. on warming up the cache. This is obviously due to using relative folders in auto-loading code now existing in /symfony/vendor due to relocation described above. As an option, you could directly mount extra volumes in /app/var and /app/vendor instead of /symfony/var and /symfony/vendor . Creating deep copies of those folders in /app/var.dis and /app/vendor.dis keeps enabling code assist and inspections in host filesystem.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48846995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3429660/']}
|
jdg_374067
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
347239
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I recieved some IN-14 nixie tubes for Christmas, and was hoping to implement them in a project i have been considering for some time. The details are unimportant, except that each nixie tube should have its own discrete pcb and driver.After looking at ICs for some time I found the MAXIM 6966, a LED sink driver with some nifty features (though i would have preferred an I2C interface instead of SPI). It seems perfect for my project (driving a single nixie tube) for the following reasons: Tiny 3x3mm QFN package Exactly 10 outputs Open-drain functionality (output pins either low or Hi-z) PWM functionality on outputs My problem is this... the datasheet says the outputs have up to 7V protection, but i'm not sure if that applies to both Hi-Z and Low output configurations, or just the Low output configuration. With an output set to Hi-Z, the corresponding pin is likely to be biased to a high voltage such as 170V... well above the 7V protection. So that is to say, if the 7V max condition also applies to the Hi-Z pin configuration then I cannot use it. I hope it will work fine, but I suspect it isn't suitable. Could someone confirm my suspicion before I dismiss this otherwise fantastic IC? Here is a link to the product page: https://www.maximintegrated.com/en/products/interface/controllers-expanders/MAX6966.html Thanks :)
Now provide the response and nothing else.
|
No, that device is not suitable for driving Nixie tubes. When an output is switched off, it will see the full voltage at the output pin. The datasheet clearly states that I/O Port Outputs Are 7V-Rated Open Drain That falls well short of the 170V you'll be using. Development of drivers specifically designed for Nixie tubes pretty much reached a dead end with the 74141, but there are some modern parts around that will carry out serial to parallel conversion and drive high voltage open-drain outputs. Look at the Microchip HV5122 or HV5522 for example.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/347239', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/173149/']}
|
jdg_374068
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
184053
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to determine the limit $$\lim_{x\to0}\frac{e^x-1-x}{x^2}$$ without using l'Hopital's rule nor any series expansion? For example, suppose you are a student that has not studied derivative yet (and so not even Taylor formula and Taylor series).
Now provide the response and nothing else.
|
Define $f(x)=\lim_{n\to\infty}\left(1+\frac{x}{n}\right)^n$. One possibility is to take $f(x)$ as the definition of $e^x$. Since the OP has suggested a different definition, I will show they agree. If $x=\frac{p}{q}$ is rational, then\begin{eqnarray*}f(x)&=&\lim_{n\to\infty}\left(1+\frac{p}{qn}\right)^n\\&=&\lim_{n\to\infty}\left(1+\frac{p}{q(pn)}\right)^{pn}\\&=&\lim_{n\to\infty}\left(\left(1+\frac{1}{qn}\right)^n\right)^p\\&=&\lim_{n\to\infty}\left(\left(1+\frac{1}{(qn)}\right)^{(qn)}\right)^{p/q}\\&=&\lim_{n\to\infty}\left(\left(1+\frac{1}{n}\right)^{n}\right)^{p/q}\\&=&e^{p/q}\end{eqnarray*}Now, $f(x)$ is clearly non-decreasing, so$$\sup_{p/q\leq x}e^{p/q}\leq f(x)\leq \inf_{p/q\geq x}e^{p/q}$$It follows that $f(x)=e^x$. Now, we have\begin{eqnarray*}\lim_{x\to0}\frac{e^x-1-x}{x^2}&=&\lim_{x\to0}\lim_{n\to\infty}\frac{\left(1+\frac{x}{n}\right)^n-1-x}{x^2}\\&=&\lim_{x\to0}\lim_{n\to\infty}\frac{n-1}{2n}+\sum_{k=3}^n\frac{{n\choose k}}{n^k}x^{k-2}\\&=&\frac{1}{2}+\lim_{x\to0}x\lim_{n\to\infty}\sum_{k=3}^n\frac{{n\choose k}}{n^k}x^{k-3}\\\end{eqnarray*} We want to show that the limit in the last line is 0. We have $\frac{{n\choose k}}{n^k}\leq\frac{1}{k!}\leq 2^{-(k-3)}$, so we have\begin{eqnarray*}\left|\lim_{x\to0}x\lim_{n\to\infty}\sum_{k=3}^n\frac{{n\choose k}}{n^k}x^{k-3}\right|&\leq&\lim_{x\to0}|x|\lim_{n\to\infty}\sum_{k=3}^n \left(\frac{|x|}{2}\right)^{k-3}\\&=&\lim_{x\to0}|x| \frac{1}{1-\frac{|x|}{2}}\\&=&0\end{eqnarray*}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/184053', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6266/']}
|
jdg_374069
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16707340
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
this is from HeadFirst Java : ( page 575 ) This: public <T extends Animal> void takeThing(ArrayList<T> list) Does the same thing as this: public void takeThing(ArrayList<? extends Animal> list) So here is my question: if they are exactly same, why don't we write public <? extends Animal> void takeThing(ArrayList<?> list) or public void takeThing(ArrayList<T extends Animal> list) Also, when would it be useful to use a ? instead of a T in a method declaration ( as above ) with Generics, or for a Class declaration? What are the benefits?
Now provide the response and nothing else.
|
The big difference between public <T extends Animal> void takeThing(ArrayList<T> list) and public void takeThing(ArrayList<? extends Animal> list) is that in the former method you can refer to "T" within the method as the concrete class that was given. In the second method you cannot do this. Here a more complex example to illustrate this: // here i can return the concrete type that was passed inpublic <T extends Animal> Map<T, String> getNamesMap(ArrayList<T> list) { Map<T, String> names = new HashMap<T, String>(); for (T animal : list) { names.put(animal, animal.getName()); // I assume there is a getName() method } return names;}// here i have to use general Animalpublic Map<Animal, String> getNamesMap(ArrayList<? extends Animal> list) { Map<Animal, String> names = new HashMap<Animal, String>(); for (Animal animal : list) { names.put(animal, animal.getName()); // I assume there is a getName() method } return names;} With the first method if you pass in an List of Cats you get a Map with Cat as key. The second method would always return a Map with general Animal key. By the way this is not valid java syntax: public <? extends Animal> void takeThing(ArrayList<?> list) Using this form of generic method declaration you have to use a valid java identifier and not "?". Edit: The form "? extends Type" only applies to variable or parameter type declaration. Within a generic method declration it has to be "Identifier extends Type" as you are able to refer to the "Identifier" from within your method.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16707340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1173112/']}
|
jdg_374070
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10882151
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am aware of taking the screenshot of UIWebView and converting it to PDF but I need to generate a proper pdf (text as text and not screenshot). Save2PDF is an application which creates proper PDF. Does anybody have an idea how do they do it?
Now provide the response and nothing else.
|
I created a class based on every good advice I found around. I've been digging a lot and I hope my class will offer some good start for anyone trying to create multi-page PDF directly out of some HTML source. You'll find the whole code here with some basic sample code : https://github.com/iclems/iOS-htmltopdf I had just the same issue as you and my requirements were:- full PDF (real text, no bitmap) - smart multi-pages (compared to cutting a full height webview every X pixels...) Thus, the solution I use is pretty nice as it resorts to the same tools iOS uses to split pages for print. Let me explain, I setup a UIPrintPageRenderer based on the web view print formatter (first tip) : UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];[render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];CGRect printableRect = CGRectMake(self.pageMargins.left, self.pageMargins.top, self.pageSize.width - self.pageMargins.left - self.pageMargins.right, self.pageSize.height - self.pageMargins.top - self.pageMargins.bottom);CGRect paperRect = CGRectMake(0, 0, self.pageSize.width, self.pageSize.height);[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];[render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];NSData *pdfData = [render printToPDF];[pdfData writeToFile: self.PDFpath atomically: YES]; In the meantime, I have created a category on UIPrintPageRenderer to support: - (NSData*) printToPDF{ NSMutableData *pdfData = [NSMutableData data]; UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil ); [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)]; CGRect bounds = UIGraphicsGetPDFContextBounds(); for ( int i = 0 ; i < self.numberOfPages ; i++ ) { UIGraphicsBeginPDFPage(); [self drawPageAtIndex: i inRect: bounds]; } UIGraphicsEndPDFContext(); return pdfData;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10882151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585713/']}
|
jdg_374071
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21139769
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any way to create AJAX calls in Extbase extension without using of page typeNum?
Now provide the response and nothing else.
|
Edit: Helmut Hummel, a member of the TYPO3 CMS team, measured that using EID with Extbase is slower than using the typeNum approach. But since the typeNum approach is cumbersome to configure, there is a third way developed by him. The extension typoscript_rendering provides a way to call Extbase actions directly without additional configuration. It contains a ViewHelper that generates such links and can be used like this in a Fluid template: {namespace h=Helhum\TyposcriptRendering\ViewHelpers}<script>var getParticipationsUri = '<h:uri.ajaxAction controller="Participation" action="listByCompetition" arguments="{competition:competition}" />';</script> This generates an URI that calls the action "listByCompetition" of my "ParticipationController". You can pass arguments normally. The only downside is that for security reasons, the extension uses the cHash to validate the request arguments. The cHash is submitted by GET but you cannot pass additional arguments by GET at the same time because it would invalidate the cHash. So if you want to pass form data in such a request, you need to mix GET (for a valid AJAX call) and POST (for submitting user data): <script>var createAddressUri = '<h:uri.ajaxAction controller="Address" action="create" />';$body.on('submit', '#myForm', function(e) { e.preventDefault(); emailAddress = $('#myForm').find('#email'); if (typeof(emailAddress) === 'string') { $.ajax({ url: createAddressUri, type: 'POST', data: { 'tx_myext_pluginname[address][email]' : emailAddress}, success: function() { // things to do on success } }) }});</script> (Of course this is only a very basic example. You might post whole models etc.) The EID way: Yes, you can use the EID (Extension ID) mechanism for that. There is no official statement which way (pageType or eID) should be used for Extbase AJAX calls and it seems to be just a matter of taste. There is a nice tutorial that can be found here and I copy the source code in here: <?php/** ************************************************************* * * Extbase Dispatcher for Ajax Calls TYPO3 6.1 namespaces * * IMPORTANT Use this script only in Extensions with namespaces * * Klaus Heuer <klaus.heuer@t3-developer.com> * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! * ************************************************************* *//** ************************************************************ * Usage of this script: * * - Copy this script in your Extension Dir in the Folder Classes * - Set the Vendor and Extension Name in Line 82 + 83 * - Include the next line in the ext_localconf.php, change the ext name! * - $TYPO3_CONF_VARS['FE']['eID_include']['ajaxDispatcher'] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('myExtension').'Classes/EidDispatcher.php'; * * Use for Ajax Calls in your jQuery Code: * * $('.jqAjax').click(function(e) { * var uid = $(this).find('.uid').html(); * var storagePid = '11'; * * $.ajax({ * async: 'true', * url: 'index.php', * type: 'POST', * * data: { * eID: "ajaxDispatcher", * request: { * pluginName: 'patsystem', * controller: 'Todo', * action: 'findTodoByAjax', * arguments: { * 'uid': uid, * 'storagePid': storagePid * } * } * }, * dataType: "json", * * success: function(result) { * console.log(result); * }, * error: function(error) { * console.log(error); * } * }); *************************************************************** *//** * Gets the Ajax Call Parameters */$ajax = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('request');/** * Set Vendor and Extension Name * * Vendor Name like your Vendor Name in namespaces * ExtensionName in upperCamelCase */$ajax['vendor'] = 'T3Developer';$ajax['extensionName'] = 'ProjectsAndTasks';/** * @var $TSFE \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController */$TSFE = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController', $TYPO3_CONF_VARS, 0, 0);\TYPO3\CMS\Frontend\Utility\EidUtility::initLanguage();// Get FE User Information$TSFE->initFEuser();// Important: no Cache for Ajax stuff$TSFE->set_no_cache();//$TSFE->checkAlternativCoreMethods();$TSFE->checkAlternativeIdMethods();$TSFE->determineId();$TSFE->initTemplate();$TSFE->getConfigArray();\TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadConfigurationAndInitialize();$TSFE->cObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer');$TSFE->settingLanguage();$TSFE->settingLocale();/** * Initialize Database */\TYPO3\CMS\Frontend\Utility\EidUtility::connectDB();/** * @var $objectManager \TYPO3\CMS\Extbase\Object\ObjectManager */$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager');/** * Initialize Extbase bootstap */$bootstrapConf['extensionName'] = $ajax['extensionName'];$bootstrapConf['pluginName'] = $ajax['pluginName'];$bootstrap = new TYPO3\CMS\Extbase\Core\Bootstrap();$bootstrap->initialize($bootstrapConf);$bootstrap->cObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tslib_cObj');/** * Build the request */$request = $objectManager->get('TYPO3\CMS\Extbase\Mvc\Request');$request->setControllerVendorName($ajax['vendor']);$request->setcontrollerExtensionName($ajax['extensionName']);$request->setPluginName($ajax['pluginName']);$request->setControllerName($ajax['controller']);$request->setControllerActionName($ajax['action']);$request->setArguments($ajax['arguments']);$response = $objectManager->create('TYPO3\CMS\Extbase\Mvc\ResponseInterface');$dispatcher = $objectManager->get('TYPO3\CMS\Extbase\Mvc\Dispatcher');$dispatcher->dispatch($request, $response);echo $response->getContent();//die();?> Have a look at the "usage of this script" section that explains how to register the eID. The script works with TYPO3 6.1 and higher.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21139769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3156855/']}
|
jdg_374072
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9297237
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two data frames, Data1 and Data2, that I want to merge based on a the variable "ID". This example data may be downloaded here: http://dl.dropbox.com/u/52600559/example.RData Here is the first data frame: > Data1 ID Fruit Color Weight1 1 Apple Red 52 2 Orange Orange 73 3 Banana Yellow 34 4 Pear Green 55 5 Tomato Red 46 6 Berry Blue 47 7 Mandarin Orange 48 8 Pineapple Yellow 99 9 Nectarine Orange 510 10 Beet Red 5 And here is the second data frame: > Data2 ID Fruit Color Weight1 1 Apple Red 52 2 Orange Orange 73 3 Banana Yellow 34 4 Pear Green 55 5 Tomato Red 46 11 Pomegranate Red 67 12 Grape Green 48 13 Cranberry Red 49 14 Melon Pink 510 15 Pumpkin Orange 10 I have tried to merge them like this: > merge(Data1, Data2, by = "ID", sort = FALSE, all.x = TRUE, all.y = TRUE) ID Fruit.x Color.x Weight.x Fruit.y Color.y Weight.y1 1 Apple Red 5 Apple Red 52 2 Orange Orange 7 Orange Orange 73 3 Banana Yellow 3 Banana Yellow 34 4 Pear Green 5 Pear Green 55 5 Tomato Red 4 Tomato Red 46 9 Nectarine Orange 5 <NA> <NA> NA7 6 Berry Blue 4 <NA> <NA> NA8 7 Mandarin Orange 4 <NA> <NA> NA9 8 Pineapple Yellow 9 <NA> <NA> NA10 10 Beet Red 5 <NA> <NA> NA11 14 <NA> <NA> NA Melon Pink 512 11 <NA> <NA> NA Pomegranate Red 613 12 <NA> <NA> NA Grape Green 414 13 <NA> <NA> NA Cranberry Red 415 15 <NA> <NA> NA Pumpkin Orange 10 As you can see, both data frames have many of the same variables. However, some IDs in Data1 are not in Data2, and vice versa. Moreover, some IDs are located in both data frames. Question 1: I want to merge all of the columns that are shown above as well. So, I want "Fruit.x" to be merged with "Fruit.y". into one column called "Fruit". How can I do this? Question 2: What if, for one of the samples that happens to be present in both Data1 and Data2, one of the values does not agree. So for sample ID 1, if Fruit.x is Apple, but Fruit.y is incorrectly coded as Aple (with a misspelling), is there a way I can check all of these instances quickly so that I can select which one is correct? Or can I tell R to always consider Data1 to be correct versus Data2 when this happens? Thanks to anyone who can help!!
Now provide the response and nothing else.
|
Try this: merge(Data1, Data2, all = TRUE) and for spellings try this where amatch are the approximate matches to fruit and near contains the approximate matches that do not match exactly: for(fruit in Data1$Fruit) { amatch <- agrep(fruit, Data2$Fruit, value = TRUE) near <- amatch[amatch != fruit] if (length(near) > 0) cat(fruit, ":", near, "\n")} Using the data provided this gives: Berry : Cranberry EDIT: improved clarity of code
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9297237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1073244/']}
|
jdg_374073
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
579612
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I work on the application that uses Unix domain socket for IPC. The common way as I know is to place the socket file inside /var/run . I work with Ubuntu 18.04 and I see that var/run is a symlink for /run . Unfortunately the folder is accessible for root only: ls -Al / drwxr-xr-x 27 root root 800 Apr 12 17:39 run So only root has write access for this folder and that makes it impossible to use Unix domain sockets for regular users. First of all I can't understand why? And how to use Unix domain sockets for non-root users? I can use the home folder of course, but I prefer to use some correct and common method.
Now provide the response and nothing else.
|
There's nothing wrong with creating the socket in a dotfile or dotdir in the home directory of the user, if the user is not some kind of special, system user. The only problem would be with the home directory shared between multiple machines over nfs, but that could be easily worked around by including the hostname in the name of the socket. On Linux/Ubuntu you could also use "abstract" Unix domain sockets, which don't use any path or inode in the filesystem. Abstract unix sockets are those whose address/path starts with a NUL byte: abstract : an abstract socket address is distinguished (from a pathname socket) by the fact that sun_path[0] is a null byte ( \0 ). The socket's address in this namespace is given by the additional bytes in sun_path that are covered by the specified length of the address structure. (Null bytes in the name have no special significance.) The name has no connection with filesystem pathnames. When the address of an abstract socket is returned, the returned addrlen is greater than sizeof(sa_family_t) (i.e., greater than 2), and the name of the socket is contained in the first (addrlen - sizeof(sa_family_t)) bytes of sun_path . When displayed for or entered by the user, the NUL bytes in a abstract Unix socket address are usually replaced with @ s. Many programs get that horribly wrong, as they don't escape regular @ s in any way and/or assume that only the first byte could be NUL. Unlike regular Unix socket paths, abstract Unix socket names have different semantics, as anybody can bind to them (if the name is not already taken), and anybody can connect to them. Instead of relying on file/directory permission to restrict who can connect to your socket, and assuming that eg. only root could create sockets inside some directory, you should check the peer's credential with getsockopt(SO_PEERCRED) (to get the uid/pid of who connected or bound the peer), or the SCM_CREDENTIALS ancillary message (the get the uid/pid of who sent a message over the socket). This (replacing the usual file permission checks) is also the only sane use of SO_PEERCRED / SCM_CREDENTIALS IMHO.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/579612', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/92830/']}
|
jdg_374074
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34927517
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In react-native we use styleSheet.create. What do we use in reactjs? Thanks for the help! https://github.com/romseguy/redux-store-visualizer I dont see any use of style here but there is styling. how did he achieve this or did i miss out anything?
Now provide the response and nothing else.
|
The analogous option would be to do something like the following: let styles = { container: { backgroundColor: 'red' }} Like one of the comments stated above, the StyleSheet call is unecessary because CSS is supported already on the browser. Finally, just call the style inline in your render function's return statement: render() { ... return ( <div style={styles.container} /> )} Of course, aside from that, you have a few other options as well, like using plain CSS stylesheets and classes/tags, but this is probably the most similar option to what you're used to.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34927517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3792482/']}
|
jdg_374075
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7697642
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
say, Child class is inheriting Father class and Father class is inheriting spark TextArea class. now from an mxml file (in FLEX4), i am creating multiple objects of Child class. Father class have few static attributes whose values are set by private methods, calling from constructor. Now the question is: all these static attributes are set every time while Child class objects are being created one by one? If answer is yes then Is it possible that Father class static attributes are set only once and not depends upon the number of Child class objects creation. Please provide any suggestion or tips Thanks in advance.
Now provide the response and nothing else.
|
The key to generalizing to several panels was to refactor your code. In its present form, while very nice, it was mixing visualization / UI primitives and options with the split logic, and had lots of duplicate code. This made generalization hard. Here is the refactored version: ClearAll[SplitPane];Options[SplitPane] = { Direction -> "Vertical", DividerWidth -> Automatic, Paneled -> True};SplitPane[opts___?OptionQ] := Module[{dummy}, SplitPane[Dynamic[dummy], opts]];SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];SplitPane[val_, content_, opts___?OptionQ] := SplitPane[val, content, {100, 50}, opts];SplitPane[sp_List, {cont__}, {maxX_, maxY_}, opts___?OptionQ] /; Length[sp] == Length[Hold[cont]] - 1 := Module[{scrollablePane, dividerPane, onMouseDownCode, onMouseDraggedCode, dynPane, gridArg, split, divider, panel}, With[{paneled = Paneled /. {opts} /. Options[SplitPane],len = Length[Hold[cont]]}, Which[ TrueQ[paneled ], panel = Table[True, {len}], MatchQ[paneled, {Repeated[(True | False), {len}]}], panel = paneled, True, Message[SplitPane::badopt]; Return[$Failed, Module] ] ]; DynamicModule[{temp, dir, d, coord, max, fix, val}, {dir, d} = {Direction, DividerWidth}/.{opts}/.Options[SplitPane]; dir = dir /. { Bottom | Top | "Vertical" -> "Vertical", _ -> "Horizontal" }; d = d /. Automatic -> 2; val = Clip[sp /. {_?NumberQ -> sp, _ -> maxX/2}, {0, maxX}]; {coord, max, fix} = Switch[dir, "Vertical", {First, maxX, maxY}, "Horizontal", {(max - Last[#]) &, maxY, maxX} ]; Do[split[i] = sp[[i]], {i, 1, Length[sp]}]; split[Length[sp] + 1] = max - Total[sp] - 2*d*Length[sp]; panel = (# /. { None | False -> Identity, _ -> (Panel[#, ImageMargins -> 0,FrameMargins -> -1] &) }) & /@ panel; scrollablePane[args___] := Pane[args, ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, AppearanceElements -> None]; dividerPane[size : {_, _}] := Pane[Null, ImageSize -> size, ImageMargins -> -1,FrameMargins -> -1]; onMouseDownCode[n_] := Module[{old}, temp = coord@MousePosition@"CellContentsAbsolute"; If[Abs[temp - split[n]] <= d \[And] 0 <= temp <= max, old = split[n]; split[n] = temp-Sum[split[i], {i, n - 1}]; split[n + 1] += old - split[n]; ]]; onMouseDraggedCode[n_] := Module[{old}, temp = coord@MousePosition@"CellContentsAbsolute"; If[0 <= temp <= max, old = split[n]; split[n] = temp -Sum[split[i], {i, n - 1}]; split[n + 1] += old - split[n]; ] ; ]; SetAttributes[dynPane, HoldFirst]; dynPane[expr_, n_, size_] := panel[[n]]@scrollablePane[expr, ImageSize -> size]; divider[n_, sizediv_, resizeType_] := Deploy@EventHandler[ MouseAppearance[dividerPane[sizediv], resizeType], "MouseDown" :> onMouseDownCode[n], "MouseDragged" :> onMouseDraggedCode[n] ]; SetAttributes[gridArg, HoldAll]; gridArg[{content__}, sizediv_, resizeType_, sizeF_] := Module[{myHold, len = Length[Hold[content]] }, SetAttributes[myHold, HoldAll]; List @@ Map[ Dynamic, Apply[Hold, MapThread[Compose, { Range[len] /. { len :> Function[ exp, myHold[dynPane[exp, len, sizeF[len]]], HoldAll ], n_Integer :> Function[exp, myHold[dynPane[exp, n, sizeF[n]], divider[n, sizediv, resizeType] ], HoldAll] }, Unevaluated /@ Unevaluated[{content}] }] (* MapThread *) ] /. myHold[x__] :> x ] (* Map *) ]; (* Module *) (* Output *) Grid[ If[dir === "Vertical", List@ gridArg[{cont}, {d*2, fix},"FrameLRResize",{split[#] - d, fix} &], (* else *) List /@ gridArg[{cont}, {fix, d*2},"FrameTBResize", {fix, split[#] - d} &] ], Spacings -> {0, -.1}]]];SplitPane[val_, arg___] /; NumberQ[val] := Module[{x = val}, SplitPane[Dynamic[x], arg]]; Here is how it may look: SplitPane[{300, 300}, { Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], Factorial[123], CompleteGraph[5] }, {900, 300}] Can't comment of performance problems you mentioned. Also, when you start dragging with the mouse, the real cursor position is often quite off with respect to the divider position. This is both for your and my versions, perhaps some more precise scaling is needed. Just want to emphasize once again - generalization became only possible after I did the refactoring, to separate the splitting logic from the visualization-related things. As to the optimization, I also think that it will be much easier to attempt optimizing this version than the original one, for the same reasons. EDIT I hesitated a bit to add this note, but it must be mentioned that my solution above, while working, shows one practice which is considered bad by expert UI mma programmers. Namely, it uses Module - generated variables inside Dynamic inner to that Module (in particular, split in the code above, also various auxiliary functions). The reasons I used it are that I wasn't able to make this work with only DynamicModule - generated variables, plus Module - generated variables always worked for me before. However, please see the post by John Fultz in this MathGroup thread, where he states that this practice should be avoided.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7697642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975061/']}
|
jdg_374076
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59428311
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am reading this documentation: int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen); getpeername() returns the address of the peer connected to the socket sockfd Questions : If I am on the server machine and I have the "server" and many "clients" connections to sockfd what address will it return? What does peer mean in this context?
Now provide the response and nothing else.
|
When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword? "Why?" questions like this can be hard to answer because they are vague. I'm going to assume that your question is "what arguments could be made during language design to argue for the position that the override keyword is required ?" Let's start by taking a step back. In some languages, say, Java, methods are virtual by default and overridden automatically. The designers of C# were aware of this and considered it to be a minor flaw in Java. C# is not "Java with the stupid parts taken out" as some have said, but the designers of C# were keen to learn from the problematic design points of C, C++ and Java, and not replicate them in C#. The C# designers considered overriding to be a possible source of bugs; after all, it is a way to change the behaviour of existing, tested code , and that is dangerous. Overriding is not something that should be done casually or by accident; it should be designed by someone thinking hard about it . That's why methods are not virtual by default, and why you are required to say that you are overriding a method. That's the basic reasoning. We can now go into some more advanced reasoning. StriplingWarrior's answer gives a good first cut at making a more advanced argument. The author of the derived class may be uninformed about the base class, may be intending to make a new method, and we should not allow the user to override by mistake . Though this point is reasonable, there are a number of counterarguments, such as: The author of a derived class has a responsibility to know everything about the base class! They are re-using that code, and they should do the due diligence to understand that code thoroughly before re-using it. In your particular scenario the virtual method is abstract; it would be an error to not override it, and so it is unlikely that the author would be creating an implementation by accident. Let's then make an even more advanced argument on this point. Under what circumstances can the author of a derived class be excused for not knowing what the base class does? Well, consider this scenario: The base class author makes an abstract base class B. The derived class author, on a different team, makes a derived class D with method M. The base class author realizes that teams which extend base class B will always need to supply a method M, so the base class author adds abstract method M. When class D is recompiled, what happens? What we want to happen is the author of D is informed that something relevant has changed . The relevant thing that has changed is that M is now a requirement and that their implementation must be overloaded. D.M might need to change its behaviour once we know that it could be called from the base class. The correct thing to do is not to silently say "oh, D.M exists and extends B.M". The correct thing for the compiler to do is fail , and say "hey, author of D, check out this assumption of yours which is no longer valid and fix your code if necessary". In your example, suppose the override was optional on SayHello because it is overriding an abstract method. There are two possibilities: (1) the author of the code intends to override an abstract method, or (2) the overriding method is overriding by accident because someone else changed the base class, and the code is now wrong in some subtle way. We cannot tell these possibilities apart if override is optional . But if override is required then we can tell apart three scenarios. If there is a possible mistake in the code then override is missing . If it is intentionally overriding then override is present . And if it is intentionally not overriding then new is present . C#'s design enables us to make these subtle distinctions. Remember compiler error reporting requires reading the mind of the developer ; the compiler must deduce from wrong code what correct code the author likely had in mind , and give an error that points them in the correct direction. The more clues we can make the developer leave in the code about what they were thinking, the better a job the compiler can do in reporting errors and therefore the faster you can find and fix your bugs. But more generally, C# was designed for a world in which code changes . A great many features of C# which appear "odd" are in fact there because they inform the developer when an assumption that used to be valid has become invalid because a base class changed. This class of bugs is called "brittle base class failures", and C# has a number of interesting mitigations for this failure class.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59428311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3014866/']}
|
jdg_374077
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1445191
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was solving a differential equation by reduction of order, and was required to evaluate the indefinite integral $$I=\int \frac{xe^x}{(x+1)^2}dx.$$ The only method that came to mind was inspection, i.e. recognizing that $$ \frac{d}{dx} \frac{e^x}{x+1} = \frac{xe^x}{(x+1)^2}.$$ I would not trust myself to recognize this under the pressure of a test or exam, so is it possible to evaluate $I$ by substitution, parts, or some other method?
Now provide the response and nothing else.
|
A nice trick is to write $\frac{x}{(1+x)^2}$ as $\frac{(x+1)-1}{(x+1)^2}=\frac{1}{(x+1)}-\frac{1}{(x+1)^2}$, then apply integration by parts: $$ \int \frac{e^x}{(1+x)^2}\,dx = -\frac{e^x}{1+x}+\int \frac{e^x}{(1+x)}\,dx.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1445191', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/180579/']}
|
jdg_374078
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12468022
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory mydir . Each script, before outputting checks if mydir exists and if not creates it: if not os.path.isdir(mydir): os.makedirs(mydir) but this yields the error: os.makedirs(self.log_dir) File "/usr/lib/python2.6/os.py", line 157, in makedirsmkdir(name,mode)OSError: [Errno 17] File exists I suspect it might be due to a race condition, where one job creates the dir before the other gets to it. Is this possible? If so, how can this error be avoided? I'm not sure it's a race condition so was wondering if other issues in Python can cause this odd error.
Now provide the response and nothing else.
|
Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception while True: mydir = next_dir_name() try: os.makedirs(mydir) break except OSError, e: if e.errno != errno.EEXIST: raise # time.sleep might help here pass If you have a lot of threads trying to make a predictable series of directories this will still raise a lot of exceptions, but you will get there in the end. Better to just have one thread creating the dirs in that case
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12468022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_374079
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
300606
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The curve $$(X-16)^3=XY\tag{1}\label{1}$$is essential to Heegner's approach to the class number one problem for imaginary quadratic fields. We have the following “modular” parametrization \begin{equation}\tag{2}\label{2}(X,Y)=\left(2^{12}\Phi(\tau),j(\tau)\right),\end{equation}where $\Phi(\tau)=\frac{\Delta(2\tau)}{\Delta(\tau)}$. Note that the function $\Phi(\tau)$ is a Hauptmodul for the group $\Gamma_0(2)$. My questions are: The parametrization \eqref{2} can be deduced, quite laboriously, using Weierstrass elliptic functions and the product expansion for $\Delta$. However, when we clear the denominators, equation \eqref{1} (possibly) becomes an identity between modular forms and such identities should be easy to prove using the fact, that the space of modular forms has a finite dimension. Can this be done? What can we say about $\Delta(2\tau)$? It is a modular form with respect to some group?
Now provide the response and nothing else.
|
Firstly, you have a typo.The left side is $$(X-16)^3=-4096 + 3145728q - 729808896q^2+O(q^3)$$ while the right side is $$XY=4096 + 3145728q + 880803840q^2+O(q^3).$$ Looking at (19) of Stark's paper , I think the relevant root of $(X-16)^3=Xj(\tau)$ is $X=-f_2(\tau)^{24}$, which is $-2^{12}\Phi(\tau)$ in your notation. Proceeding from this, you are then interested in a modular forms proof of$$(2^{12}\Delta(q^2)+16\Delta(q))^3=2^{12}\Delta(q^2)\Delta(q)^2j(q).$$I'm not sure there is anything better than noting that both sides are weight 36 modular forms of level 2, and then equating enough coefficients to exploit the finite dimensionality. Whether this is "easier" than the method you mention is not clear. I don't know what you intend by (2). In general, $f(\tau)$ is a modular form on $\Gamma_0(N)$, then $f(M\tau)$ is a modular form on $\Gamma_0(MN)$. So clearly $\Delta(2\tau)$ is a modular form on $\Gamma_0(2)$. Indeed, as you note, the quotient is a modular function on $\Gamma_0(2)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/300606', 'https://mathoverflow.net', 'https://mathoverflow.net/users/122104/']}
|
jdg_374080
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6445167
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My employer has a dedicated module 1 we use for internal unit / system test; however, the author of this module no longer works here and I have been asked to test some devices with it. The problem is that pyfoo requires an ancient version of twisted (v8.2.0) and it imports twisted in 33 different files. I tried running pyfoo 's unit tests under v11.0.0 and I don't even see TCP SYN packets 2 . Unfortunately, I have already got twisted v11.0.0 installed on my lab linux server and I have my own code that depends on it. To solve this problem, I have only come up with the following options: Option A . Install a new version of python, install virtualenv , and then install an old version of twisted under the virtualenv . Only run the tests requiring pyfoo under this new version of python. Option B . Edit all 33 of the files with the following: DIR = '../'; sys.path.insert(0, DIR) and install the old version of python in the appropriate directory below the source. Option C . Attempt to fix pyfoo to use v11.0.0 3 Are there any options I am missing? Is there a more elegant way to solve this problem, besides Option A, above? **END-NOTES:** Let's call it pyfoo for sake of argument The unit tests connect to one of our local lab servers and exercises basic telnet functionality This option is almost a non-starter... pyfoo is not trivial, and I have a short deadline for this work.
Now provide the response and nothing else.
|
A better version of option B. would be to replace import twisted by import pkg_resourcespkg_resources.require("Twisted==8.2.0")import twisted which will arrange for the correct version of twisted to be imported, so long as it's installed, and raises an exception otherwise. This is a more portable solution. This won't work, though (nor would any other variaton of option B), if twisted gets imported before the pkg_resources.require gets called; twisted will already be in sys.modules OP Edit : Minor syntax correction, per pkg_resources docs
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6445167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/667301/']}
|
jdg_374081
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3320
|
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm aware of the following four functions of money: Medium of exchange. Measure of value (in dollars, pounds, etc.) Standard for exchanging goods (guaranteed by the Fed) A Store of value (as an asset). AFAIK, the last one didn't exist according to Classical Economists, but only John Maynard Keynes brought it later in his theory. I want to understand whether this function really exists? I'm more inclined to agree with the Classical Economists - I've created a simple analogy to understand this. Suppose there is a small village where there are N residents who trade only in barter. Now, you introduce a new bank in the village called Banko and a currency called pebbles. (For simplicity, lets assume that Banko is both a central bank and also lends/borrows money). Now in order to leave barter and migrate to currency system, the villagers will have to either sell their goods to Banko, or borrow pebbles from them. So, there is a "give and take" or exchange of pebbles against goods. But at the end of the day, if you consider the overall macro-economic position , the pebbles made no difference in value at all. The villager's NET ENDOWMENT is same as it was before, the pebbles just facilitate transactions and used to count their assets now. So, my question is, if money doesn't make any difference to the REAL value of goods and services, how can it be considered an asset?
Now provide the response and nothing else.
|
What is value ? Ultimately, value flows from the utility people get from consuming goods and services. Now, suppose, in your example world, I am a farmer and it is Autumn so I have the product of a large harvest. Here are three things I could do with it: Consume (and thereby enjoy the value of) my entire harvest immediately. But this would leave me hungry in the winter. Store some food for later: Put some of the grain I produced into a silo and take it out of the silo to eat in the winter. Sell some of my food to the bank in return for pebbles. Then, later in the winter, use those pebbles to buy back some food when my supply has run out. Notice that points 2 and 3 are essentially equivalent (they result in the same distribution of consumption across time). In the former, I am directly storing food. In the latter, I am using the pebbles to store the value associated with the food until I want to claim that value back. Although the store of value is really just an abstract implementation of the physical storage of the goods generating that value, this distinction becomes important in more sophisticated economies. Storing value rather than storing the goods that generate that value is attractive for a few reasons. Many goods and services are hard to store. For example, as an economics professor it is impossible for me to "store" lectures during the autumn for use in the summer when I can't find any students to teach. How do I avoid starving during these long, studentless summer months? I take the (hopefully positive) value my lectures produce during the autumn and store this value in money. I can then claim this value back during the summer when I need it. Storage of physical stuff takes up a lot of space and is expensive. Storage of money is much less so. Similarly, transporting stuff is expensive. With a bank card it becomes unnecessary to transport money at all. Storage is often wasteful because it involves stuff sitting around doing nothing when it could be generating utility for someone.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/3320', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/2919/']}
|
jdg_374082
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6122816
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know how to convert a string input into a variable name to use into Python code. A concrete example: def insrospect(foo, bar): requested_module = makestringvariable(foo) requested_object = makestringvariable(bar) import requested_module for item in inspect.getmemebers(requested_module.requested_object): member = makestringvariable(item[0]) if callable(requested_object.member): print itemif __name__ == '__main__': introspect(somemodule, someobject) So here above, because i do not know which module to introspect before launching, i need to convert the string to a usable module name and because getmembers() returns the members as strings, i also need them to be converted into usable variable names to check if they are callable. Is there such a makestringvariable() function?
Now provide the response and nothing else.
|
with the __import__ function and the getattr magic, you will be able to directly write this : import importlibdef introspect(foo, bar): imported_module = importlib.import_module(foo) imported_object = getattr(imported_module, bar) for item in inspect.getmembers(imported_object): if callable(getattr(imported_object, item[0]): print itemif __name__ == '__main__': introspect(somemodule, someobject)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6122816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717441/']}
|
jdg_374083
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2863599
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given the below coefficients, if the Diophantine equation $Axy + Bx + Cy + D = \lfloor\frac{n}{3}\rfloor$ has exactly one solution, then $n$ is prime, otherwise $n$ is composite. In a sense, this equation models primes by formalizing the factorization of $n$. The nonnegative solutions for $y$ uniquely encode the exhaustive set of odd factors of $n$. Here are the assumptions: $n=2x+1$ where $x \in \mathbb{N}$, $d=2a+1$ is the divisor of $n$ corresponding to $y$, where $a=y+b$ if $3 \mid n$, otherwise $a=3y+b$ (thus $d$ is decoded from $y$), and where the following coefficients are used: $$\begin{array}{c|c|c|} & \text{A} & \text{B} & \text{C} & \text{D} & \text{b} \\ \hline\text{1.a} & 6 & 5 & 2 & 1 & 2 \\ \hline\text{1.b} & 6 & 7 & 2 & 2 & 3 \\ \hline\text{2.a} & 6 & 5 & 4 & 3 & 2 \\ \hline\text{2.b} & 6 & 7 & 4 & 4 & 3 \\ \hline\text{3} & 2 & 5 & 0 & 0 & 2 \\ \hline\end{array}$$ For each $n$ the equation must be solved once or twice in order to complete the list of factors. Values of $n$ of the form $6j-1$, for any integer $j>0$, must use the $1.a$ and $2.b$ coefficients, those of the form $6j+1$ must use the $1.b$ and $2.a$ coefficients, and multiples of 3 must use the case 3 coefficients. For case 3, 3 is not in the solution (but choosing case 3 coefficients implies 3 is a factor). Here are the solutions for $n=99$: 3 $\rightarrow$ 11 and 33 , for $n=119$: 1.a $\rightarrow$ 119 , 17 and 2.b $\rightarrow$ 7 , and for $n=157$: 1.b $\rightarrow$ 157 . The value $x=0$ for case-1 coefficients is a trivial solution, since that solution corresponds to $d=n$. No values of $y$ correspond to $d=1$. The first four cases simplify to two equations, both of which may be evaluated for any $n=6j\pm1$, where $z=c \pmod 2$, $n=f(c)=2g+1$, $g=c+\lceil\frac{c}{2}\rceil$, and $c=\lfloor\frac{n}{3}\rfloor$: $6xy + 5x + 4y + 3 - 2z(y+1) = c$ $6xy + 7x + 2y + 2 + 2z(y+1) = c$ My question is, does this qualify as one of the prime-representing Diophantine equations revealed by Matiyasevich ? In either case, please explain what aspects of the above equation meet of violate Matiyasevich's criteria.
Now provide the response and nothing else.
|
A representation of a Diophantine set $S \subset \mathbb{N}$ is a polynomial with integer coefficients $P(X_1,X_2,\ldots,X_n,Y)$ with the following property: $y \in S$ if and only if there exist $x_1,x_2,\ldots,x_n \in \mathbb{N}$ such that $P(x_1,x_2,\ldots,x_n,y)=0$. That is all. You need one polynomial in some number of variables, and the coefficients of that polynomial are integers. For example, the polynomial $(X_1+2)(X_2+2)-Y$ has a solution with $Y=y$ if, and only if, $y$ is a composite natural number. Therefore the set of composite numbers is a Diophantine set. If you want to show that the set of primes is Diophantine, you need to exhibit such a polynomial. The equation $Axy+Bx+Cy+D=\lfloor \frac{n}{3} \rfloor$ doesn't qualify since the floor function is not part of the language of polynomials, and since you didn't say what $A,B,C,D$ are: you gave several options which seem to depend on the other variables. A polynomial has specific, fixed coefficients. There are, indeed, Diophantine equations defining the set of primes, but all known such equations have high degree or a large number of variables (or both). It is extremely unlikely that there is such an equation with just two variables, though I'm not aware that this is a proven result. It is certain that there is no such equation with two variables and degree $2$, as your example attempts (I think) to show.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2863599', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/326130/']}
|
jdg_374084
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57468144
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm creating a music player. This class among other things is suppose to add new songs to the playlist.A new window pops up with available songs and the checked songs get added. Songs can be filtered and the selected rows are to change the color when the checkbox is checked. The filtering works and everything is being added the way it's suppose to but... The problem is that when I check a song/some songs and then click on the search filter and the soft keyboard pops up the color of the selected rows changes to the default color, (the the song is still checked and can be added to the Playlist). When songs are checked and I hide the keyboard the same thing happens. The other issue is that when the list gets filtered the color of the row previously selected goes away as well when the search box is cleared, the songs remain schecked though. And I don't understand how and why that happens and therefore how to fix this. Anyone has any ideas, please? I think I don't understand how updating after filtering works and what notifyDataSetChanged() does exactly. Here's the adapter code : public class MyTrackAdapter extends ArrayAdapter<File> { private final Activity context; private ArrayList<File> album, temp; private ArrayList<File> piosenki; public MyTrackAdapter(Activity context, ArrayList<File> album) { super(context, R.layout.adapter_traki, album); this.context = context; this.temp = new ArrayList<File>(album); this.album = album; this.piosenki=new ArrayList<File>(); } public View getView(int position, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); final View rowView = inflater.inflate(R.layout.adapter_traki, null,true); final CheckBox cb_plus = (CheckBox) rowView.findViewById(R.id.add); final int position1=position; final TextView txt = (TextView) rowView.findViewById(R.id.list_text); if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor); else rowView.setBackgroundResource(R.color.bpcolor); txt.setText(album.get(position1).getName().toString().replace(".mp3","")); cb_plus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (cb_plus.isChecked()) { cb_plus.setBackgroundResource(R.drawable.x2); txt.setTextColor(context.getResources().getColor(R.color.bdcolor)); rowView.setBackgroundResource(R.color.acolor); piosenki.add(album.get(position1)); } else { cb_plus.setBackgroundResource(R.drawable.plus); txt.setTextColor(context.getResources().getColor(R.color.gcolor)); if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor); else rowView.setBackgroundResource(R.color.bpcolor); piosenki.remove(album.get(position1)); } } }); return rowView; } public void showTost(String s) { Toast.makeText(context, s, Toast.LENGTH_SHORT).show(); } public ArrayList<File> getpiosenki() { return piosenki; } public Filter getFilter() { return filtr; } private Filter filtr = new Filter() { protected FilterResults performFiltering(CharSequence s) { FilterResults r = new FilterResults(); ArrayList<File> f = new ArrayList<File>(); if(s==null || s.length()==0) f.addAll(temp); else { String ss=s.toString().toLowerCase().trim(); for(File ff : temp) if(ff.getName().replace(".mp3", "").toLowerCase().contains(ss)) f.add(ff); } r.values=f; r.count=f.size(); return r; } protected void publishResults(CharSequence s, FilterResults r) { album.clear(); album.addAll((ArrayList)r.values); notifyDataSetChanged(); } };} And the Playlist class : public class Playlist extends Activity implements TextWatcher{ int where; long pos; String pllist; ArrayList<String> lstp, lsts; ArrayList<Long> lsti; ArrayList<Integer> lstx; DBHandler db; private TextView txt1, txt2; ImageView pic; private ListView lv_traki; ListView lv_traki2add; PopupWindow pw; View popupv; TextView etext; MyTrackAdapter tadapter; ImageView add2list; ArrayList <File> piosenki, toadd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playlist); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); db = new DBHandler(getApplicationContext()); Intent tnt = getIntent(); Bundle bn = tnt.getExtras(); lstp = (ArrayList) bn.getParcelableArrayList("path"); lsts = (ArrayList) bn.getParcelableArrayList("song"); lsti = (ArrayList) bn.getParcelableArrayList("indx"); lstx = (ArrayList) bn.getParcelableArrayList("pause"); pos = bn.getLong("pos", 0); where = bn.getInt("skad", 0); pllist = bn.getString("album"); piosenki = (ArrayList) bn.getParcelableArrayList("full"); setData(0, lstp.size()); songlist(); lv_traki.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) { Intent it; lstp.clear(); lsti.clear(); lsts.clear(); lstx.clear(); db.gett1path(pos, lstp); db.gett1song(pos, lsts); db.gett1pause(pos, lstx); db.gett1id(pos, lsti); it=new Intent(getApplicationContext(), Player.class); it.putExtra("path", lstp).putExtra("nazwa", lsts).putExtra("pause", lstx).putExtra("pos",i).putExtra("skad",4); startActivity(it); } }); if(where==5) lv_traki.performItemClick(lv_traki.getAdapter().getView(0, null, null), 0, lv_traki.getAdapter().getItemId(0)); add2list = (ImageView) findViewById(R.id.btn_addtoplay); toadd = new ArrayList<File>(); add2list.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { popupv = ((LayoutInflater) getApplicationContext().getSystemService("layout_inflater")).inflate(R.layout.popup_addtolist, null); ImageView btn01 = (ImageView) popupv.findViewById(R.id.btn_addtoplay); FrameLayout fl = (FrameLayout) findViewById(R.id.frameLayout1); etext = (EditText) popupv.findViewById(R.id.etext); etext.addTextChangedListener(Playlist.this); lv_traki2add = (ListView) popupv.findViewById(R.id.lst_traki2add); tadapter = new MyTrackAdapter(Playlist.this, piosenki); lv_traki2add.setAdapter(tadapter); toadd=tadapter.getpiosenki(); btn01.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if(toadd.size()>0) { for (File addt1 : toadd) { db.addt1(pos, addt1); } lstp.clear(); lsts.clear(); lstx.clear(); lsti.clear(); db.gett1path(pos, lstp); db.gett1song(pos, lsts); db.gett1pause(pos, lstx); db.gett1id(pos, lsti); lv_traki.setAdapter(null); setData(0, lstp.size()); MyPlaylistAdapter adapter=new MyPlaylistAdapter(Playlist.this, lsts, lstp, lsti, lstx, pos, pllist, lv_traki, txt2); lv_traki.setAdapter(adapter); for(int x=0; x<lv_traki2add.getChildCount(); x++) { CheckBox cb = lv_traki2add.getChildAt(x).findViewById(R.id.add); cb.setChecked(false); } pw.dismiss(); showTost("Songs Added"); } else pw.dismiss(); } }); pw = new PopupWindow(popupv, -1, -1, true); pw.showAtLocation(fl, 17, 0, 0); } }); } private void songlist() { lv_traki = (ListView) findViewById(R.id.lst_traki); MyPlaylistAdapter adapter=new MyPlaylistAdapter(this, lsts, lstp, lsti, lstx, pos, pllist, lv_traki, txt2); lv_traki.setAdapter(adapter); } public void setData(int z, int size) { MediaMetadataRetriever mmr = new MediaMetadataRetriever(); MediaMetadataRetriever tmp = new MediaMetadataRetriever(); mmr.setDataSource(lstp.get(z)); txt1 = (TextView) findViewById(R.id.txt1); txt2 = (TextView) findViewById(R.id.txt2); pic = (ImageView) findViewById(R.id.img_bg); int tmax = 0; for(int i=0;i<size;i++) { tmp.setDataSource(lstp.get(i)); tmax+=Integer.parseInt(tmp.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); tmax+=lstx.get(i)*1000; } txt1.setText(pllist); if (size>1) txt2.setText(size+" songs; "+mili_t(tmax)); else txt2.setText("1 song; "+mili_t(tmax)); Bitmap bm; Drawable d; byte [] img = mmr.getEmbeddedPicture(); if(img!=null) { bm = BitmapFactory.decodeByteArray(img, 0, img.length); d = new BitmapDrawable(getResources(), bm); pic.setBackground(d); } else { pic.setBackgroundResource(R.drawable.no_image); pic.getLayoutParams().height = 400; pic.getLayoutParams().width = 400; pic.setScaleType(ScaleType.CENTER_INSIDE); } } public String mili_t(int t) { int s = (int) (t / 1000) % 60 ; int m = (int) ((t / (1000*60)) % 60); int h = (int) ((t / (1000*60*60)) % 24); String dt="", dh, ds, dm; if(h>0) { dh=Integer.toString(h); if(h<10) dh="0"+dh; dt=dt+dh+":"; } if(m>=0) { dm=Integer.toString(m); if(m<10) dm="0"+dm; dt=dt+dm+":"; } if(s>=0) { ds=Integer.toString(s); if(s<10) ds="0"+ds; dt=dt+ds; } return dt; } public void showTost(String s) { Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { tadapter.getFilter().filter(s); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) {}} And the xml : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/popupwrap" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@color/bdcolor"><RelativeLayout android:id="@+id/popup" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/bdcolor"> <EditText android:id="@+id/etext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColorHint="@color/bbcolor" android:hint="SEARCH FILTER" android:background="@drawable/etext" android:textSize="24sp" android:textCursorDrawable="@drawable/cursor" android:textColor="@color/gcolor" android:inputType="text" android:layout_marginLeft="10dp" android:layout_marginRight="80dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:layout_centerVertical="true" android:layout_alignParentLeft="true"/> <ImageView android:id="@+id/btn_addtoplay" android:layout_width="40dp" android:layout_height="40dp" android:layout_marginBottom="10dp" android:layout_marginRight="10dp" android:src="@drawable/check1" android:clickable="true" android:layout_alignParentRight="true" android:layout_marginTop="10dp" android:layout_centerVertical="true"/></RelativeLayout> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/lst_traki2add"> </ListView></LinearLayout>
Now provide the response and nothing else.
|
The problem is that when env.py is executed, models is not in your PYTHONPATH , so it can't be imported. With the project structure you've outlined, it might be a little hard to address; the easiest solution might be to modify your PYTHONPATH inside env.py like this: import syssys.path = ['', '..'] + sys.path[1:]from models import Base This will add the parent directory of alembic/ to your PYTHONPATH so that it can find the models module. Alternatively, you add the directory containing your modules to your PYTHONPATH environment variable in your shell: $ export PYTHONPATH='/path/to/some db/some db':$PYTHONPATH This solution is a little more brittle because you have to remember to do this each session and it will be different for each machine you intend to run Alembic on. When I ran into this issue, the SQLAlchemy developer suggested that if I was using pip and virtual environments, I could install my project in editable mode so that it's in the system PYTHONPATH and Alembic would be able to find it from anywhere. More details are available in the Python packaging guide . For this, you'd need a setup.py for your project and you may want to change your project structure so that there's a top-level module containing things like models and alchemy . For example: myproj/ setup.py alembic/ env.py migrations/ myapp/ __init__.py alchemy/ __init__.py models/ __init__.py If this is set up correctly, you can $ pip install -e . from inside the myproj/ directory. Then in env.py you would then import Base like this: from myapp.models import Base
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57468144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11919331/']}
|
jdg_374085
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21382
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $\mathcal C,\otimes$ be a monoidal category, i.e. $\otimes : \mathcal C \times \mathcal C \to \mathcal C$ is a functor, and there's a bit more structure and properties. Suppose that for each $X \in \mathcal C$, the functor $X \otimes - : \mathcal C \to \mathcal C$ has a right adjoint. I will call this adjoint (unique up to canonical isomorphism of functors) $\underline{\rm Hom}(X,-) : \mathcal C \to \mathcal C$. By general abstract nonsense, $\underline{\rm Hom}(X,-)$ is contravariant in $X$, and so defines a functor $\underline{\rm Hom}: \mathcal C^{\rm op} \times \mathcal C \to \mathcal C$. If $1 \in \mathcal C$ is the monoidal unit, then $\underline{\rm Hom}(1,-)$ is (naturally isomorphic to) the identity functor. Then there are canonically defined "evaluation" and "internal composition" maps, both of which I will denote by $\bullet$. Indeed, we define "evaluation" $\bullet_{X,Y}: X\otimes \underline{\rm Hom}(X,Y) \to Y$ to be the map that corresponds to ${\rm id}: \underline{\rm Hom}(X,Y) \to \underline{\rm Hom}(X,Y)$ under the adjuntion. Then we define "composition" $\bullet_{X,Y,Z}: \underline{\rm Hom}(X,Y) \otimes \underline{\rm Hom}(Y,Z) \to \underline{\rm Hom}(X,Z)$ to be the map that corresponds under the adjunction to $\bullet_{Y,Z} \circ (\bullet_{X,Y} \otimes {\rm id}) : X \otimes \underline{\rm Hom}(X,Y) \otimes \underline{\rm Hom}(Y,Z) \to Z$. (I have supressed all associators.) Question: Is $\bullet$ an associative multiplication? I.e. do we have necessarily equality of morphisms $\bullet_{W,Y,Z} \circ (\bullet_{W,X,Y} \otimes {\rm id}) \overset ? = \bullet_{W,X,Z} \circ ({\rm id}\otimes \bullet_{X,Y,Z})$ of maps $\underline{\rm Hom}(W,X) \otimes \underline{\rm Hom}(X,Y) \otimes \underline{\rm Hom}(Y,Z) \to \underline{\rm Hom}(X,Z)$? If not, what extra conditions on $\otimes$ are necessary/sufficient?
Now provide the response and nothing else.
|
It is associative. Consider the evaluation cube drawn here . Four of the faces commute by definition of the composition map, and one by functoriality of the tensor product. The commutativity of these five faces implies that any of the maps $W \otimes \operatorname{Hom}(W, X) \otimes \operatorname{Hom}(X, Y) \otimes \operatorname{Hom}(Y, Z) \to Z$ are equal, so by adjunction, the two composites of compositions are equal.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/21382', 'https://mathoverflow.net', 'https://mathoverflow.net/users/78/']}
|
jdg_374086
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24483075
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to take input of a particular part of a string like "First (helloWorld): last" From that string I want to take input only "helloWorld" by regular expression. I am using %*[^(] (%s):" But that does not serve my purpose. Please somebody help me to solve this problem.
Now provide the response and nothing else.
|
The format specifiers in the scanf family of functions are not generally considered to be a species of regular expression. However, you can do what you want something like this. #include <stdio.h>int main() { char str[256]; scanf("First (helloWorld): last", "%*[^(](%[^)]%*[^\n]", str); printf("%s\n", str); return 0;}%*[^(] read and discard everything up to opening paren( read and discard the opening paren%[^)] read and store up up to (but not including) the closing paren%*[^\n] read and discard up to (but not including) the newline The last format specifier is not necessary in the context of the above sscanf , but would be useful if reading from a stream and you want it positioned at the end of the current line for the next read. Note that the newline is still left in the stream, though. Rather than use fscanf (or scanf ) to read from a stream directly, it's pretty much always better read a line with fgets and then extract the fields of interest with sscanf // Read lines, extracting the first parenthesized substring.#include <stdio.h>int main() { char line[256], str[128]; while (fgets(line, sizeof line, stdin)) { sscanf(line, "%*[^(](%127[^)]", str); printf("|%s|\n", str); } return 0;} Sample run: one (two) three|two|four (five) six|five|seven eight (nine) ten|nine|
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24483075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3114833/']}
|
jdg_374087
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3289319
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i am trying to access MQ queues using JMS. i am getting the below java.lang.UnsatisfiedLinkError: no mqjbnd05 in java.library.path i am passing -Djava.library.path="C:\Program Files\IBM\WebSphere MQ\java\lib" as the VM argument while running the program in eclipse. This issue is discussed quite a lot on the net but with out any conclusion. Has anyone resolved this? TIA.
Now provide the response and nothing else.
|
As I had to deal with this error myself; and it took me a lot of time to find the right answer, I'd like to share it with the next one, who comes along this thread... Actually the solution to the problem was very simple (at least in my case). It was not related to any CLASSPATH , java.library.path or installation issues. I simply forgot to switch the MQConnectionFactory into the Client mode. This has to be done, by simply calling cf.setTransportType(WMQConstants.WMQ_CM_CLIENT); or cf.setTransportType(WMQConstants.WMQ_CM_BINDINGS_THEN_CLIENT); or any other connection type, that fits your needs. By default, the ConnectionFactory is in "Binding" mode ( WMQ_CM_BINDINGS ), which is intended for local server installations, as it is is stated in the IBM Documentation: To connect to a queue manager in bindings mode , a WebSphere MQ classes for JMS application must run on the same system on which the queue manager is running. This transport type is the same as the XMSC_WMQ_CONNECTION_MODE ( WMQConstants.WMQ_CONNECTION_MODE ) property, when using JNDI or the JmsFactoryFactory . The same should apply to the other ConnectionFactory types: MQQueueConnectionFactory , MQTopicConnectionFactory , MQXAConnectionFactory , MQXAQueueConnectionFactory and MQXATopicConnectionFactory Check the IMB Knowledge Center for more information about the different connection/binding options: https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.dev.doc/q031720_.htm https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.dev.doc/q030560_.htm
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3289319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114194/']}
|
jdg_374088
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11207394
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My app needs to contact the same device it is working on, via http://127.0.0.1/... (a localhost url). For some reason, about 50% of the times (and maybe exactly 50%) when I reach a website there with JSON content, I get the exception: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer) For the other 50%, I get perfectly good results. I've tried to do polls (and even large delay between polls), but I keep getting the same weird results. I've searched the internet and also here, and I'm not sure why it occurs. Does the peer mean that the client has caused it? Why does it happen, and how should i handle it? Some websites say that it's a common thing, but I didn't find what's the best thing to do in such cases.
Now provide the response and nothing else.
|
Ok, the answer was that it's the server's fault - it had to close the connection after each request. It might be that Android keeps a pool of connections and use the old one or something like that. Anyway , now it works. EDIT: according to the API of HttpURLConnection , this can be solved on the client side too: The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams with BufferedInputStream or BufferedOutputStream. Callers that do only bulk reads or writes may omit buffering. When transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string). To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() may return the socket to a pool of connected sockets. This behavior can be disabled by setting the http.keepAlive system property to false before issuing any HTTP requests. The http.maxConnections property may be used to control how many idle connections to each server will be held. Taken from: developer.android.com/reference/java/net/HttpURLConnection.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11207394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878126/']}
|
jdg_374089
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1426935
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$A = (1,2)\cup(3,4) ; B=[1,4]$ find $B\setminus A$ and the complement of $A$ also is $A\setminus B=\emptyset$ right ?
Now provide the response and nothing else.
|
The rationale of the elimination method is rather obvious: as you can't solve an equation in two unknowns directly, you transform the system in a way to get an equation in a single unknown, which is easily solved. You'll soon learn that this process generalizes to a system of $n$ equations in $n$ unknowns, where you transform a square system in a triangular one. The approach is very smart and very efficient. The method works because you are allowed to replace an equation by a linear combination of itself and other equations (as you combine equal expressions, the equality $LHS=RHS$ isn't lost). Any system of equations (linear or not) can be written as equalities to zero of some functions of the unknowns.$$f(x,y)=ax+by-n=0,\\g(x,y)=cx+dy-m=0.$$ You are "allowed" to transform the system into another, provided you don't introduce new solutions nor discard valid ones. For instance, omitting the arguments $(x,y)$, the single equation $$f^2+g^2=0$$ has the same solution set, $f=0,g=0$. In particular, you can form linear combinations, such as $$\alpha f+\beta g=0,\\\gamma f+\delta g=0,$$ provided that the corresponding system isn't indeterminate, i.e. if $\alpha\delta-\beta\gamma\ne0$. A special case is that used in elimination, where you add an equation to another and keep the other unchanged, $$f=0,\\\gamma f+g=0.$$It obviously fulfills the criterion. This new system is equivalent to $$ax+by=n,\\(\gamma a +c)x+(\gamma b+d)y=\gamma n+m,$$ and you are free to choose $\gamma$ so that the term in $y$ vanishes.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1426935', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/268975/']}
|
jdg_374090
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7836882
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a datagridview with multiple checkboxes. When the Finished checkbox is checked I need to execute linq code to update a specific table. How do I find out if that specific check box is dirty and where do I write the code to pass the values I need to be passed to the table. Note that it is not the same table that the datagridview is based on. Thanks. EDIT: private void propertyInformationDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)propertyInformationDataGridView.Rows[e.RowIndex].Cells[3]; DataGridViewRow row = propertyInformationDataGridView.Rows[e.RowIndex] as DataGridViewRow; System.Data.DataRowView SelectedRowView; newCityCollectionDataSet.PropertyInformationRow SelectedRow; SelectedRowView = (System.Data.DataRowView)propertyInformationBindingSource.Current; SelectedRow = (newCityCollectionDataSet.PropertyInformationRow)SelectedRowView.Row; if (Convert.ToBoolean(checkCell.EditedFormattedValue) == true) { DataClasses1DataContext dc = new DataClasses1DataContext(); var matchedCaseNumber = (from c in dc.GetTable<PropertyInformation>() where c.CaseNumberKey == SelectedRow.CaseNumberKey select c).SingleOrDefault(); reportsSent newReport = new reportsSent(); newReport.CaseNumberKey = SelectedRow.CaseNumberKey; dc.reportsSents.InsertOnSubmit(newReport); dc.SubmitChanges(); } } Do I need to endedit at some point is that the issue?
Now provide the response and nothing else.
|
Try checking the Name property of the TRttiProperty.PropertyType I don't have Delphi 2010, but this works in XE. {$APPTYPE CONSOLE}uses SysUtils, Classes, Rtti;type TMyClass =class private FDate: TDateTime; FProp: Integer; FDate2: TDateTime; FDate1: TDateTime; public property Date1 : TDateTime read FDate1 Write FDate1; property Prop : Integer read FProp Write FProp; property Date2 : TDateTime read FDate2 Write FDate2; end;var ctx : TRttiContext; t : TRttiType; p : TRttiProperty;begin ctx := TRttiContext.Create; try t := ctx.GetType(TMyClass.ClassInfo); for p in t.GetProperties do if CompareText('TDateTime',p.PropertyType.Name)=0 then Writeln(Format('the property %s is %s',[p.Name,p.PropertyType.Name])); finally ctx.Free; end; Readln;end. this code returns the property Date1 is TDateTimethe property Date2 is TDateTime
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7836882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/630737/']}
|
jdg_374091
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24086269
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having some trouble with my pagination.I'm having two tables with data from a database and I paginated it with laravel Paginator. Now my problem is when you go to, for example, page 2 it adds ?page=2 but that makes the first table go to page 2 too. Is there anyway to get something like this ? page_table1={number}&page_table2={number} so you don't apply the page change on other tables.
Now provide the response and nothing else.
|
Unfortunately I can't test this code right now, but browsing at the docs and the code (in Illuminate/Pagination/Environment ) I guess you could something like this: # use default 'page' for this$collection1 = Model::paginate(20);# use custom 'other_page' for this$collection2 = Model2::paginate(20);$collection2->setPageName('other_page'); The setPageName() method isn't documented in the docs, but it's a public method alongside those indicated in the documentation, so it should be working fine. FOr reference, this is the declaration (l. 171-180 in vendor/laravel/framework/src/Illuminate/Pagination/Environment.php ): /** * Set the input page parameter name used by the paginator. * * @param string $pageName * @return void */public function setPageName($pageName){ $this->pageName = $pageName;} Now take into consideration that you will have another query string appended to the url, so you need to tell the pagination to consider it. Use the appends() method: $collection1->appends(array_except(Request::query(), 'page'))->links();$collection2->appends(array_except(Request::query(), 'other_page'))->links(); That is, tell each Presenter to build up the url with all the query strings (the array resulting from Request::query() without the current index used by the paginator, or you'll end up with a double value). array_except() is a Laravel built in array helper that returns the given array (1st parameter) purged of the passed index (2nd parameter). I'll try to test this code as soon as I can, but it should work. Let me know in any case!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24086269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3072335/']}
|
jdg_374092
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4092756
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According the the MSDN documentation, Set() and Reset() on ManualResetEvent (or any EventWaitHandle) returns a boolean indicator whether or not the operation was successful. Under which circumstances can this call return false, and what am I supposed to do if it does?
Now provide the response and nothing else.
|
I wasn't sure how to answer this and looking at a lot of MSDN examples the Set return value is ignored so it must not be important or likely to happen. But that wasn't good enough. I fired up my VM and I opened up Reflector to take a look at the code. ManualResetEvent doesn't have Set but it inherits from EventWaitHandle which does. Here's the code: public bool Set(){ bool flag = Win32Native.SetEvent(base.safeWaitHandle); if (!flag) { __Error.WinIOError(); } return flag;} Where SetEvent is imported from Kernel32: [DllImport("kernel32.dll", SetLastError=true)]internal static extern bool SetEvent(SafeWaitHandle handle); The WinIOError() call just calls GetLastWin32Error which we don't really care about. Basically this means for the call to return false, something pretty wrong would have had to have occurred in the Win32 native code. Putting this info together with the fact that code hosted in official MSDN documentation ignores the return value (why not? what are you going to do if the kernel fails anyway?) you can safely ignore it yourself if you want to clean your logic up a bit or get it and log it if you're especially pedantic.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4092756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190480/']}
|
jdg_374093
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49387
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given the product of two functions defined explicitly through their Fourier coefficients (of unknown undeveloped form): $\sum_k{c_k e^{i k t}} \cdot \sum_k{c'_k e^{i k t}}$ Is there any way to express it as a Fourier series? ( Edit: approximated using a finite number of terms of the original) That is: $\sum_k{c''_k e^{i k t}}$ where each $c''_k$ could be explicitly defined from a finite sum of $c$ and $c'$. I feel the convolution theorem should be of some help here, but I can't see how for the life of me... (probably not relevant, but my goal is to use this product's equality with a third Fourier series and use coefficient identity in order to extract a set of optimisation constraints based on the terms of all three original series) Edit: since I am trying to identify coefficients, what I'm really hoping for is an approximated expression of the product, based on a limited number of terms... In the absence of any particular properties of $c$ and $c'$ that would simplify the convolution, is there any way to achieve this? (thanks a lot to people who already answered and made me realise the issue with my original formulation)
Now provide the response and nothing else.
|
I'd use the notation $ \times $ rather than $ * $ because the latter is used for convolutions in this sort of context (Fourier analysis). In any case, you can explicitly calculate the coefficients of the product's Fourier series via$$ c''_n = \sum_{k=-\infty}^{\infty} c_{n-k} c'_k$$Note that this can be related to convolutions in the sense that $ c''_n = (c * c')_n $.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/49387', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12472/']}
|
jdg_374094
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
404448
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As for now, I use my CLI (Command Line Interface) with either rbash , bash , dash , or sh . Given this fact, one can assume that the CLI is not shell dependent, and that even if we will delete all of these shells, we could use some primal/basic/ultralimited CLI. My question If I delete all the aforementioned shells in my GUIless operating system, will I still have a primal CLI of some sort? Notes I assume that that CLI won't be part of the kernel, because as I understand, the kernel is usually accessible only via proxy, like a shell). I was thinking about tmux and screen too but removed them from the headline and the question.
Now provide the response and nothing else.
|
No. Your premise that these different shells are all running on top of some more basic CLUI, because they are all fairly similar, is incorrect. Each shell is separately implementing a CLI interface to the kernel, which all look somewhat similar (because they are all 'Unix' shells, which conform more or less rigidly to an accepted standard, and they all run on the same sort of terminal device). The CLUI is coded into each shell program separately - they are all independent and are not sharing some underlying CLUI. If you delete all the shells, then you will have no CLUI. That makes Tux cry :(
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/404448', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/258010/']}
|
jdg_374095
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2192416
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a project where I have many constant strings formed by concatenation (numbers, etc.). For example, I have a LOCATION macro that formats __FILE__ and __LINE__ into a string that I can use to know where I am in the code, when printing messages or errors: #define _STR(x) # x#define STR(x) _STR(x)#define LOCATION __FILE__ "(" STR(__LINE__) ")" So, this would format a location like "file.cpp(42)". The problem is when I try to convert the result to a wide-string: #define _WIDEN(x) L ## x#define WIDEN(x) _WIDEN(x)#define WLOCATION WIDEN(LOCATION) This works just fine with GCC, and results in L"file.cpp(42)" being inserted in my code. However, when trying this with MSVC++ (using Visual C++ 2008 Express), I get an error: error: Concatenating wide "file.cpp" with narrow "(" I understand that the L prefix gets added only to the first term in my expression. I've also tried this: #define _WIDEN(x) L ## #x Which "works", but gives the string L"\"file.cpp\" \"(\" \"42\" \")\"" which is obviously not very convenient (and not what I am looking for), especially considering that this macro is simple compared to other macros. So, my question is: how can I get it to apply to the entire expression in MSVC++, so I can get the same result I am getting with GCC? I would rather not create a second string with all-wide tokens, because I would then have to maintain two macros for each one, which is not very convenient and can lead to bugs. Plus, I need the narrow version of each string as well, so using all-wide strings is not an option either, unfortunately.
Now provide the response and nothing else.
|
According to the C standard (aka "ISO-9899:1999" aka "C99"), Visual C is wrong and gcc is correct. That standard states, section 6.4.5/4: In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and wide string literal tokens are concatenated into a single multibyte character sequence. If any of the tokens are wide string literal tokens, the resulting multibyte character sequence is treated as a wide string literal; otherwise, it is treated as a character string literal. So you could file a complaint. Arguably, the previous version of the C standard (aka "C89" aka "C90" aka "ANSI C") did not mandate merging of wide strings with non-wide strings. Although C99 is now more than ten years old, it seems that Microsoft has no interest in making its C compiler conforming. Some users have reported being able to access some "C99" features by compiling C code as if it was C++ code, because C++ includes these features -- and for C++, Microsoft made an effort. But this does not seem to extend to the preprocessor. In the C89 dialect, I think that what you are looking for is not possible (actually I am pretty sure of it, and since I have written my own preprocessor I think I know what I am talking about). But you could add an extra parameter and propagate it: #define W(x) W_(x)#define W_(x) L ## x#define N(x) x#define STR(x, t) STR_(x, t)#define STR_(x, t) t(#x)#define LOCATION_(t) t(__FILE__) t("(") STR(__LINE__, t) t(")")#define LOCATION LOCATION_(N)#define WLOCATION LOCATION_(W) which should work on both gcc and Visual C (at least, it works for me, using Visual C 2005). Side note: you should not define macros with a name beginning with an underscore. These names are reserved, so by using them you could clash with some names used in system headers or in future versions of the compiler. Instead of _WIDEN , use WIDEN_ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2192416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228120/']}
|
jdg_374096
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
91507
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any optical component in existence that uniformizes randomly pointing rays?
Now provide the response and nothing else.
|
To add to Carl Witthoft's answer : your proposed device would violate Conservation of Optical Extent aka Optical Étendue unless it were an active device ( i.e. one needing a work input to "uniformise" a given quantity of light). The law that optical extent can only be held constant or increased by a passive optical system is equivalent to the second law of thermodynamics for light, because the optical extent of a light source is its volume in phase space. The optical extent $\Sigma$ for the light radiated from a surface $S$ is: $$\Sigma = \int_S \int_\Omega I(x) \cos(\theta(x, \Omega)) \,{\rm d} \Omega\, {\rm d} S$$ where we integrate the intensity $I$ at each point $x\in S$ over all solid angles $\Omega$ taking account of the angle $\theta$ each component of the radiation from point $x$ makes with the surface's unit normal. Then we integrate this quantity over all points on the surface $S$. So, the $\Sigma$ for your output would be nought, whilst it would be large for your input, so no passive imaging device can do what you ask. So, another way of putting Carl's answer would be that the proposed device would have to "forget" the state encoded in the input light's wavefront direction at each point. Thus your proposed device, if at all possible, would needfully be an active device, needing work input of $k_B\,T\,\log 2$ joules for each bit of light state forgotten in accordance with the Landauer Principle form of the second law of thermodynamics. I say more about this in my answer here .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/91507', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16853/']}
|
jdg_374097
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1099509
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a hash table where the keys are rather complex lists, with sublists of symbols and integers, and the value should be modified depending on the already existing value. The table is created with :test #'equal . I do something similar to this a lot: (defun try-add (i) (let ((old-i (gethash complex-list table nil))) (if (may-add old-i) (push i (gethash complex-list table))))) Profiling shows that equal tests take a lot of time. I have an optimization idea, that the amount of gethash lookups could be reduced from two to one. It can be done in C++ by reusing the iterator, but not sure how this would be done in Lisp. Any ideas?
Now provide the response and nothing else.
|
Don't do anything special, because the implementation does it for you. Of course, this approach is implementation-specific, and hash table performance varies between implementations. (But then optimization questions are always implementation-specific.) The following answer is for SBCL. I recommend checking whether your Lisp's hash tables perform the same optimization. Complain to your vendor if they don't! What happens in SBCL is that the hash table caches the last table index accessed by GETHASH. When PUTHASH (or equivalently, (SETF GETHASH)) is called, it first checks whether the key at that cached index is EQ to the key that you are passing in. If so, the entire hash table lookup routine is by-passed, and PUTHASH stores directly at the cached index. Note that EQ is just a pointer comparison and hence extremely fast -- it does not have to traverse the list at all. So in your code example, the is no overhead at all.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1099509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63832/']}
|
jdg_374098
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2129370
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In a Dedekind Domain we have unique decomposition of ideals into product of prime ideals. My question out of curiosity is: Is there a ring satisfying this which is not a Dedekind Domain?
Now provide the response and nothing else.
|
It is indeed a smooth function. A direct inductive argument can be given which is analogous (but a bit more tricky) to the argument that a complex function defined by a power series is smooth in the domain of convergence. In fact, it is actually easier to prove a more general statement and then apply it to deduce that $\exp$ is smooth. Let $(A, \cdot, \| \cdot \|)$ be a finite dimensional complex Banach algebra . The reason we want to generalize our discussion to an arbitrary Banach algebra and not work only with $A = M_n(\mathbb{C})$ is that it makes the inductive argument easier. Show first that the power maps $p_k \colon A \rightarrow A$ given by $p_k(X) = X^k$ are continuously differentiable with differential given by $$ dp_k|_{X}(Y) = X^{k-1}Y + X^{k-2}YX + \dots + XYX^{k-2} + YX^{k-1}.$$ The differential has this "strange" form because you don't know if $X$ and $Y$ commute. If they do, the formula above reduces to the usual formula $dp_k|_{X}(Y) = k X^{k-1} Y$. Then show the following lemma: Lemma : Let $(c_k)_{k=0}^{\infty}$ be a sequence of complex numbers such that $\sum_{k=0}^{\infty} c_k z^k$ converges on $B_{\mathbb{C}}(0,r)$. Define $f \colon B_A(0,r) \rightarrow A$ by $f(X) = \sum_{k=0}^{\infty} c_k X^k$. Then $f$ is well-defined and continuously differentiable. The differential of $f$ is given by $$ df|_{X}(Y) = \sum_{k=0}^{\infty} c_k dp_k|_{X}(Y). $$ Finally, you can use the lemma inductively to deduce that $f$ is actually smooth and not just $C^1$. For full details, see Chapter 3 of the book "Structure and Geometry of Lie Groups" by Joachim Hilgert and Karl-Hermann Neeb.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2129370', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/270091/']}
|
jdg_374099
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27960682
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I imitated a library and was able to write following code. This code created 'c' object to which 'a' function is assigned. So, to call 'a' , I will have to write c.a() . Also, I was able to add more functions to this 'c' object. I want to understand what is happening in this code. It doesn't look like normal object oriented programming. What is this type of javascript programming called? var c = (function(c) { if (c === undefined) { c = {}; } function a() { alert(1); } c.a = a; return c;}(c));
Now provide the response and nothing else.
|
It's a module pattern. You'll see many variants of that pattern, so it's essential to understand what really happens, you can't just imitate one. The point of this piece of code is to complete an object c (typically your global library). You probably have many similar pieces of code in your application, all building pieces of c , probably each of those in its own file. In case the library object c , which is passed as argument to the function, doesn't exist yet ( c === undefined ), it is created. This makes it possible to not depend of the execution order or of a preexecuted file. The right part of the assignment is an IIFE (Immediately Invoked Function Expression), that is a function which is immediately called. The advantage of this construction is that it creates a scope in which variables (for example the a function) can be declared without polluting the external (global) scope. Here the point is moot as a is externalized anyway but a module typically depends on several internal (private) functions and variables. A detail that might need an explanation : all those files look like they define a new variable c but there's no problem here, even if the files are concatenated : a var statements doesn't define a new variable if it already exists (a variable is defined for the whole scope, here globally, even before the point of declaration). Another way to write this would have been var c = c || {}; // ensure the c variable is defined, and initialize its value it if necessary(function() { // let's use an IIFE to have a protected scope and not pollute the global one function a() { alert(1); } c.a = a; // let's augment c})(); This one is probably clearer as it explicitly separates the two steps ( c initialization and c completion using an IIFE) it doesn't depend on two c variables with the same name it is less verbose
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27960682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774159/']}
|
jdg_374100
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
623256
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've learned in my high school the solution to such riddle: How many rectangles are there in this shape: the solution is through combinations:in this shape is a $5\times 6$ grid so the number of rectangles would be:$C^2_5 * C_6^2 $ I would like to know if this is possible in case of triangles? squares? is there a general rule for this?
Now provide the response and nothing else.
|
For a big equilateral triangle with sidelength $n$ filled with unit triangles it's $$\sum_{i = 1}^{n} \binom{n + 2 - i}{2} = \binom{n + 2}{3} = \frac{n(n+1)(n+2)}{6}$$triangles pointing upwards (exception. Triangles pointing downwards is a bit more tricky. The answer is (credit to WolframAlpha for the closed form)$$\sum_{i = 1}^{\left\lfloor \frac{n}{2}\right\rfloor}\binom{n + 2-2i}{2} = \frac{1}{6} \bigg\lfloor\frac{n}{2}\bigg\rfloor \left(4 \bigg\lfloor\frac{n}{2}\bigg\rfloor^2-3 (2 n+1) \bigg\lfloor\frac{n}{2}\bigg\rfloor+3 n^2+3 n-1\right)$$ If you want some help finding these formulas yourself, the sums are built around the question "How many triangles of side length $i$ are there?", and it turns out to always be a triangular number, although slightly nicer spaced for the upward-pointing triangles. A figure for the case $n = 4$ below. For squares, we have, following the same rule of "How many of size $i$ are there?", we get$$\sum_{i = 1}^n (n - i + 1)^2 = \frac{2n^3 + 3n^2 + n}{6}$$This is basically just a sum of consecutive squares, only summing from the largest to the smallest because that's the way it turned out. A figure for $n = 4$ is supplied below.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/623256', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/105069/']}
|
jdg_374101
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5205
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why do we think chronic inflammation can cause cancer? I know the pathway is not fully understood, but what makes scientists believe that inflammation causes cancer?
Now provide the response and nothing else.
|
There are good epidemiological data for this. Links between cancer and inflammation were first made in thenineteenth century, on the basis of observations that tumours oftenarose at sites of chronic inflammation and that inflammatory cellswere present in biopsied samples from tumours. There are many triggers of chronic inflammation that increase the riskof developing cancer. Such triggers include microbial infections (forexample, infection with Helicobacter pylori is associated with gastriccancer and gastric mucosal lymphoma), autoimmune diseases (forexample, inflammatory bowel disease is associated with colon cancer)and inflammatory conditions of unknown origin (for example,prostatitis is associated with prostate cancer). Accordingly,treatment with non-steroidal anti-inflammatory agents decreases theincidence of, and the mortality that results from, several tumourtypes. Cited from Mantovani, Alberto, et al. "Cancer-related inflammation." Nature 454.7203 (2008): 436-444. http://www.sld.cu/sitios/reumatologia/temas.php?idv=21500
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/5205', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/558/']}
|
jdg_374102
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1047
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The size of a finite skeletal category C in the sense of Leinster is defined as follows: Label the objects of C by integers 1,2,...,n and let a ij be the number of morphisms from i to j (for i and j between 1 and n). The size (or Euler characteristic) of C is defined as the sum of the entries of the inverse of the nxn matrix A=(a ij ), if the inverse exists. Let F q be a finite field with q elements. For every natural number i, there is up to isomorphism exactly one F q -vector space V i of dimension i. The number of linear maps from V i to V j is equal to q ij . We ignore the zero dimensional vector space V 0 . Consider the infinite matrix Q=(q ij ) where rows and and columns are indexed by positive integers 1,2,3,... From now on let us treat q as a formal parameter, don't care about convergence issues, and set v=q -1 . Is there a notion of an inverse of Q? (The entries will probably be formal power series in v.) If the answer is yes, what is a closed form for the sum of the entries of the inverse (as a formal power series in v), i.e. the size of the category of finite dimensional F q -vector spaces? At least every truncation Q n of Q to an upper left nxn corner has an inverse for every positive integer n, since Q n is a Vandermonde matrix. What is the limit of the sum of the entries of Q n -1 as n goes to infinity? I believe the answer is a power series in v. Is there an explicit form? How can you interpret the answer? Is it the Euler characteristic of some moduli space? Is it equal or related to a sum of 1/Gl(V i )? Does something interesting happen at q=1?
Now provide the response and nothing else.
|
Following the observations made in the comments one can compute the sum of the entries of Q n -1 . It turns out that Kevin Costello's formula is true for every n. Let (a 1 , a 2 , ..., a n ) be the the transpose of the k th column vector of Q n -1 . (Of course, this vector depends on k, but we omit the index k.) Qiaochu Yuan suggested to consider the polynomial A(x) = a 1 x + a 2 x 2 + ... + a n x n . The degree of A is n, therefore A is determined by values at n+1 points. But we know that A(0)=0 and that A(q i ) = delta ik for i = 1, 2, ... , n. By Lagrange interpolation, A(x) is equal to x(x-q)(x-q 2 )...(x-q k-1 )(x-q k+1 )...(x-q n ) / q k (q k -q)(q k -q 2 )...(q k -q k-1 )(q k -q k+1 )...(q k -q n ). The sum a 1 +a 2 +...+a n is equal to A(1). Let us work with quantized integers. We use the notation [k] = (1-q k )/(1-q) = 1+q+...+q k-1 . (Note that people from quantum groups sometimes use a different convention.) Furthermore, let [n choose k] be the quantized binomial coefficient. Then, A(1) is equal to (-1) k-1 [n choose k] q k(k-1)/2-kn . We sum A(1) over all k. A variant of the quantum binomial theorem gives that the sum of the entries of Q n -1 is equal to 1 - (1-1/q)(1-1/q 2 )...(1-1/q n ).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/1047', 'https://mathoverflow.net', 'https://mathoverflow.net/users/296/']}
|
jdg_374103
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19709923
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I recently tried this code and was a little confused. See the following declarations: static st; auto au; register reg; volatile vl; const cn; They all are allocating memory of 4 bytes (on 32 bit GCC). But when i try to print (using printf function) their sizes, they are not working and giving errors. sizeof(const) // worked and printed 4 sizeof(volatile) // worked and printed 4 sizeof(auto) // error: expected expression before ‘auto’ sizeof(static) // error: expected expression before ‘static’ sizeof(register) // error: expected expression before ‘register’ My doubt is auto, static, register keywords also allocating memory of 4 bytes(on 32 bit arch). But why these are giving errors unlike const and volatile ?
Now provide the response and nothing else.
|
In C prior to the 1999 standard, an unspecified type would default to int in many contexts. C99 dropped that rule, and omitting the type is now illegal (strictly speaking, it's a constraint violation , requiring a diagnostic -- which could be a non-fatal warning). In any case, omitting the int type has always been a bad idea. (It goes back to C's predecessor languages BCPL and B, which where largely typeless.) static st;auto au;register reg;volatile vl;const cn; These declarations are all legal in C90 (and all the variables are of type int ), but they're invalid in C99. sizeof(const) sizeof(volatile) Somewhat to my surprise, these are actually legal in C90 (but not in C99). const or volatile by itself is a type name, equivalent to const int and volatile int , respectively. Syntactically, const and volatile are type qualifiers . sizeof(auto)sizeof(static)sizeof(register) The distinction is that this: const int x = 42; defines x to be an object of type const int , while this: static int x = 42; defines x to be a static object of type int ( static isn't part of the type). These are all syntax errors, because auto , static , and register are not type names. Those keywords are storage-class specifiers . This explains why the first two sizeof expressions seem to work, and the others do not. But that's not particularly useful to know, because if you specify the type int (which you always should), it doesn't matter that sizeof(const) happens to be valid (in C90, not in C99). The bottom line is that you should always specify the type in any declaration. And though you can legally write sizeof (const int) , it's guaranteed to be the same as sizeof (int) , so there's not much point in using const in that context.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19709923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2689414/']}
|
jdg_374104
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31110
|
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using SGD matrix factorisation (python) using the movielens dataset to make recommendations. I have a website which allows users to give feedback which is positive or negative to whether an item is a good recommendation for a particular movie. I was wondering if I could use this feedback in my matrix factorisation. I wasn't 100% sure how I would proceed. So for example I would have a vector like m1 m2 m3m1 0 0 0m2 5 0 -4m3 0 0 0 Where m2-m1 is a score of 5 so with an example case where noone rated it negative, 5 people think its good. With the other for m2-m3 being -4 so a poor recommendation. Any help would be greatly appreciated. Edit: response from answer I am currently using a sparse matrix for user item ratings and am using bias. I have been trying to add additional input sources and am using the following to create a attribute matrix containing a genre representation: for genre in item_genres: genres[genre] = 1 self.attribute_item_matrix[i] = sum(list(genres.values())) pred = self.global_mean + self.bias_user[u] + self.bias_item[i] +np.dot(self.P[u, :],(self.Q[:, i]+self.attribute_item_matrix[i])) However, I don't think this is correct as it eventually fails and causes a nan error. I have been following this paper Matrix Factorisation Techniques for recommender systems Thanks
Now provide the response and nothing else.
|
The ratio of vocabulary vs embedding length to determine the size of other layers in a neural network doesn't really matter. Word embeddings are always around 100 and 300 in length, longer embedding vectors don't add enough information and smaller ones don't represent the semantics well enough. What matters more is the network architecture, the algorithm(s) and the dataset size. A simple way to understand this concept is that a bidirectional LSTM model with 50 neurons (nodes) followed by a fully connected layer of 70 neurons will outperform a simple MLP of 1000 neurons (nodes) connected to a embedding layer simply due to its architecture. Adding dropout will improve performance as well. In addition, even if the vocabulary is just 300 words, using pre-trained embeddings will probably yield better results than training the embeddings directly on the dataset. The same applies to data size, a dataset with more samples will make a better classifier than a dataset with just a couple thousand samples. In summary, it is preferable to try many architectures and cross-validate them (and/or ensemble them depending if you have a large enough dataset) with the smallest number of neurons possible and then start building up in size, depending on what computational resources you have and the speed of development you need. Large models slow down development speed whereas small models speed it up. This goes whether your vocabulary is the size of common crawl or just 300. As usual, try feature engineering (sentence length, special characters, etc.) and increase the dataset size as doing so often helps in whatever task you're trying to predict.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/31110', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/51499/']}
|
jdg_374105
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7553901
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In SQL Server we can use this: DECLARE @variable INT;SELECT @variable= mycolumn from myTable; How can I do the same in Oracle? I'm currently attempting the following: DECLARE COMPID VARCHAR2(20);SELECT companyid INTO COMPID from app where appid='90' and rownum=1; Why this is not working ?
Now provide the response and nothing else.
|
SELECT INTO DECLARE the_variable NUMBER;BEGIN SELECT my_column INTO the_variable FROM my_table;END; Make sure that the query only returns a single row: By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition. A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set. The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7553901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/960567/']}
|
jdg_374106
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9861841
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I got a problem similar to this question: jQuery Ajax calls in Rails 3 getting 401 Unauthorized Request I have added token_authenticatable to my devise model. In my action for the ajax call: def rate params[:kon][:IP] = request.remote_ip params[:kon][:tag_id] = params[:id] @konkurrencer = Tagrating.new(params[:kon]) @konkurrencer.save @konkurrencer.tag.rating_score += params[:kon][:ratings].to_i @konkurrencer.tag.ratings += 1 @konkurrencer.save render :nothing => true end How do I authenticate the ajax call? How to get the token key for current user. I have tried: <%= current_user.token_authentication_key %>
Now provide the response and nothing else.
|
The author posted that this was a CSRF token issue. While the solution posted works, it is not secure. A better solution was proposed in this question: https://stackoverflow.com/a/8175979/696610 I'm copying it here: You should do this: Make sure that you have <%= csrf_meta_tag %> in your layout Add beforeSend to all the ajax request to set the header like below: $.ajax({ url: 'YOUR URL HERE', type: 'POST', beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, data: 'someData=' + someData, success: function(response) { $('#someDiv').html(response); }}); Credit to https://stackoverflow.com/users/1052893/chau-hong-linh for the answer.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9861841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557527/']}
|
jdg_374107
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12230698
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to pass a tuple argument the best way ? Example: def foo(...): (Int, Int) = ...def bar(a: Int, b: Int) = ... Now I would like to pass the output of foo to bar . This can be achieved with: val fooResult = foo(...)bar(fooResult._1, fooResult._2) This approach looks a bit ugly, especially when we deal with a n -tuple with n > 2 . Also we have to store the result of foo in an extra value, because otherwise foo has to be executed more than once using bar(foo._1, foo._2) . Is there a better way to pass through the tuple as argument ?
Now provide the response and nothing else.
|
There is a special tupled method available for every function: val bar2 = (bar _).tupled // or Function.tupled(bar _) bar2 takes a tuple of (Int, Int) (same as bar arguments). Now you can say: bar2(foo()) If your methods were actually functions (notice the val keyword) the syntax is much more pleasant: val bar = (a: Int, b: Int) => //...bar.tupled(foo()) See also How to apply a function to a tuple?
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12230698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1406176/']}
|
jdg_374108
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26289
|
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the context of Artificial Intelligence, sometimes people use the word "agent" and sometimes use the word "model" to refer to the output of the whole "AI-process". For examples: "RL agents " and "deep learning models ". Are the two words interchangeable? If not, in what case should I use "agents" instead of "models" and vice versa?
Now provide the response and nothing else.
|
Agent The other answer defines an agent as a policy (as it's defined in reinforcement learning). However, although this definition is fine for most current purposes, given that currently agents are mainly used to solve video games, in the real world, an intelligent agent will also need to have a body , which Russell and Norvig call an architecture (section 2.4 of the 3rd edition of Artificial Intelligence: A Modern Approach , page 46), which should not be confused with an architecture of a model or neural network, but it's the computing device that contains the physical sensors and actuators for the agent to sense and act on the environment, respectively. So, to be more general, the agent is defined as follows agent = body + policy (brain) where the policy is what Russell and Norvig call the agent program , which is an implementation of the agent function . Alternatively, it can be defined as follows An agent is anything that can be viewed as perceiving its environment through sensors and acting upon that environment through actuators. This is just another definition given by Russell and Norvig, which I also report in this answer , where I describe different types of agents. Note that these definitions are equivalent. However, in the first one, we just emphasize that we need some means to "think" (brain) and some means to "behave" (body). These definitions are quite general, so I think people should use them, although, as I said above, sometimes people refer to an agent as just the policy. Model In this answer , I describe what a model is or what I like to think a model is, and how it is different from a function. In AI, a model can refer to different but somehow related concepts. For example, in reinforcement learning , a model typically refers to $p(s', r \mid s, a)$ , i.e. the joint probability distribution over the next state $s'$ and reward $r$ , given the current state $s$ and action $a$ taken in $s$ . In deep learning , a model typically refers to a neural network, which can be used to compute (or model) different functions. For example, a neural network can be used to compute/represent/model a policy, so, in this case, there would be no actual difference between a model and an agent (if defined as a policy, without a body). However, conceptually, at a higher-level, these would still be different (in the same way that biological neural networks are different from the brain). More generally, in machine learning , a model typically refers to a system that can be changed to compute some function. Examples of models are decision trees, neural networks, linear regression models, etc. So, as I also state in the other answer, I like to think of a model as a set of functions , so, in this sense, a model would be a hypothesis class in computational learning theory . This definition is roughly consistent with $p(s', r \mid s, a)$ , which can also be thought of as a (possibly infinite) set of functions, but note that a probability distribution is not exactly a set of functions. In the context of knowledge bases , a model is an assignment to the variables, which represents a "possible world". See section 7.3, page 240, of the cited book . There are possible other uses of the word model (both in the context of AI, e.g. in the context of planning , there's often the idea of a conceptual model , which is similar to an MDP in RL, and in other areas), but the definitions given above should be more or less widely applicable in their contexts. What is the difference between an agent and a model? Given that there are different possible definitions of a model depending on the context, it's not easy to briefly state what the difference between the two is. So, here's the difference in the context of RL (and you can now find out the differences in other contexts by using the different definitions): an agent can have a model of the world, which allows it to predict e.g. the reward it will receive given its current state and some action that it decides to take. The model can allow the agent to plan. In this same context, a model could also refer to the specific system (e.g. a neural network) used to compute/represent the policy of the agent, but note that people usually refer to $p(s', r \mid s, a)$ when they use the word model in RL. See this post for more details.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://ai.stackexchange.com/questions/26289', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/16565/']}
|
jdg_374109
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1671668
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Actionscript supports a [RemoteClass] metadata tag that is used in BlazeDS to provide data-binding hints for marshalling AMF binary objects from Java to BlazeDS. For example: Java: package sample; public class UserInfo{ private String userName; public String getUserName() { return userName; } public void setUserName(String value) { userName = value; }} Actionscript: [Bindable][RemoteClass(alias="sample.UserInfo")]public class UserInfo{ public var userName:String=”";} How exactly is the [RemoteClass] implemented in the BlazeDS framework and could you override that behavior and provide a custom data-binding remoting framework (e.g. a JSON message passing system) that you could bind to the Actionscript [Bindable], [RemoteClass] class?
Now provide the response and nothing else.
|
[RemoteClass(alias="com.example.MyClass")] is a Flex shorthand for calling flash.net.registerClassAlias() : public function registerClassAlias(aliasName:String, classObject:Class):void To access those registered alias classes at runtime (to write a custom JSON data serialization framework) you can call: getClassByAlias (aliasName:String):ClassLooks up a class that previously had an alias registered through a call to the registerClassAlias() method. For outgoing encoding from AS to Java you need to retrieve the aliased class name, you can do that by calling flash.utils.describeType() and use "reflection" on your Actionscript object's class to query attributes, properties, methods of the object. For example the following code snippet for ObjectCodec.as seems to retrieve the alias attribute by using "@": override protected function encodeComplex(o:Object, b:IBinary, context:IContext=null):void{ var desc:XML = describeType(o); var classAlias:String = desc.@alias; //...}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1671668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98050/']}
|
jdg_374110
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3452364
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been reading up on DDD and I think I may be using services wrong or at least in a not so ideal way. My service classes tend to have quite a few instance variables containing repository references and they seem to do a lot of work (i.e have a lot of methods). Is it advisable to create more focused services? Like one method per service that performs some specific logic? Also, should service classes store instance variables to other entities? I read something about services being stateless, I'm not sure if I am breaking that rule by having those instance variables. Thanks!
Now provide the response and nothing else.
|
My service classes tend to have quitea few instance variables... This is not necessarily a code-smell. If your service requires many dependencies to complete its work, then this is simply a fact. ...they seem to do a lot of work (i.ehave a lot of methods). Is it advisable to create more focused services? As a general rule, the more granular you can make your service-interfaces (i.e. the fewer methods), the better (ever had to trawl through an interface with fifty methods on it looking for the one that you want to call?). But unless you are releasing as a public API, the granularity of your service-interfaces can be refined as you go along. Often, when starting a project, I will begin with just one service, and split it out over time. If you are the consumer of these services, then when you start to feel the pain of an interface getting to large, you will know it is time to break it up. Of course, if this is a public API, then you will have to do a lot more up-front design. Also, should service classes store instance variables to other entities? I read something about services being stateless, I'm not sure if I am breaking that rule by having those instance variables. Storing dependencies as instance variables does not necessarily imply that your service is not stateless, as long as the instance variables are also stateless. To be considered stateless, method calls on a service must not in any way depend on previous methods having being called. You should be able to load a single instance of service, and have it shared for your application (i.e. an instance of a stateless service should not be specific to a particular user's session). In other words, your service should not maintain any state between method calls. Storing a stateless repository dependency as a variable on a service instance does not violate this requirement. The reason stateless services is a desirable goal, is having no state greatly reduces the possibility of bugs. It simplifies the testing of a service method by restricting the test-cases to varying the parameters passed in, rather than having to worry about the previous state of the service. It can also offer performance benefits.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3452364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173432/']}
|
jdg_374111
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
418467
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I've got a bunch of files that are all >100 lines long. I'd like to trim off the top 14 lines and the bottom 9 lines, leaving only the lines in the middle. This command will trim off the top fourteen: cat myfile.txt | tail -n +15 Is there another command I can pipe through to trim off the bottom 9 without explicitly passing the length of the file? Edited to add: My version of head (Mac OS 10.5) doesn't accept a negative number of lines as a parameter.
Now provide the response and nothing else.
|
This will work on OS X and might be a bit more easily understandable than the sed example: < myfile.txt tail -n +15 | tail -r | tail -n +10 | tail -r Of course, if you can get your hands on GNU's version of head , it can be done even more elegantly: < myfile.txt tail -n +15 | head -n -9 Be aware the tail starts at the nth line while head skips n lines of the input.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/418467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20021/']}
|
jdg_374112
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4659929
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to use UTF-8 in my resource properties using Java's ResourceBundle . When I enter the text directly into the properties file, it displays as mojibake. My app runs on Google App Engine. Can anyone give me an example? I can't get this work.
Now provide the response and nothing else.
|
Java 9 and newer From Java 9 onwards property files are encoded as UTF-8 by default, and using characters outside of ISO-8859-1 should work out of the box. Java 8 and older The ResourceBundle#getBundle() uses under the covers PropertyResourceBundle when a .properties file is specified. This in turn uses by default Properties#load(InputStream) to load those properties files. As per the javadoc , they are by default read as ISO-8859-1. public void load(InputStream inStream) throws IOException Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding ; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification. So, you'd need to save them as ISO-8859-1. If you have any characters beyond ISO-8859-1 range and you can't use \uXXXX off top of head and you're thus forced to save the file as UTF-8, then you'd need to use the native2ascii tool to convert an UTF-8 saved properties file to an ISO-8859-1 saved properties file wherein all uncovered characters are converted into \uXXXX format. The below example converts a UTF-8 encoded properties file text_utf8.properties to a valid ISO-8859-1 encoded properties file text.properties . native2ascii -encoding UTF-8 text_utf8.properties text.properties When using a sane IDE such as Eclipse, this is already automatically done when you create a .properties file in a Java based project and use Eclipse's own editor. Eclipse will transparently convert the characters beyond ISO-8859-1 range to \uXXXX format. See also below screenshots (note the "Properties" and "Source" tabs on bottom, click for large): Alternatively, you could also create a custom ResourceBundle.Control implementation wherein you explicitly read the properties files as UTF-8 using InputStreamReader , so that you can just save them as UTF-8 without the need to hassle with native2ascii . Here's a kickoff example: public class UTF8Control extends Control { public ResourceBundle newBundle (String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { // The below is a copy of the default implementation. String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { // Only this line is changed to make it to read properties files as UTF-8. bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8")); } finally { stream.close(); } } return bundle; }} This can be used as follows: ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control()); See also: Unicode - How to get the characters right?
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4659929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/571538/']}
|
jdg_374113
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
671252
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a partial fraction problem here, I understand everything in the problem except $t+C$, so I'd like to know where did the $t+C$ come from ? I want to solve this integral$$\int \frac{dy}{(y+2)(1-y)} = \int dt$$ $$\begin{align}1 &= \frac{A}{y+2} + \frac{B}{1-y} \\1 &= A(1-y) + B(y+2)\end{align}$$ Let $y=1$, then $1=B(3)$ and $B=1/3$. Let $y=-2$, then $1=A(3)$ and $A=1/3$ $$\begin{align}\int \frac{1/3}{y+2} + \frac{1/3}{1-y} \;dy &= \int dt\\\frac{1}{3}(\ln|y+2| - \ln|1-y|) &= \color{red}{t+C} & \text{?}\\\ln\left|\frac{y+2}{1-y}\right| &=3(t+C)\\\frac{y+2}{1-y} = Ce^{3t}\end{align}$$
Now provide the response and nothing else.
|
The word "splitting" refers historically to the splitting of a polynomial into linear factors. If we have an irreducible polynomial with coefficients in a field $K$, it may split into linear factors when considered within some larger field $L$. For example, the irreducible Real polynomial $x^2+1$ splits over the Complex numbers as $(x+i)(x-i)$.The Real numbers can be regarded as a subfield of the Complex numbers, or the Complex numbers as an extension of the Reals. With a little care about conditions - but in a wide range of useful situations - it can be proved that IF $p(x)$ is an irreducible polynomial [which means it has no non-trivial factors, not just no linear factors] over some field $F$, and $p(x)$ splits into linear factors in some larger field $L$. And $L$ is the smallest field that works (i.e. p(x) doesn't split into linear factors in any subfield of $L$) THEN any irreducible polynomial $q(x)$ with coefficients in $F$, which has a linear factor which can be extracted within $L$, will split completely into linear factors in $L$. So $L$ is a splitting field for lots of polynomials - and since the splitting property no longer belongs only to the particular polynomial we started with, $L$ is often called a splitting field without reference to any original polynomial.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/671252', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/115178/']}
|
jdg_374114
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2332833
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read the subversion book and it is clear to me that subversion does not store individual files but only deltas in order to minimize disk space. Subversion also does the same with binary files as well (this used to be a huge weakness of CVS). However I do not understand the exact mechanism. When I commit a file what happens? Subversion stores only the diff (and already has the old version) Subversion deletes the previous version, stores the new file intact and creates a reverse diff in order to "re-create" the old version if needed. Something else that I haven't thought of. The first case might seem the most logical. This however raises another question. If I have in a subversion repository a file with 1000 commits and a new developer checks out a clean copy, then subversion would have to fetch the original version (initial import) and apply 1000 diffs on this before returning the result. Is this correct? Is there some sort of caching for files where the latest version is kept as well? Basically where can I find information on the svn repository internals? Update: Apparently the backend of subversion plays a big role in this. At the timeor writing FSFS uses option 1 while BDB uses option 2. Thanks msemack!
Now provide the response and nothing else.
|
Because Subversion's repository format is entirely internal, they are free to change the representation from one revision to the next. I believe the current revision generally stores reverse deltas (your option 2), but also stores complete snapshots periodically so it doesn't have to resolve 1000 diffs before returning a result. The Subversion 1.6 release notes has a section on Filesystem storage improvements that has some notes on this, and links to other sources. Suffice to say that the details of Subversion data storage are complex and subject to change. There is also a design document in the Subversion source tree that describes the use of skip deltas in Subversion . Generally, the /notes/ directory contains several useful documents regarding Subversion internals.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2332833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60593/']}
|
jdg_374115
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
309382
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $K$ be a compact subset of $\mathbb R^2$ such that $\mathbb R^2\setminus K$ is not connected. Is it true that $K$ contains a simple closed curve?
Now provide the response and nothing else.
|
No. One counterexample is the closure of topologist's sine curve $y=\sin (1/x)$, $0<x<1$, plus a curve connecting its "good" end to the line segment at the other end. The complement is open and clearly not path-connected, hence not connected.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/309382', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59304/']}
|
jdg_374116
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29429571
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As you can see from the picture, the background image does not scale according to the height of the divs it is covering. The divs are blocks. <div style="/* background-size:100%; */background-image: url('http://www.infor.com/furniture/design2014/images/10x-technology.jpg'); margin-top: 50px; margin-bottom: 50px; padding-top: 50px; padding-bottom: 50px;"><div style="margin-left: 9%; margin-right: 9%;"><div class="block">
Now provide the response and nothing else.
|
create LinearLayout inside HorizontalScrollView,then create an imageView dynamically and add that imageview to linearLayout. Example code: <HorizontalScrollView android:id="@+id/horizontal_scroll"android:layout_width="match_parent"android:layout_height="wrap_content" > <LinearLayout android:id="@+id/linear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > </LinearLayout></HorizontalScrollView> In onCreate() method,get the id of linearLayout from the xml file and add dynamically created ImageView to linearlayout: LinearLayout layout = (LinearLayout) findViewById(R.id.linear); for (int i = 0; i < 10; i++) { ImageView imageView = new ImageView(this); imageView.setId(i); imageView.setPadding(2, 2, 2, 2); imageView.setImageBitmap(BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher)); imageView.setScaleType(ScaleType.FIT_XY); layout.addView(imageView); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29429571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3209917/']}
|
jdg_374117
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4727901
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create or open a file to store some output in HDFS, but I'm getting a NullPointerException when I call the exists method in the second to last line of the code snippet below: DistributedFileSystem dfs = new DistributedFileSystem();Path path = new Path("/user/hadoop-user/bar.txt");if (!dfs.exists(path)) dfs.createNewFile(path);FSDataOutputStream dos = dfs.create(path); Here is the stack trace: java.lang.NullPointerException at org.apache.hadoop.dfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:390) at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:667) at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:80) at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:65) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:47) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:227) at org.apache.hadoop.mapred.TaskTracker$Child.main(TaskTracker.java:2209) What could the problem be?
Now provide the response and nothing else.
|
I think the preferred way of doing this is: Configuration conf = new Configuration();conf.set("fs.default.name", "hdfs://mynamenodehost:9000");FileSystem fs = FileSystem.get(conf);Path path = ... That way you don't tie your code to a particular implementation of FileSystem; plus you don't have to worry about how each implementation of FileSystem is initialized.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4727901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329781/']}
|
jdg_374118
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27095011
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Haskell, (value-level) expressions are classified into types , which can be notated with :: like so: 3 :: Int , "Hello" :: String , (+ 1) :: Num a => a -> a . Similarly, types are classified into kinds . In GHCi, you can inspect the kind of a type expression using the command :kind or :k : > :k IntInt :: *> :k MaybeMaybe :: * -> *> :k EitherEither :: * -> * -> *> :k NumNum :: * -> Constraint> :k MonadMonad :: (* -> *) -> Constraint There are definitions floating around that * is the kind of "concrete types" or "values" or "runtime values." See, for example, Learn You A Haskell . How true is that? We've had a few questions about kinds that address the topic in passing, but it'd be nice to have a canonical and precise explanation of * . What exactly does * mean? And how does it relate to other more complex kinds? Also, do the DataKinds or PolyKinds extensions change the answer?
Now provide the response and nothing else.
|
First off, * is not a wildcard! It's also typically pronounced "star." Bleeding edge note : There is as of Feb. 2015 a proposal to simplify GHC's subkind system (in 7.12 or later) . That page contains a good discussion of the GHC 7.8/7.10 story. Looking forward, GHC may drop the distinction between types and kinds, with * :: * . See Weirich, Hsu, and Eisenberg, System FC with Explicit Kind Equality . The Standard: A description of type expressions. The Haskell 98 report defines * in this context as : The symbol * represents the kind of all nullary type constructors. In this context, "nullary" simply means that the constructor takes no parameters. Either is binary; it can be applied to two parameters: Either a b . Maybe is unary; it can be applied to one parameter: Maybe a . Int is nullary; it can be applied to no parameters. This definition is a little bit incomplete on its own. An expression containing a fully-applied unary, binary, etc. type constructor also has kind * , e.g. Maybe Int :: * . In GHC: Something that contains values? If we poke around the GHC documentation, we get something closer to the "can contain a runtime value" definition. The GHC Commentary page "Kinds" states that "' * ' is the kind of boxed values. Things like Int and Maybe Float have kind * ." The GHC user's guide for version 7.4.1 , on the other hand, stated that * is the kind of "lifted types". (That passage wasn't retained when the section was revised for PolyKinds .) Boxed values and lifted types are a bit different. According to the GHC Commentary page "TypeType" , A type is unboxed iff its representation is other than a pointer. Unboxed types are also unlifted. A type is lifted iff it has bottom as an element. Closures always have lifted types: i.e. any let-bound identifier in Core must have a lifted type. Operationally, a lifted object is one that can be entered. Only lifted types may be unified with a type variable. So ByteArray# , the type of raw blocks of memory, is boxed because it is represented as a pointer, but unlifted because bottom is not an element. > undefined :: ByteArray#Error: Kind incompatibility when matching types: a0 :: * ByteArray# :: # Therefore it appears that the old User's Guide definition is more accurate than the GHC Commentary one: * is the kind of lifted types. (And, conversely, # is the kind of unlifted types.) Note that if types of kind * are always lifted, for any type t :: * you can construct a "value" of sorts with undefined :: t or some other mechanism to create bottom. Therefore even "logically uninhabited" types like Void can have a value, i.e. bottom. So it seems that, yes, * represents the kind of types that can contain runtime values, if undefined is your idea of a runtime value. (Which isn't a totally crazy idea, I don't think.) GHC Extensions? There are several extensions which liven up the kind system a bit. Some of these are mundane: KindSignatures lets us write kind annotations , like type annotations. ConstraintKinds adds the kind Constraint , which is, roughly, the kind of the left-hand side of => . DataKinds lets us introduce new kinds besides * and # , just as we can introduce new types with data , newtype , and type . With DataKinds every data declaration (terms and conditions may apply) generates a promoted kind declaration. So data Bool = True | False introduces the usual value constructor and type name; additionally, it produces a new kind , Bool , and two types: True :: Bool and False :: Bool . PolyKinds introduces kind variables . This just a way to say "for any kind k " just like we say "for any type t " at the type level. As regards our friend * and whether it still means "types with values", I suppose you could say a type t :: k where k is a kind variable could contain values, if k ~ * or k ~ # .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27095011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1186208/']}
|
jdg_374119
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
266213
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I think $L^\infty(\Omega, \mathcal{F}, \mu)\supseteq L^p(\Omega, \mathcal{F}, \mu), \forall p \in (0, \infty)$? My reason is $L^\infty$ is defined as the set of measurable functions that are bounded up to a set of measure zero, and if $f \notin L^\infty$, then there exists a subset of measure nonzero on which $|f|$ is $\infty$, so $f \notin L^p, \forall p \in (0, \infty)$. So I wonder why "If $\mu$ is finite, then $L^\infty(\Omega, \mathcal{F}, \mu)\subseteq L^p(\Omega, \mathcal{F}, \mu)$ for each $p$"? If we both are right, then If $\mu$ is finite, $L^\infty = L^p$? This is a spinoff of a reply to my earlier question . Thanks!
Now provide the response and nothing else.
|
The general result is described here : for any measure space $(S,\mu)$, and $0\leq p<q\leq \infty$, $L^q(S,\mu)\subseteq L^p(S,\mu)$ $\iff$ $S$ does not contain sets of arbitrarily large measure $L^p(S,\mu)\subseteq L^q(S,\mu)$ $\iff$ $S$ does not contain sets of arbitrarily small (non-zero) measure Therefore, in particular, for a finite measure space $(S,\mu)$ we have $L^q(S,\mu)\subseteq L^p(S,\mu)$ for all $0\leq p<q\leq \infty$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/266213', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1281/']}
|
jdg_374120
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16183971
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to redo all of my Haskell homework problems using Erlang, and one thing that gets me is how to use a list of functions that don't have all of their parameters. Example: I'm trying to use this fold, but I don't know how to pass in the functions so that it operates on the accumulator %%inside my module)add(X,Y) -> X + Y.multiply(X,Y) -> X*Y. Afterwards using this in the command line: lists:foldl(fun(Function,Accumulator) -> Function(Accumulator) end, 3, [add(3),multiply(5)]).
Now provide the response and nothing else.
|
In Erlang you must call function passing all parameters it requires. But you can easily avoid it by creating an anonymous function which takes only those parameters you need and then calls your function rightly. If you need a function which takes one parameter X and calls function add(3, X) you can create an anonymous function like that: fun (X) -> add(3, X) end This is an example for your task: lists:foldl(fun (Function, Accumulator) -> Function(Accumulator) end, 3, [fun (X) -> add(3, X) end, fun (X) -> multiply(5, X) end]).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16183971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1331329/']}
|
jdg_374121
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1639291
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I run the following code using PowerShell to get a list of add/remove programs from the registry: Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { Write-Output $_.GetValue("DisplayName") } ` | Out-File addrem.txt I want the list to be separated by newlines per each program. I've tried: Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { Write-Output $_.GetValue("DisplayName") `n } ` | out-file test.txtGet-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object {$_.GetValue("DisplayName") } ` | Write-Host -Separator `nGet-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { $_.GetValue("DisplayName") } ` | foreach($_) { echo $_ `n } But all result in weird formatting when output to the console, and with three square characters after each line when output to a file. I tried Format-List , Format-Table , and Format-Wide with no luck. Originally, I thought something like this would work: Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { "$_.GetValue("DisplayName") `n" } But that just gave me an error.
Now provide the response and nothing else.
|
Or, just set the output field separator (OFS) to double newlines, and then make sure you get a string when you send it to file: $OFS = "`r`n`r`n""$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" | out-file addrem.txt Beware to use the ` and not the ' . On my keyboard (US-English Qwerty layout) it's located left of the 1 . (Moved here from the comments - Thanks Koen Zomers)
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1639291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198358/']}
|
jdg_374122
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15705895
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to have generic method which returns default value for passed type, but for collection type I'd like to get empty collection instead of null, for example: GetDefault<int[]>(); // returns empty array of int'sGetDefault<int>(); // returns 0GetDefault<object>(); // returns nullGetDefault<IList<object>>(); // returns empty list of objects The method I started to write is following: public static T GetDefault<T>(){ var type = typeof(T); if(type.GetInterface("IEnumerable") != null)) { //return empty collection } return default(T); } How to complete it ? EDIT: If anyone would like get default value of some type, based on type instance instead of type identifier , this construction below can be used, i.e.: typeof(int[]).GetDefault(); The implementation is internally based on @280Z28 answer: public static class TypeExtensions{ public static object GetDefault(this Type t) { var type = typeof(Default<>).MakeGenericType(t); var property = type.GetProperty("Value", BindingFlags.Static | BindingFlags.Public); var getaccessor = property.GetGetMethod(); return getaccessor.Invoke(null, null); }}
Now provide the response and nothing else.
|
You can use the magic of a static constructor to do this efficiently. To use the default value in code, simply use Default<T>.Value . The value will only be evaluated for any given type T once for the duration of your application. public static class Default<T>{ private static readonly T _value; static Default() { if (typeof(T).IsArray) { if (typeof(T).GetArrayRank() > 1) _value = (T)(object)Array.CreateInstance(typeof(T).GetElementType(), new int[typeof(T).GetArrayRank()]); else _value = (T)(object)Array.CreateInstance(typeof(T).GetElementType(), 0); return; } if (typeof(T) == typeof(string)) { // string is IEnumerable<char>, but don't want to treat it like a collection _value = default(T); return; } if (typeof(IEnumerable).IsAssignableFrom(typeof(T))) { // check if an empty array is an instance of T if (typeof(T).IsAssignableFrom(typeof(object[]))) { _value = (T)(object)new object[0]; return; } if (typeof(T).IsGenericType && typeof(T).GetGenericArguments().Length == 1) { Type elementType = typeof(T).GetGenericArguments()[0]; if (typeof(T).IsAssignableFrom(elementType.MakeArrayType())) { _value = (T)(object)Array.CreateInstance(elementType, 0); return; } } throw new NotImplementedException("No default value is implemented for type " + typeof(T).FullName); } _value = default(T); } public static T Value { get { return _value; } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15705895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270315/']}
|
jdg_374123
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29795299
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Android Support Library 22.1 was released yesterday. Many new features were added into the v4 support library and v7, among which android.support.v7.util.SortedList<T> draws my attention. It's said that, SortedList is a new data structure, works with RecyclerView.Adapter , maintains the item added/deleted/moved/changed animations provided by RecyclerView . It sounds like a List<T> in a ListView but seems more advanced and powerful. So, what is the difference between SortedList<T> and List<T> ? How could I use it efficiently? What's the enforcement of SortedList<T> over List<T> if it is so? Could somebody post some samples of it? Any tips or codes will be appreciated. Thanks in advance.
Now provide the response and nothing else.
|
SortedList handles the communication to the Recycler adapter via Callback . One difference between SortedList and List is seen in the addAll helper method in the sample below. public void addAll(List<Page> items) { mPages.beginBatchedUpdates(); for (Page item : items) { mPages.add(item); } mPages.endBatchedUpdates(); } Keeps last added item Say I have 10 cached items to load immediately when my recycler list is populated. At the same time, I query my network for the same 10 items because they could have changed since I cached them. I can call the same addAll method and SortedList will replace the cachedItems with fetchedItems under the hood (always keeps the last added item). // After creating adaptermyAdapter.addAll(cachedItems)// Network callbackmyAdapter.addAll(fetchedItems) In a regular List , I would have duplicates of all my items (list size of 20). With SortedList its replaces items that are the same using the Callback's areItemsTheSame . Its smart about when to update the Views When the fetchedItems are added, onChange will only be called if one or more of the Page 's title changed. You can customize what SortedList looks for in the Callback's areContentsTheSame . Its performant If you are going to add multiple items to a SortedList, BatchedCallback call convert individual onInserted(index, 1) calls into one onInserted(index, N) if items are added into consecutive indices. This change can help RecyclerView resolve changes much more easily. Sample You can have a getter on your adapter for your SortedList , but I just decided to add helper methods to my adapter. Adapter Class: public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private SortedList<Page> mPages; public MyAdapter() { mPages = new SortedList<Page>(Page.class, new SortedList.Callback<Page>() { @Override public int compare(Page o1, Page o2) { return o1.getTitle().compareTo(o2.getTitle()); } @Override public void onInserted(int position, int count) { notifyItemRangeInserted(position, count); } @Override public void onRemoved(int position, int count) { notifyItemRangeRemoved(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { notifyItemMoved(fromPosition, toPosition); } @Override public void onChanged(int position, int count) { notifyItemRangeChanged(position, count); } @Override public boolean areContentsTheSame(Page oldItem, Page newItem) { // return whether the items' visual representations are the same or not. return oldItem.getTitle().equals(newItem.getTitle()); } @Override public boolean areItemsTheSame(Page item1, Page item2) { return item1.getId() == item2.getId(); } }); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.viewholder_page, parent, false); return new PageViewHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { PageViewHolder pageViewHolder = (PageViewHolder) holder; Page page = mPages.get(position); pageViewHolder.textView.setText(page.getTitle()); } @Override public int getItemCount() { return mPages.size(); } // region PageList Helpers public Page get(int position) { return mPages.get(position); } public int add(Page item) { return mPages.add(item); } public int indexOf(Page item) { return mPages.indexOf(item); } public void updateItemAt(int index, Page item) { mPages.updateItemAt(index, item); } public void addAll(List<Page> items) { mPages.beginBatchedUpdates(); for (Page item : items) { mPages.add(item); } mPages.endBatchedUpdates(); } public void addAll(Page[] items) { addAll(Arrays.asList(items)); } public boolean remove(Page item) { return mPages.remove(item); } public Page removeItemAt(int index) { return mPages.removeItemAt(index); } public void clear() { mPages.beginBatchedUpdates(); //remove items at end, to avoid unnecessary array shifting while (mPages.size() > 0) { mPages.removeItemAt(mPages.size() - 1); } mPages.endBatchedUpdates(); }} Page class: public class Page { private String title; private long id; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getId() { return id; } public void setId(long id) { this.id = id; }} Viewholder xml: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/text_view" style="@style/TextStyle.Primary.SingleLine" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout> Viewholder class: public class PageViewHolder extends RecyclerView.ViewHolder { public TextView textView; public PageViewHolder(View itemView) { super(itemView); textView = (TextView)item.findViewById(R.id.text_view); }}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29795299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407176/']}
|
jdg_374124
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8585218
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I installed tagbar in vim. It parses the whole js file perfectly. But, when i try to use ctags, it doesnt parse the file well. Now, isnt tagbar using ctags? https://picasaweb.google.com/lh/photo/dVQuETMxHXqTEgM7Zeim1dMTjNZETYmyPJy0liipFm0?feat=directlink
Now provide the response and nothing else.
|
The simplest way is to add the data to the request. Since this is a forward, the same request is passed around to different handlers within the server. As example, let's start with a simple setup of two controllers, one forwarding to the other: @Controllerpublic class TestController { @RequestMapping(value="/test") public String showTestPage() { return "forward:/test2"; }}@Controllerpublic class TestController2 { @RequestMapping(value="/test2") public String showTestPage() { return "testPageView"; }} First way to add the data is to set it as attributes on the request. The new controllers will look like this ( A ): @Controllerpublic class TestController { @RequestMapping(value="/test") public String showTestPage(HttpServletRequest request) { request.setAttribute("param1", "foo"); request.setAttribute("param2", "bar"); return "forward:/test2"; }}@Controllerpublic class TestController2 { @RequestMapping(value="/test2") public String showTestPage(HttpServletRequest request) { String param1 = (String) request.getAttribute("param1"); String param2 = (String) request.getAttribute("param2"); return "testPageView"; }} Since the view name in the forward prefix is basically an URL , you can also have the following versions (attribute changed to parameter) ( B ): @Controllerpublic class TestController { @RequestMapping(value="/test") public String showTestPage() { return "forward:/test2?param1=foo¶m2=bar"; }}@Controllerpublic class TestController2 { @RequestMapping(value="/test2") public String showTestPage(HttpServletRequest request) { String param1 = request.getParameter("param1"); String param2 = request.getParameter("param2"); return "testPageView"; }} You can also further simplify the second controller by using annotations instead: @Controllerpublic class TestController2 { @RequestMapping(value="/test2") public String showTestPage(@RequestParam String param1, @RequestParam String param2) { return "testPageView"; }} And just for the fun of it, and to show Spring's binding behavior in action, you could do it even like this ( C ): @Controllerpublic class TestController { @RequestMapping(value="/test") public String showTestPage() { return "forward:/test2?param1=foo¶m2=bar"; }}@Controllerpublic class TestController2 { @RequestMapping(value="/test2") public String showTestPage(@ModelAttribute DummyBinder params) { String param1 = params.getParam1(); String param2 = params.getParam2(); return "testPageView"; }}class DummyBinder { private String param1; private String param2; public String getParam1() { return param1; } public void setParam1(String param1) { this.param1 = param1; } public String getParam2() { return param2; } public void setParam2(String param2) { this.param2 = param2; }} I would personally go with solution A for many parameters, and solution B for a few. Solution C has a sort of "huh...?!" effect so I would avoid it (also it works with parameters added to the URL so a few of those or you get a messy URL). Adding the data in the session would also work off course, but would extend the data's life time unnecessarily, so the best place is to add it on the request during the transition to the second controller.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8585218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/963319/']}
|
jdg_374125
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11410582
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am going to need to replace a dirty string for a clean string: -(void)setTheFilter:(NSString*)filter{ [filter retain]; [_theFilter release]; <PSEUDO CODE> tmp = preg_replace(@"/[0-9]/",@"",filter); <~PSEUDO CODE> _theFilter = tmp;} This should eliminate all numbers in the filter so that: @"Import6652" would yield @"Import" How can I do it in iOS ? Thanks!
Now provide the response and nothing else.
|
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: @"([0-9]+)" options:0 error:nil];[regex replaceMatchesInString:str options:0 range:NSMakeRange(0, [str length]) withTemplate:@""]; Swift do { let regex = try NSRegularExpression(pattern: "([0-9]+)", options: NSRegularExpressionOptions.CaseInsensitive) regex.replaceMatchesInString(str, options: NSMatchingOptions.ReportProgress, range: NSRange(0,str.characters.count), withTemplate: "")} catch {}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11410582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/817527/']}
|
jdg_374126
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20826078
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to declare a priority queue in c++ using a custom comparison function... So , I declare the queue as follows: std::priority_queue<int,std::vector<int>, compare> pq; and here's the compare function : bool compare(int a, int b){ return (a<b);} I'm pretty sure I did this before, without a class,in a similar way, but now, this code doesn't compile and I get several errors like this : type/value mismatch at argument 3 in template parameter list for 'template<class _Tp, class _Sequence, class _Compare> class std::priority_queue' Is there a way to create a compare function similar to this but without using a class? Thanks
Now provide the response and nothing else.
|
The template parameter should be the type of the comparison function. The function is then either default-constructed or you pass a function in the constructor of priority_queue . So try either std::priority_queue<int, std::vector<int>, decltype(&compare)> pq(&compare); or don't use function pointers but instead a functor from the standard library which then can be default-constructed, eliminating the need of passing an instance in the constructor: std::priority_queue<int, std::vector<int>, std::less<int> > pq; http://ideone.com/KDOkJf If your comparison function can't be expressed using standard library functors (in case you use custom classes in the priority queue), I recommend writing a custom functor class, or use a lambda .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20826078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2455103/']}
|
jdg_374127
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5333217
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using version Galleria 1.2, which I know is a bit out of date, and I am having issues with IE7 and IE8. FireFox works correctly. I tried to upgrade to 1.2.2 but ran into other issues which I will have to deal with later due to time constraints. The problem is that the background of the lightbox opens up black instead of 50% opacity. If I click on the image a second time, the lightbox opens up correctly. First click: Second click: My code: <script type="text/javascript" src="~/content/js/galleria.js"></script><script type="text/javascript">Galleria.loadTheme('~/content/css/Galleria/galleria.classic.js');</script>$('#imageGallery').galleria({ debug: true, width: 300, height: 225, showInfo: false, showCounter: false, showImagenav: false, data_source: data, on_image: function(image, thumb) { var gallery = this; $(image).click( function() { gallery.openLightbox(); }); }}); Here's the page request using Fiddler which seems to show the css file being loaded: If I load the css myself prior to the component loading, I get this: I am not sure how to fix it. Thank you!
Now provide the response and nothing else.
|
Consider this subexpression: (?<=([\.!?])|(?<=([\.!?][\'\"]))) The left side of the | is one character, while the right size is zero. You have the same issue in your larger negative look-behind too, it could be 1, 2, 3, 4, or 5 characters. Logically, a negative look-behind of (?<!A|B|C) should be equivalent to a series of look-behinds (?<!A)(?<!B)(?<!C) . A positive look-behind of (?<=A|B|C) should be equivalent to (?:(?<=A)|(?<=B)|(?<=C)) .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5333217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131818/']}
|
jdg_374128
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9233909
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently I have a column that is declared as a NUMBER. I want to change the precision of the column to NUMBER(14,2). SO, I ran the command alter table EVAPP_FEES modify AMOUNT NUMBER(14,2)' for which, I got an error : column to be modified must be empty to decrease precision or scale I am guessing it wants the column to be empty while it changes the precision and I don't know why it says we want to decrease it while we are increasing it, the data in the columns can't be lost. Is there a short workaround for this? I don't want to copy it into another table and drop it afterwards, or rename a column and copy in between columns, because there is a risk of losing data between the transfers and drops.
Now provide the response and nothing else.
|
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14. The easiest way to handle this is to rename the column, copy the data over, then drop the original column: alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;alter table EVAPP_FEES add AMOUNT NUMBER(14,2);update EVAPP_FEES set AMOUNT = AMOUNT_OLD;alter table EVAPP_FEES drop column AMOUNT_OLD; If you really want to retain the column ordering, you can move the data twice instead: alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;update EVAPP_FEES set AMOUNT = null;alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;alter table EVAPP_FEES drop column AMOUNT_TEMP;
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9233909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813040/']}
|
jdg_374129
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
92899
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have a list of 2-tuples that is visualized by ListPlot . Each 2-tuple is also associated with another graph. Now what I want to realize is to display the corresponding graph by mouse-clicking "roughly" on the data point of the 2-tuple on the ListPlot plot. I have found a similar question , but here I have ListPlot instead of BarChart . So it is not straightforward to use Button , as each data point has to be distinguished, but I do not know how to put Button on every point or whether it is a good idea to do so since there are hundreds of points. Edit 1: Regarding performance. Sample code: graphGen[x_, y_] := ListPlot[Table[{x - i^2 y, x + i y}, {i, 0, 30}]]BulkCode = Table[indexedGraphVariable[x, y] = graphGen[x, y], {x, -10., 10, 1}, {y, -10., 10, 1}];popupGraph[pt_] := indexedGraphVariable @@ pttoolRule = Tooltip[x__] :> PopupWindow[Tooltip[x], popupGraph@Last@{x}];ListPlot[Tooltip@{Flatten[ Table[{x, y}, {x, -2, 10, 1}, {y, -10, 10, 1}], 1], Flatten[Table[{x, y}, {x, -10, -1, 1}, {y, -10, 10, 1}], 1]}, ImageSize -> 1000] /. toolRule run the code open the system monitor, notice the memory used by MMA, which should be static, like 70MB click up ten popup windows and close them, check the memory again. It starts going up gradually until ~500MB if re-do the process, the used memory gets doubled This code plots only 400 points. If there are ~10000 points, the popup-window clicking will cost several GB, and the interface slows down obviously. EDIT 2: The problem emerges actually when I try to click on the point but miss clicking on the background of the ListPlot graph. The interface then starts to get slow. I suppose this is due to ToolTip 's underlying mechanism but do not know how?
Now provide the response and nothing else.
|
Here is a simple way to convert any ListPlot into something that raises a PopupWindow , and it gives you feedback about the active point before clicking it, by showing a Tooltip : popupGraph[pt_] := Graphics[Circle[pt, .1], PlotRange -> {{0, 4}, {0, 4}}, Frame -> True]toolRule = Tooltip[x__] :> PopupWindow[Tooltip[x], popupGraph@Last@{x}];ListPlot[Tooltip@{{1, 2}, {2, 3}, {3, 1}}] /. toolRule Here I made up a Graphics to show in the popup that takes the coordinate of the listed point as the center of a circle. The idea is to start with regular Tooltip s and replace them after the execution of ListPlot , using the replacement toolRule . I used the same idea in this answer .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/92899', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13580/']}
|
jdg_374130
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8589739
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My questions is, suppose we have two classes A and B. I want to have an object of B in class A. Should I use, class A{ public: A(); ~A(); B* b;}; or class A{ public: A(); ~A(); B b;}; As far as I know, in the first scenario, I can initialize the object *b using new operator and for the second scenario, I can initialize b using an initialization list if I don't want to use the default constructor of class B . Which is more convenient to use?
Now provide the response and nothing else.
|
It depends. Even if you use the pointer, you can initialize the member in the initialization list, but that's not your biggest concern. There are advantages and disadvantages to both: Using a pointer: Pros: the class will be smaller in memory you only need a forward declaration to the other class - no need to include the other header in your header can use derived objects from B as members Cons: memory management - this is a pretty big one. Do you want the memory to be managed by the class (override destructor, assignment operator and copy constructor)? Using an object: Pros: no need to worry about memory management Cons: can only use objects of the base class. What if you want to derive from B ? more memory for each instance constructor of B will be called on construction of A you need the full definition of B inside the header I'll edit my answer if I think of more.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8589739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1109792/']}
|
jdg_374131
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2896
|
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am implementing a Flanger using a fractional delay line. I am modulating the length of the delay line using a sin function. The delay line already uses linear interpolation to compute the delay output for the fractional sample. When the delay length is decreasing (and pitch is increasing), the modulated length sounds just about perfect, with no artifacts. However, when the delay length is increasing (and pitch is decreasing), I am getting a kind of "zipper" effect, with intermittent clicks, that one would expect from a non-interpolated delay line, as if sharp edges are being produced. My guess is that I need to do additional interpolation beyond the simple fractional interpolation, but I have some questions. First, why would I only hear artifacts during the period where my modulated delay length is decreasing? Second, what is the best method to reduce these artifacts? My first instinct is an all-pass filter, but is it typical to use an all-pass filter as well as an interpolation over a fractional delay length? I just want to make sure I'm getting it right, and not wasting unnecessary cpu cycles :). Some code will help. In this code, config holds all delay line info, and delaySamples is the current working length of the delay line. There are two read pointers, two write pointers, and two feedback values - one for each channel. Thanks for taking a look! void delayconfig_setDelayTime(DelayConfig *config, float delay) { config->delayTime = delay > 0 ? (delay <= 1 ? delay : 1) : 0; if (config->delayTime < 0.0001) config->delayTime = 0.0001; config->delaySamples = config->delayTime*SAMPLE_RATE; int channel; float *rp, *wp; pthread_mutex_lock( &delayMutex); for (channel = 0; channel < 2; channel++) { rp = &(config->rp[channel]); wp = &(config->wp[channel]); *rp = *wp - config->delaySamples; while (*rp < config->delaySamples) { *rp += config->delaySamples; } } pthread_mutex_unlock( &delayMutex);}float interp(float *delayBuffer, float delaySamples, float position) { position = fmod(position, delaySamples); int prev = floorf(position); int next = fmod(ceilf(position), delaySamples); float frac = position - prev; return delayBuffer[prev] + frac*(delayBuffer[next] - delayBuffer[prev]);}void delay_process(void *p, float **buffers, int size) { DelayConfig *config = (DelayConfig *)p; float out; int channel, samp; float *wp, *rp; for (channel = 0; channel < 2; channel++) { rp = &(config->rp[channel]); wp = &(config->wp[channel]); for (samp = 0; samp < size; samp++) { // here is where I'm changing my delay length. The values are tentative while I'm figuring this out, and aren't really improtant. // The important thing is thing is that it's a sin function delayconfig_setDelayTime(config, 0.0061f + 0.006f*sin(M_PI*config->count++*INV_SAMPLE_RATE)); pthread_mutex_lock(&delayMutex); if (*rp >= config->delaySamples) (*rp) -= config->delaySamples; if (*wp >= config->delaySamples) (*wp) -= config->delaySamples; float interpolated = interp(config->delayBuffer[channel], config->delaySamples, (*rp)++); int wpi = floorf((*wp)++); pthread_mutex_unlock(&delayMutex); out = interpolated*config->wet + buffers[channel][samp]*(1 - config->wet); if (out > 1) out = 1; config->delayBuffer[channel][wpi] = buffers[channel][samp] + out*config->feedback[channel]; buffers[channel][samp] = out; } }}
Now provide the response and nothing else.
|
It's a bug. M_PI*config->count++ You are processing 2 channels, but incrementing your modulation in the inner loop. So at the end of processing 1 channel, you continue to increment the modulation as you process the second channel. c1 [ 1,2,3,4] [9,10,11,12]...c2 [5,6,7,8] The modulation has a discontinuity, i.e in my simplifies example - c1 modulation jumps from '4' to '9'. resulting in zipper noise. Hope that makes sense.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/2896', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/1683/']}
|
jdg_374132
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30879429
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this dataframe: Lat Long59 44 50 151 45 1159 49 28 154 52 5659 46 42 150 45 15 How can I convert this into decimal columns? lat is in dd mm ss and long is in ddd mm ss I found a similar solution here, but couldn't adapt the regex for my case. Converting geo coordinates from degree to decimal
Now provide the response and nothing else.
|
Try this function: angle2dec <- function(angle) { angle <- as.character(angle) x <- do.call(rbind, strsplit(angle, split=' ')) x <- apply(x, 1L, function(y) { y <- as.numeric(y) y[1] + y[2]/60 + y[3]/3600 }) return(x)} Then you can apply it to each column in your data frame: new_df <- apply(df, 2L, angle2dec)new_df Lat Long[1,] 59.74722 151.7531[2,] 59.82444 154.8822[3,] 59.77833 150.7542 or just df$Lat <- angle2dec(df$Lat)df$Long <- angle2dec(df$Long)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30879429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3942806/']}
|
jdg_374133
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18142872
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to remove an object from List<T> in C# and return the removed object ? Does RemoveAt destroys the object?Do I need to first make deep copy of the object and then call RemoveAt ?
Now provide the response and nothing else.
|
RemoveAt does not destroy the object and a deep copy will not be needed. var result = list[i];list.RemoveAt(i);return result; RemoveAt is O( n - i ) vs Remove which is O( n ) (where n is the length and i is the index of the element to be removed). After you've removed an element, you have to shift everything after it down one. According to this documentation, if you want the most performant way of removing an element, swap it with last, element and then remove that. This does not maintain the order like the above. In theory this means that it is O(1) to remove the last element of a list. var result = list[i];list[i] = list[list.Length-1];list.RemoveAt(list.Length-1);return result;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18142872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2381422/']}
|
jdg_374134
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18568373
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a factory that is retrieving the data from an external source. As soon as i get the data, i use a second factory to filter it by a certain criteria. The factory property is assigned to scope. Now when i do this in my factory, it doesn't update the scope: factory.foo = [{id:1,name:'foo'}]; // doesn't work therefor also the filterin in a second factory doesn't work factory.foo = Filter.filter(); // doesn't work while this works: factory.foo.push({id:1,name:'foo'}); // works Does anyone have an idea if this is intended and why it is like this, and how to solve it? Full Sample plus plunkr app.factory('Foo',function(Filter) { var factory = { foo:[], getDataForFoo:function() { factory.foo = Filter.filter(); // doesn't work //factory.foo = [{id:1,name:'foo'},{id:1,name:'foo'}]; // doesn't work //factory.foo.push({id:1,name:'foo'}); // works } }; return factory;});app.factory('Filter',function() { var factory = { filter:function() { var arr = []; arr.push({id:1,name:'foo'}); return arr; } } return factory;});app.controller('MainCtrl', function($scope,Foo) { $scope.test = 'running'; $scope.foo = Foo.foo; $scope.click = Foo.getDataForFoo;}); Plunkr
Now provide the response and nothing else.
|
The problem is that your factory replace the reference to Factory.foo . When your scope is initialized, $scope.foo holds a reference to an array (empty). When you call Foo.getDataForFoo , it internally changes the reference to Factory.foo but your scope still hold a reference to the previous array. This is why using push works as it doesn't change the array reference, but the array content. There are a few ways to fix this. Without going in all the different options, the easiest one is to wrap your $scope.foo in a function, returning Factory.foo . This way, Angular will detect a reference change in a digest cycle and will update the view accordingly. app.controller('MainCtrl', function($scope,Foo) { $scope.test = 'running'; $scope.foo = function() { return Foo.foo }; $scope.click = Foo.getDataForFoo});// And in the view (the relevant part)<ul ng-repeat="elem in foo()"> <li>{{elem.id}} {{elem.name}}</li></ul><a href="" ng-click="click()">add</a>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18568373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717607/']}
|
jdg_374135
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49176796
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying ARKit 1.5 with image recognition and, as we can read in the code of the sample project from Apple : Image anchors are not tracked after initial detection, so create an animation that limits the duration for which the plane visualization appears. An ARImageAnchor doesn't have a center: vector_float3 like ARPlaneAnchor has, and I cannot find how I can track the detected image anchors. I would like to achieve something like in this video , that is, to have a fix image, button, label, whatever, staying on top of the detected image, and I don't understand how I can achieve this. Here is the code of the image detection result: // MARK: - ARSCNViewDelegate (Image detection results)/// - Tag: ARImageAnchor-Visualizingfunc renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let imageAnchor = anchor as? ARImageAnchor else { return } let referenceImage = imageAnchor.referenceImage updateQueue.async { // Create a plane to visualize the initial position of the detected image. let plane = SCNPlane(width: referenceImage.physicalSize.width, height: referenceImage.physicalSize.height) plane.materials.first?.diffuse.contents = UIColor.blue.withAlphaComponent(0.20) self.planeNode = SCNNode(geometry: plane) self.planeNode?.opacity = 1 /* `SCNPlane` is vertically oriented in its local coordinate space, but `ARImageAnchor` assumes the image is horizontal in its local space, so rotate the plane to match. */ self.planeNode?.eulerAngles.x = -.pi / 2 /* Image anchors are not tracked after initial detection, so create an animation that limits the duration for which the plane visualization appears. */ // Add the plane visualization to the scene. if let planeNode = self.planeNode { node.addChildNode(planeNode) } if let imageName = referenceImage.name { plane.materials = [SCNMaterial()] plane.materials[0].diffuse.contents = UIImage(named: imageName) } } DispatchQueue.main.async { let imageName = referenceImage.name ?? "" self.statusViewController.cancelAllScheduledMessages() self.statusViewController.showMessage("Detected image “\(imageName)”") }}
Now provide the response and nothing else.
|
You’re already most of the way there — your code places a plane atop the detected image, so clearly you have something going on there that successfully sets the center position of the plane to that of the image anchor. Perhaps your first step should be to better understand the code you have... ARPlaneAnchor has a center (and extent ) because planes can effectively grow after ARKit initially detects them. When you first get a plane anchor, its transform tells you the position and orientation of some small patch of flat horizontal (or vertical) surface. That alone is enough for you to place some virtual content in the middle of that small patch of surface. Over time, ARKit figures out where more of the same flat surface is, so the plane anchor’s extent gets larger. But you might initially detect, say, one end of a table and then recognize more of the far end — that means the flat surface isn’t centered around the first patch detected. Rather than change the transform of the anchor, ARKit tells you the new center (which is relative to that transform). An ARImageAnchor doesn’t grow — either ARKit detects the whole image at once or it doesn’t detect the image at all. So when you detect an image, the anchor’s transform tells you the position and orientation of the center of the image. (And if you want to know the size/extent, you can get that from the physicalSize of the detected reference image, like the sample code does.) So, to place some SceneKit content at the position of an ARImageAnchor (or any other ARAnchor subclass), you can: Simply add it as a child node of the SCNNode ARKit creates for you in that delegate method. If you don’t do something to change them, its position and orientation will match that of the node that owns it. (This is what the Apple sample code you’re quoting does.) Place it in world space (that is, as a child of the scene’s rootNode ), using the anchor’s transform to get position or orientation or both. (You can extract the translation — that is, relative position — from a transform matrix: grab the first three elements of the last column; e.g. transform.columns.3 is a float4 vector whose xyz elements are your position and whose w element is 1.) The demo video you linked to isn’t putting things in 3D space, though — it’s putting 2D UI elements on the screen, whose positions track the 3D camera-relative movement of anchors in world space. You can easily get that kind of effect (to a first approximation) by using ARSKView (ARKit+SpriteKit) instead of ARSCNView (ARKit+SceneKit). That lets you associate 2D sprites with 3D positions in world space, and then ARSKView automatically moves and scales them so that they appear to stay attached to those 3D positions. It’s a common 3D graphics trick called “billboarding”, where the 2D sprite is always kept upright and facing the camera, but moved around and scaled to match 3D perspective. If that’s the effect you’re looking for, there’s an App(le sample code) for that, too. The Using Vision in Real Time with ARKit example is mostly about other topics, but it does show how to use ARSKView to display labels associated with ARAnchor positions. (And as you’ve seen above, placing content to match an anchor position is the same no matter which ARAnchor subclass you’re using.) Here’s the key bit in their code: func view(_ view: ARSKView, didAdd node: SKNode, for anchor: ARAnchor) { // ... irrelevant bits omitted... let label = TemplateLabelNode(text: labelText) node.addChild(label)} That is, just implement the ARSKView didAdd delegate method, and add whatever SpriteKit node you want as a child of the one ARKit provides. However, the demo video does more than just sprite billboarding: the labels it associates with paintings not only stay fixed in 2D orientation, they stay fixed in 2D size (that is, they don’t scale to simulate perspective like a billboarded sprite does). What’s more, they seem to be UIKit controls, with the full set of inherited interactive behaviors that entails, not just 2D images the likes of which are ways to do with SpriteKit. Apple’s APIs don’t provide a direct way to do this “out of the box”, but it’s not a stretch to imagine some ways one could put API pieces together to get this kind of result. Here are a couple of avenues to explore: If you don’t need UIKit controls, you can probably do it all in SpriteKit, using constraints to match the position of the “billboarded” nodes ARSKView provides but not their scale. That’d probably look something like this (untested, caveat emptor): func view(_ view: ARSKView, didAdd node: SKNode, for anchor: ARAnchor) { let label = MyLabelNode(text: labelText) // or however you make your label view.scene.addChild(label) // constrain label to zero distance from ARSKView-provided, anchor-following node let zeroDistanceToAnchor = SKConstraint.distance(SKRange(constantValue: 0), to: node) label.constraints = [ zeroDistanceToAnchor ]} If you want UIKit elements, make the ARSKView a child view of your view controller (not the root view), and make those UIKit elements other child views. Then, in your SpriteKit scene’s update method, go through your ARAnchor -following nodes, convert their positions from SpriteKit scene coordinates to UIKit view coordinates, and set the positions of your UIKit elements accordingly. (The demo appears to be using popovers, so those you wouldn’t be managing as child views... you’d probably be updating the sourceRect for each popover.) That’s a lot more involved, so the details are beyond the scope of this already long answer. A final note... hopefully this long-winded answer has been helpful with the key issues of your question (understanding anchor positions and placing 3D or 2D content that follows them as the camera moves). But to clarify and give a warning about some of the key words early in your question: When ARKit says it doesn’t track images after detection, that means it doesn’t know when/if the image moves (relative to the world around it). ARKit reports an image’s position only once, so that position doesn’t even benefit from how ARKit continues to improve its estimates of the world around you and your position in it. For example, if an image is on a wall, the reported position/orientation of the image might not line up with a vertical plane detection result on the wall (especially over time, as the plane estimate improves). Update: In iOS 12, you can enable "live" tracking of detected images. But there are limits on how many you can track at once, so the rest of this advice may still apply. This doesn’t mean that you can’t place content that appears to “track” that static-in-world-space position, in the sense of moving around on the screen to follow it as your camera moves. But it does mean your user experience may suffer if you try to do things that rely on having a high-precision, real-time estimate of the image’s position. So don’t, say, try to put a virtual frame around your painting, or replace the painting with an animated version of itself. But having a text label with an arrow pointing to roughly where the image is in space is great.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49176796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1751191/']}
|
jdg_374136
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29504
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There was a Question bothering me. I tried solving it But couldn't So I finally went up to my teacher asked him for help . He told me that there was a formula for Electrostatic pressure $\rightarrow$ $$\mbox{Pressure}= \frac{\sigma^2}{2\epsilon_0}$$ And we had just to multiply it to the projected area = $\pi r^2$ When i asked him about the pressure thing he never replied. So what is it actually.Can someone Derive it/Explain it please.
Now provide the response and nothing else.
|
I haven't seen the term electrostatic pressure used explicitly before, but I can explain how to think about the problem. You need to consider the total force on each hemisphere, which is of course the integral over the sphere of the (vector) force per unit area. Take, then, a surface element $dA$, with charge $\sigma dA$. As is nicely explained by Purcell , the force on such a surface element is given by the average of the electric field inside and outside. Since the field inside vanishes, the total force on the surface element is then $$d\mathbf{F}=\frac{1}{2}\sigma dA\times\frac{4\pi R^2\sigma}{4\pi\epsilon_0}\frac{\hat{\mathbf{r}}}{R^2}=\frac{\sigma^2}{2\epsilon_0}\hat{\mathbf{r}}\,dA.$$By symmetry, the total force on each hemisphere will be along the axis of the problem, which I take in the $z$ direction. This total force will then be$$\mathbf{F}=\int d\mathbf{F}=\hat{\mathbf{z}}\int\frac{\sigma^2}{2\epsilon_0}\hat{\mathbf{z}}\cdot\hat{\mathbf{r}}dA=\hat{\mathbf{z}}\frac{\sigma^2}{2\epsilon_0}R^2\int\cos(\theta)d\Omega=\frac{\sigma^2\pi R^2}{2\epsilon_0}\hat{\mathbf{z}}.$$ The effect is indeed like having a gas inside exerting an outward pressure $p=\frac{dF}{dA}=\frac{\sigma^2}{2\epsilon_0}$, but this is hardly general - it depends on the precise, global arrangement of charges of this particular problem, while giving the impression of being a purely local thing (since it depends only on the "local" charge density, which is of course also a global parameter). If you do accept this "pressure" then yes, the total force is this constant pressure times the area vector of the surface, which is $\pi R^2\hat{\mathbf{z}}$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/29504', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8923/']}
|
jdg_374137
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32381
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can we compute the localization of the ring $\mathbb{Z}/6\mathbb{Z}$ at the prime ideal $2\mathbb{Z}/\mathbb{6Z}$? (or how do we see that this localization is an integral domain)?
Now provide the response and nothing else.
|
The localization of a ring $R$ at a prime $P$ is the local ring $R_P$, having maximal ideal $PR_P$. In this case, $R=\mathbb{Z}/6\mathbb{Z}$ and $P=2\mathbb{Z}/6\mathbb{Z}$, so that the maximal ideal $$PR_P=\{\textstyle\frac{r}{s}\mid r\in P, s\notin P\}=\{\frac{0}{1},\frac{2}{1},\frac{4}{1},\frac{0}{3},\frac{2}{3},\frac{4}{3},\frac{0}{5},\frac{2}{5},\frac{4}{5}\}$$However, note that $\frac{r_1}{s_1}=\frac{r_2}{s_2}$ iff there is a $u\notin P$ such that $u(r_1s_2-r_2s_1)=0$. Thus, for example $\frac{2}{1}=\frac{0}{1}$ because $3(2\cdot1-0\cdot 1)=0$. In fact every element of $PR_P$ is 0, by a similar computation. Thus $PR_P=0$, and a local ring whose maximal ideal is the 0 ideal is a field (and hence in particular an integral domain). Thus $R_P$ is an integral domain. EDIT: We really also have to check that $R_P$ is not in fact the zero ring (which is not an integral domain or field). We can do this directly, by checking that $\frac{1}{1}\neq\frac{0}{1}$ (because there is no $s\notin P$ such that $s(1\cdot1-0\cdot 1)=s=0$), or we can do it as follows: The canonical map $f:R\rightarrow R_P$ defined by $f(r)=\frac{r}{1}$ can easily be seen to have kernel $\ker(f)=\{r\in R\mid \exists s\notin P: sr=0\}$. For $R=\mathbb{Z}/6\mathbb{Z}$ and $P=2\mathbb{Z}/6\mathbb{Z}$, note that $\ker(f)=P$, so that by the first isomorphism theorem $R/P$ injects into $R_P$, so that $R_P$ is not the zero ring.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/32381', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_374138
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47977238
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While implementing a Kronecker-product for pedagogical reasons (without using the obvious and readily available np.kron() ), I obtained a 4 dimensional array as an intermediate result, which I've to reshape to get the final result. But, I still can't wrap my head around reshaping these high dimensional arrays. I have this 4D array: array([[[[ 0, 0], [ 0, 0]], [[ 5, 10], [15, 20]]], [[[ 6, 12], [18, 24]], [[ 7, 14], [21, 28]]]]) This is of shape (2, 2, 2, 2) and I'd like to reshape it to (4,4) . One might think that this is obvious to do with np.reshape(my4darr, (4,4)) But, the above reshape does not give me the expected result which is: array([[ 0, 5, 0, 10], [ 6, 7, 12, 14], [ 0, 15, 0, 20], [18, 21, 24, 28]]) As you can see, all the elements in the expected result are present in the 4D array. I just can't get the hang of doing the reshape correctly as needed. In addition to the answer, some explanation of how to do the reshape for such high dimensional arrays would be really helpful. Thanks!
Now provide the response and nothing else.
|
General idea for nd to nd transformation The idea with such nd to nd transformation is using just two things - Permute axes (with numpy.transpose or numpy.moveaxis or numpy.rollaxis if the needed permute order is a rolled one or numpy.swapaxes if just two axes need to be swapped) and Reshape. Permute axes : To get the order such that the flattened version corresponds to the flattened version of output. So, if you somehow end up using it twice, look again because you shouldn't. Reshape : To split the axes or bring the final output to the desired shape. Splitting axes is needed mostly at the start, when the input is of lower-dim and we are needed to split into blocks. Again, you shouldn't need this more than twice. Hence, generally we would have three steps : [ Reshape ] ---> [ Permute axes ] ---> [ Reshape ] Create more axes Bring axes Merge axes into correct order Back-tracking method The safest way to solve, given the input and output is through, what one could call as the back-tracking method, i.e. split the axes of the input (when going from smaller nd to bigger nd ) or split the axes of the output (when going from bigger nd to smaller nd ). The idea with the splitting is to bring the number of dims of the smaller nd one same as the bigger nd one. Then, study the strides of the output and match it up against the input to get the required permute order. Finally, a reshape (default way or C order) might be needed at the end, if the final one is a smaller nd one, to merge axes. If both input and output are of same number of dims, then we would need to split both and break into blocks and study their strides against each other. In such cases, we should have the additional input parameter of block sizes, but that's probably off-topic. Example Let's use this specific case to demonstrate how to apply those strategies. In here, the input is 4D , while output is 2D . So, most probably, we won't need reshape to split. So, we need to start with permuting axes. Since, the final output is not 4D , but a 2D one, we would need a reshape at the end. Now, the input here is : In [270]: aOut[270]: array([[[[ 0, 0], [ 0, 0]], [[ 5, 10], [15, 20]]], [[[ 6, 12], [18, 24]], [[ 7, 14], [21, 28]]]]) The expected output is : In [271]: out Out[271]: array([[ 0, 5, 0, 10], [ 6, 7, 12, 14], [ 0, 15, 0, 20], [18, 21, 24, 28]]) Also, this is a bigger nd to smaller nd transformation, so the back-tracking method would involve, splitting the output and studying its strides and matching up against the corresponding values in input : axis = 3 --- --> axis = 1 ------> axis=2| axis=0| [ 0, 5, 0, 10], | [ 6, 7, 12, 14], v | [ 0, 15, 0, 20], v [18, 21, 24, 28]]) Hence, the permuted order needed is (2,0,3,1) : In [275]: a.transpose((2, 0, 3, 1))Out[275]: array([[[[ 0, 5], [ 0, 10]], [[ 6, 7], [12, 14]]], [[[ 0, 15], [ 0, 20]], [[18, 21], [24, 28]]]]) Then, simply reshape to the expected shape : In [276]: a.transpose((2, 0, 3, 1)).reshape(4,4)Out[276]: array([[ 0, 5, 0, 10], [ 6, 7, 12, 14], [ 0, 15, 0, 20], [18, 21, 24, 28]]) More examples I dug up my history and found few Q&As based on nd to nd transformations. These could serve as other example cases, albeit with lesser explanation (mostly). As mentioned earlier, at most two reshapes and at most one swapaxes / transpose did the job everywhere. They are listed below : Python Reshape 3d array into 2d reshape an array using python/numpy Merging non-overlapping array blocks Conversion from a Numpy 3D array to a 2D array how to reshape an N length vector to a 3x(N/3) matrix in numpy using reshape Construct image from 4D list Reshaping/Combining several sub-matrices to one matrix in multi-dimensional space Interlace various small 2D matrices into a bigger one how to retrieve every section by 3X3? Reshaping 3D Numpy Array to a 2D array Iterate in submatrices through a bigger matrix Reorganizing a 2D numpy array into 3D Numpy change shape from (3, 512, 660, 4) to (3,2048,660,1) Numpy: rotate sub matrix m of M Split a 3D numpy array into 3D blocks Converting 3D matrix to cascaded 2D Matrices Rearranging numpy array Numpy: Reshape array along a specified axis How to construct 2d array from 2d arrays How to form a matrix from submatrices? Python: Reshape 3D image series to pixel series
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47977238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2956066/']}
|
jdg_374139
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21200
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When we humans look around, we pan smoothly from one side to the other. Birds on the other hand seem to point their head in one direction for a while, then abruptly point their head in another direction and stay in the new position for a while. Then they continue with the abrupt movement. Why is that?
Now provide the response and nothing else.
|
Most species of birds have 2 foveas, the temporal fovea and the central fovea . temporal fovea, which is like ours in the sense that it looks straight ahead and offers binocular vision (i.e. the temporal foveas of both eyes point in the same direction). But birds also have a central fovea, which points sideways and is, obviously, monocular (i.e., the central foveas of both eyes look in opposite directions). So the bird has a choice of which fovea it wants to look through. It can look straight ahead with its temporal foveas, to the left with the central fovea of its left eye, or to the right with the central fovea of its right eye. And this is not a hypothetical possibility: Birds actually do switch between foveas all the time! This is why they tend to swing their heads erratically in turns of about 90° ( reference ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/21200', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/9196/']}
|
jdg_374140
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.