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 | 1288168 |
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've this confusion all the time. If I write a code which uses fake code to assert some operation, how do i trust my real implementation when it is started really using the real objects instead of fake ones. For example, I've this code -- [Test] public void CanCreateContactsWithData() { using(ISession session = factory.OpenSession()) using (ITransaction trans = session.BeginTransaction()) { _contactId = (long) session.Save(contact); trans.Commit(); } Assert.AreNotEqual(0, _contactId); } This code tests the implementation of a "contact" object whether that gets saved into database or not. If i happened to use a stub instead of a real database connection, do I need to have separate test for storing it in database? And, do you guys call that as integration testing? Answers are sincerely appreciated.
Now provide the response and nothing else.
| Martin Fowler has a good discussion here . From his article: Meszaros uses the term Test Double as the generic term for any kind of pretend object used in place of a real object for testing purposes. The name comes from the notion of a Stunt Double in movies. (One of his aims was to avoid using any name that was already widely used.) Meszaros then defined four particular kinds of double: Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example). Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'. Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive. Of these kinds of doubles, only mocks insist upon behavior verification. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1288168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125904/']} | jdg_74741 |
stackexchange | llm_judgeable_groundtruth_similarity | 141943 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For any simple Lie algebra $\mathfrak{g}$, is there a category $C$ of (possibly infinite-dimensional) representations of $\mathfrak{g}$ such the Weyl group $W$ of the corresponding root system acts in a nontrivial way on $C$? In other words, can we find such a category $C$ and for each $g \in W$, an endofunctor $$ A(g) : C \to C $$ together with natural isomorphisms $$ \alpha_{g,h} : A(g) A(h) \stackrel{\sim}{\rightarrow} A(g h) $$ perhaps obeying the obvious coherence laws? I'd be even happier if certain weights $\lambda \in \mathfrak{h}^*$ (where $\mathfrak{h}$ is the Cartan) somehow gave rise to simple objects $R_\lambda \in C$ in such a way that $$ A(g) R_\lambda \cong R_{g(\lambda)} $$ At one point I hoped the Bernstein-Gelfand-Gelfand category $\mathcal{O}$ would do the job here, because for each weight $\lambda \in \mathfrak{h}^*$ I believe there's a simple object $L_\lambda \in \mathcal{O}$. But someone more knowledgeable than me persuaded me that no endofunctors $A(g)$ sending $L_\lambda$ to $L_{g(\lambda)}$, or perhaps just no exact such functors, exist on category $\mathcal{O}$. I would love to be wrong here, or at least to learn how close (or far) the Weyl group comes to being able to act on category $\mathcal{O}$ in such a way that $$A(g) L_\lambda \cong L_{g(\lambda)}$$ Maybe we can't find such an action with exact or even right exact functors, but we can still do it with functors that preserve direct sums.
Now provide the response and nothing else.
| To follow up on what Tobias and Chuck wrote, I think you should reconsider category $\mathcal{O}$ or better yet, its principal block $\mathcal{O}_0$, but with the proviso that you have to make some sacrifices. One sacrifice is that you have to work in the derived category, not the abelian, and the other sacrifice is that you must accept a braid group action, not a Weyl group one. Once you do this, there are a beautiful pair of commuting braid group actions on $D^b(\mathcal{O}_0)$ given by shuffling and twisting functors. If you identify the Grothendieck group of $D^b(\mathcal{O}_0)$ with $\mathbb{Z}[W]$ by sending the class of the Verma module $M_{w\cdot \rho-\rho}$ to $w\in \mathbb{Z}[W]$, then these categorify the left and right actions of right and left actions of $W$ on itself, except that the functors satisfy the braid relations, not the Weyl group relations. One secret reason for this is that they really categorify the right and left action of the Hecke algebra on itself, so you can't really expect more than the braid relations. This action also really thinks that it is a Weyl group action in the following sense: the most natural way of defining them actually assigns a functor in a each element of the Weyl group, and the proof of the braid relations is really that $T_wT_{w'}=T_{ww'}$ if $\ell(w)+\ell(w')=\ell(ww')$. Perhaps this is slicing it a little finely, but to me that says you should really think of it as a Weyl group action that got upgraded a bit. EDIT: Yes, I mean the Artin group, which you can define as the group freely generated by the elements of the Weyl group, modulo the relation $T_wT_{w'}=T_{ww'}$ if $\ell(w)+\ell(w')=\ell(ww')$. If you want a monoidal category, then maybe you should think about the category of Harish-Chandra bimodules, discussed in work of Bernstein and Gelfand (that's BGG with lower Gelfand multiplicity). Let $U(\mathfrak{g})_0=U(\mathfrak{g})/I_0$ denote $U(\mathfrak{g})$ modulo the ideal $I_0$ generated by central elements that act trivially on the trivial representation. The category I have is essentially the category of bimodules you get over $U(\mathfrak{g})_0$ by looking taking all sums, quotients and extensions of the bimodules $B_V$ gotten from $U(\mathfrak{g})\otimes V$ for all finite dimensional reps $V$ by killing the left and right action of $I_0$. The right action on $U(\mathfrak{g})\otimes V$ is the obvious one ignoring $V$, and the left action is by the coproduct (this is the bimodule where tensor product of it with a left module over $U(\mathfrak{g})$ is the same as usual Hopf algebra tensoring). The derived category of HC-bimodules is monoidal under the usual tensor product, and there is a functor from the braid group (thought of as a monoidal category) to this category, which corresponds to the shuffling functors. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/141943', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2893/']} | jdg_74742 |
stackexchange | llm_judgeable_groundtruth_similarity | 2681112 |
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:
HelloI am trying to solve a geometry puzzle, its been 30 years since I was in school and I struggled with maths! I would love to get some help to find out what the radius of the bigger circle is if the radius of the smaller circle "乙" is 3.06. Are you clever enough to figure this one out? What formula do you need? What is the radius?
Now provide the response and nothing else.
| Better answer. $$q = 2 p \sqrt{2} \qquad\stackrel{p=3.06}{\to}\qquad q \approx 8.65$$ Previous answer. $$q = 2 r - r \sqrt{2} = \sqrt{2}\left( \sqrt{2} r - r \right) = \sqrt{2}\cdot 2 p \quad\to\quad q = 2 p \sqrt{2} \quad\stackrel{p=3.06}{\to}\quad q \approx 8.65$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2681112', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/538456/']} | jdg_74743 |
stackexchange | llm_judgeable_groundtruth_similarity | 263767 |
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:
Compute the limit $$\lim_{n\to\infty} \left(\int_0^{\pi} \frac{\sin^2 n x}{\sin x} \ dx-\sum_{k=1}^n \frac{1}{k}\right)$$
Now provide the response and nothing else.
| Let's suppose that $\ \displaystyle f(n):=\int_0^{\pi} \frac{\sin^2 n x}{\sin x} \ dx\ $ then :\begin{align}f(n+1)-f(n)&=\int_0^{\pi} \frac{\sin^2((n+1) x)-\sin^2(n x)}{\sin x} \ dx\\&=\int_0^{\pi} \frac{\cos(2n x)-\cos(2(n+1) x)}{2\sin x} \ dx\\&=\int_0^{\pi} \frac{\cos(2n x)(1-\cos(2x))+\sin(2nx)\sin(2x)}{2\sin x}dx\\ &=\int_0^{\pi} \frac{\cos(2n x)2\sin(x)^2)+\sin(2nx)2\sin(x)\cos(x)}{2\sin x} dx\\&=\int_0^{\pi} \cos(2n x)\sin(x)+\sin(2nx)\cos(x)\;dx\\&=\int_0^{\pi} \sin((2n+1) x)\;dx\\&=\frac 2{2n+1} \\\end{align} So that your limit (as $\ (n+1)\to +\infty$) is the series :$$f(0)+\sum_{n=0}^\infty \left(\frac 2{2n+1}-\frac 1{n+1}\right)=2\sum_{n=0}^\infty \left(\frac 1{2n+1}-\frac 1{2n+2}\right)=2\,\log(1+1)=\log(4)$$ (using the expansion of $\;\log(1+x)\,$ at $\,x=1$) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/263767', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32016/']} | jdg_74744 |
stackexchange | llm_judgeable_groundtruth_similarity | 16769 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across a Frost diagram for cyclic compounds in my book, and all my book had to offer was that it geometrically reproduces the solutions of the wave equation, and can therefore determine the relative energies of each pi molecular orbital. How, exactly, does a Frost diagram work? My book was of no use.
Now provide the response and nothing else.
| Frost developed this mnemonic patterning as an extension of the Hückel ($4n+2$) rule. A Frost diagram is usually applied to all-carbon, monocyclic, π systems. It allows one to find the number of molecular orbitals in the molecule's π system and their energetic positions. To construct a Frost diagram, proceed as follows: Draw a circle and inscribe a regular polygon with a vertex located at the bottom of the circle. The polygon has the same shape as the ring you are interested in. For example, if you are interested in benzene, draw a hexagon; for the tropylium ion, draw a heptagon. Energy-wise, the top and bottom of the circle are defined as $\alpha+2\beta$ and $\alpha-2\beta$ respectively (so the circle has radius $2\beta$); the center of the circle is located at $\alpha$; other points can be interpolated accordingly; the bottom of the circle is at lower energy than the top of the circle. Wherever a vertex of the polygon touches the circle, that is the energetic location of a molecular orbital. Using benzene as an example, the lowest MO has energy $\alpha-2\beta$; the HOMO is degenerate (2 MO's) and located at $\alpha-\beta$; the LUMO is also degenerate and located at $\alpha+\beta$. Any orbital below the center of the circle is bonding, any orbital at the center is non-bonding and any orbital in the top-half of the circle is antibonding. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/16769', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/5084/']} | jdg_74745 |
stackexchange | llm_judgeable_groundtruth_similarity | 68531 |
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:
Is there a way to return the current watt consumption on the command line? I have found about the powertop program, but have not seen a way to return the Watt consumption as a value to the command line. I'm thinking of some file that I can cat or grep .
Now provide the response and nothing else.
| On my system I can obtain the power drawn from the battery from cat /sys/class/power_supply/BAT0/power_now9616000 On Thinkpads if the tp_smapi module is loaded, the file is cat /sys/devices/platform/smapi/BAT0/power_now The value seems to be in µW, though. You can convert it with any tool you're comfortable with, e.g. awk : awk '{print $1*10^-6 " W"}' /sys/class/power_supply/BAT0/power_now9.616 W In case you cannot find the location within the sysfs file system, you can search for it: find /sys -type f -name power_now 2>/dev/null Additionally, the package lm-sensors may be used to determine the system power usage on some machines: # sensors power_meter-acpi-0power_meter-acpi-0Adapter: ACPI interfacepower1: 339.00 W (interval = 1.00 s) | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/68531', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/16766/']} | jdg_74746 |
stackexchange | llm_judgeable_groundtruth_similarity | 18736250 |
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 the following data saved as an NSString : { Key = ID; Value = { Content = 268; Type = Text; };}, { Key = ContractTemplateId; Value = { Content = 65; Type = Text; };}, I want to convert this data to an NSDictionary containing the key value pairs. I am trying first to convert the NSString to a JSON objects as follows : NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; However when I try : NSString * test = [json objectForKey:@"ID"];NSLog(@"TEST IS %@", test); I receive the value as NULL . Can anyone suggest what is the problem ?
Now provide the response and nothing else.
| I believe you are misinterpreting the JSON format for key values. You should store your string as NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; Now if you do following NSLog statement NSLog(@"%@",[json objectForKey:@"ID"]); Result would be another NSDictionary. { Content = 268; type = text;} Hope this helps to get clear understanding. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18736250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441717/']} | jdg_74747 |
stackexchange | llm_judgeable_groundtruth_similarity | 77897 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So, i would like to know the time complexity of the following codes: x = (float) rand() / rand(); // T(4)while (x >= 0.01) // T(?){ x *= 0.8; // T(?) x T(2)} Assuming that all the basic operations are perfomed once, is the best case T(1) - constant time? Since, that might only happen when the random x generated is <= 0.01. What about the average case? Is it T(?) x T(1) / 2? Thanks a lot!
Now provide the response and nothing else.
| Worst case, if the second call to rand() returns 0 and the first call doesn't, you get a floating point division by zero, and if you are using standard IEEE 754 arithmetic, the result is +infinity. In that case, the loop will run forever. If you changed your code to exclude that case, and exclude the case that rand () might return a 128 bit integer, then for any implementation the size of x is limited, so the number of multiplications by 0.8 is limited, so the runtime is O (1). | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/77897', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/74888/']} | jdg_74748 |
stackexchange | llm_judgeable_groundtruth_similarity | 4584729 |
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 $X, Y$ be normed vector spaces and $T:X\rightarrow Y$ linear. Let $S_X, S_Y$ be the unit spheres of $X, Y$ respectively. E.g. $S_X=\{x \in X:||x||_X<1\}$ If $TS_X = S_Y$ , then $T$ is surjective, continuous and $||T||=1$ . I can see the surjectivity, but cannot figure out the continuity, from which I'm sure the norm of $T$ follows. Hint please.
Now provide the response and nothing else.
| I don't have a copy of Apostol at hand, but I guess he is using this as an example of the general fact that we are not always allowed to change the order of two limit processes. Here $D$ and $n\to\infty$ in $$D(\lim_{n\to\infty} f_n(x))=\lim_{n\to\infty} D(f_n(x)).\qquad(*)$$ I'm sure Apostol explains somewhere that a suitable extra condition (like the sequence of derivatives $f_n'(x)$ converging uniformly) does allow the change of the order here. For a bit of extra we can look at the situation at $x=0$ specifically by plotting a few of the functions from the sequence. In the image you see the graphs of $f_1,f_3,f_5$ and $f_7$ . You see that near $x=0$ they have nearly identical slopes. That's exactly because $f_n'(0)=1$ for all $n$ . But you also see that the graphs follow this tangent line for shorter and shorter intervals before they begin to oscillate. You may also consider the following. Let's look at the sequence of functions $$f_n(x)=\frac1n\sin(nx+\alpha_n),$$ where $\alpha_n$ is a random phase shift. We still have $f_n\to 0$ uniformly. Only this time $f'_n(x)=\cos(nx+\alpha_n)$ need not even converge to anything anywhere (not at any $x$ ). Or even $$f_n(x)=\frac1n\sin(n^2x).$$ We still have $f_n\to0$ uniformly (the factor $1/n$ is decisive). This time $$f'_n(x)=n\cos(n^2x),$$ and $f'_n(0)\to\infty$ as $n\to\infty$ .See below for the sample plots $f_1,f_3,f_5,f_7,f_9$ from this sequence.Observe that as $n\to\infty$ the derivatives at zero $\to\infty$ , the sine waves become steeper and steeper. The point (if any) is that in general uniform convergence of a sequence itself does not say anything about the convergence of the derivatives. The power series form a notable exception , and in the case of power series we are always guaranteed that the sequence of derivatives also converges uniformly (on any compact interval contained in the interval of convergence). As we saw, a sequence of wildly oscillating ( $\Rightarrow$ larger and larger derivatives) functions can converge to zero uniformly. A sine wave can be as steep as we desire without the amplitude going up, simply increase the frequency. The amplitudes tending to zero gives uniform convergence of the functions, and this is unrelated to how steep the waves become because the frequency can (over)compensate. The general problem requiring adjustments in one's intuition really is about mixing two limit processes. This may become clearer if, instead of $D$ we think of the derivative as the limit of a sequence. Like $$f'(x)=\lim_{m\to\infty}\frac{f(x+\frac1m)-f(x)}{1/m},\qquad(**)$$ something that holds when $f$ is differentiable at $x$ . Rewritten like thisthe question is whether $$\lim_{n\to\infty}\left(\lim_{m\to\infty}\frac{f_n(x+\frac1m)-f_n(x)}{1/m}\right)\stackrel{?}{=}\lim_{m\to\infty}\left(\lim_{n\to\infty}\frac{f_n(x+\frac1m)-f_n(x)}{1/m}\right).$$ Superficially it looks like it could hold more generally, but you have encountered similar problems earlier. Compare with something from a first course on limits of sequences of numbers: $$\lim_{n\to\infty}\lim_{m\to\infty}(1+\frac1m)^n=\lim_{n\to\infty}1^n=1,$$ but $$\lim_{m\to\infty}\lim_{n\to\infty}(1+\frac1m)^n=\lim_{m\to\infty}\infty=\infty,$$ and $$\lim_{n\to\infty}(1+\frac1n)^n=e.$$ Combinations of limit processes are nuanced. Among other things the order in which the limits are taken may play a role. After this excursion one begins to appreciate "obvious" results like: Theorem. If the limits $\lim_{n\to\infty}a_n=A$ and $\lim_{n\to\infty}b_n=B$ with both $A$ and $B$ real numbers (so finite) exist, then $$\lim_{n\to\infty}\lim_{m\to\infty} a_nb_m=\lim_{m\to\infty}\lim_{a\to\infty} a_nb_m=\lim_{n\to\infty}a_nb_n=AB.$$ The content of this theorem being that under these circumstances we actually can do the limits of $(a_n)$ and $(b_n)$ separately, and in any which order we prefer. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4584729', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/509159/']} | jdg_74749 |
stackexchange | llm_judgeable_groundtruth_similarity | 62016 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose a group G acts on a chain complex K and induced action on H(K) is trivial. What "secondary operations" on H(K) can be defined in this situation? Example. If $G=\langle\sigma\rangle/\sigma^n$ acts trivially on H(K) then $x-\sigma x=dl(x)$ (for some function $l$) and a secondary operation $x\mapsto l(x)+\sigma l(x)+\dots+\sigma^{n-1}l(x)$ is well-defined mod n. And this operation is non-trivial (consider a complex $Z[G]\to Z[G]$, $x\mapsto (1-\sigma)x$). So looks like these operations has something to do with group homology, but details elude me. Update. Two nice answers explain what is the meaning of the operation from the example above (and how it can be defined for an arbitrary group). But does this construction give all operations? I.e. what structure on H(K) one needs to recover K (up to q/iso)? Like, associative multiplication on K $\Leftrightarrow$ $A_\infty$-structure on H(K); G-action on K $\Leftrightarrow$ ??? on H(K). (Perhaps, there is a very general answer: not just for k[G] but for an arbitrary algebra — or even arbitrary operad, maybe. Probably, Tyler Lawson 's comment is relevant — if somebody could elaborate on that...)
Now provide the response and nothing else.
| One family of secondary operations that arise come from trying to find the difference between "classes that look like they are acted on trivially" and "classes that are genuinely (or coherently) acted on trivially". Let $\cdots \to F_2 \to F_1 \to F_0 \to \mathbb{Z} \to 0$ be a free resolution of $\mathbb{Z}$. We get a sequence of chain complexes $0 = C_{-1} \subset C_0 \subset C_1 \subset C_2 \subset \cdots$ where $$C_i = \cdots \to 0 \to F_i \to F_{i-1} \to \cdots \to F_1 \to F_0 \to 0$$and we can look at mapping complexes of morphisms out:$$\cdots \to Hom_{\mathbb{Z}[G]}(C_2, K) \to Hom_{\mathbb{Z}[G]}(C_1, K) \to Hom_{\mathbb{Z}[G]}(C_0, K) \to 0$$This gives us a filtered chain complex and there's an associated spectral sequence. The spectral sequence starts with$$E_1^{p,q} = Hom(F_p, H^q(K))$$and has next term$$E_2^{p,q} = H^p(G, H^q(K)).$$In particular, $E_2^{0,q}$ consists of the elements in $H_q(K)$ which are fixed by the $G$-action. From here, we get a "secondary" operation: the $d_2$-differential $H^0(G, H^q(K)) \to H^2(G, H^{q-1}(K))$. For cyclic groups, you've described this on elements (modulo you need to be careful about how well-defined it is). The higher differentials give tertiary and higher operations. For a given element $x \in H^q(K)$, these measure a sequence of obstructions to finding a chain complex $L \sim K$ such that $x$ is represented in $L$ by a class honestly fixed by $G$. (I cohomologically indexed $K$, but only because people tend to complain if I don't.) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/62016', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1556/']} | jdg_74750 |
stackexchange | llm_judgeable_groundtruth_similarity | 5162810 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have two collections as follows: Collection1:"A1""A1""M1""M2" Collection2:"M2""M3""M1""A1""A1""A2" all the values are string values. I want to know if all the elements in Collection1 are contained in Collection2, but I have no guarantee on the order and a set may have multiple entries with the same value. In this case, Collection2 does contain Collection1 because Collection2 has two A1's, M1 and M2. Theres the obvious way: sorting both collections and popping off values as i find matches, but I was wondering if there's a faster more efficient way to do this. Again with the initial collections I have no guarantee on the order or how many times a given value will appear EDIT: Changed set to collection just to clear up that these aren't sets as they can contain duplicate values
Now provide the response and nothing else.
| Yes, there is a faster way, provided you're not space-constrained. (See space/time tradeoff .) The algorithm: Just insert all the elements in Set2 into a hashtable (in C# 3.5, that's a HashSet<string> ), and then go through all the elements of Set1 and check if they're in the hashtable. This method is faster (Θ(m + n) time complexity), but uses O(n) space. Alternatively, just say: bool isSuperset = new HashSet<string>(set2).IsSupersetOf(set1); Edit 1: For those people concerned about the possibility of duplicates (and hence the misnomer "set"), the idea can easily be extended: Just make a new Dictionary<string, int> representing the count of each word in the super-list (add one to the count each time you see an instance of an existing word, and add the word with a count of 1 if it's not in the dictionary), and then go through the sub-list and decrement the count each time. If every word exists in the dictionary and the count is never zero when you try to decrement it, then the subset is in fact a sub-list; otherwise, you had too many instances of a word (or it didn't exist at all), so it's not a real sub-list. Edit 2: If the strings are very big and you're concerned about space efficiency, and an algorithm that works with (very) high probability works for you, then try storing a hash of each string instead. It's technically not guaranteed to work, but the probability of it not working is pretty darn low. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5162810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127817/']} | jdg_74751 |
stackexchange | llm_judgeable_groundtruth_similarity | 33046 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
From Wikipedia (bold emphasis at the end is mine): In complexity theory and computability theory, an oracle machine is an abstract machine used to study decision problems. It can be visualized as a Turing machine with a black box, called an oracle, which is able to decide certain decision problems in a single operation. The problem can be of any complexity class. Even undecidable problems, like the halting problem, can be used. Isn't assuming the existence of a machine which can decide the halting problem... problematic? The way I've heard it explained is that it's only problematic if you assume it can solve its own halting problem or any of the "super-oracles" above it. However, if an oracle O can solve the halting problem for machine M, can't M just use O to solve its own halting problem? Isn't that a contradiction, from which all propositions follow? I'm sure I'm making an elementary mistake, so please point it out :)
Now provide the response and nothing else.
| Oracle machines are not "problematic". Let us consider oracle machines that have the halting problem as their oracle. Now, by "the halting problem" we mean the collection of all Turing machines (without oracle) that halt when started with an empty tape. This can be decided by an oracle machine with the halting problem as its oracle.However, such oracle machines with halting problem oracle cannot solve the halting problemfor Turing machines with the ordinary halting problem as their oracle.I.e., there is no oracle machine using the usual halting problem as an oracle that decidesthe set of all oracle machines with the halting problem as their oracle that halt on the empty input. In recursion theory, there is the jump operator or Turing jump that assigns to every problem$P$ (set of words, set of natural numbers, whatever you prefer), the set of all(codes of) oracle Turing machines with the oracle $P$ that halt on the empty tape.The Turing jump of a problem $P$ is strictly more complicated (more "uncomputable") than$P$ itself, i.e., no machine with oracle $P$ decides the jump of $P$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/33046', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2592/']} | jdg_74752 |
stackexchange | llm_judgeable_groundtruth_similarity | 6542822 |
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 had been programming under the assumption that, when calling a method in C# 4.0, supplying names for your arguments would not affect the outcome unless in doing so you were "skipping" one or more optional parameters. So I was a bit surprised to discover the following behavior: Given a method which takes a Func<T> , executes it and returns the result: public static T F<T>(Func<T> f){ return f();} And another method from which the above method is visible: static void Main(){ string s; calling F (without named arguments) compiles without any issues: s = F<string>(() => "hello world"); // with explicit type argument <string> s = F(() => "hello world"); // with type inference And when using a named argument... s = F<string>(f: () => "hello world"); ... the above line of code using the explicit type argument still compiles without issues. And maybe not too surprisingly, if you have ReSharper installed it will suggest that the "Type argument specification is redundant". However, when removing the type argument... s = F(f: () => "hello world"); the C# compiler will report this error: The type arguments for method 'Program.F(System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. Is there a logical explanation for this interaction between named arguments and type inference? Is this behavior documented somewhere in the language specification? I understand that it is not necessary at all for me to name the argument. However, I discovered this behavior in a much more complex scenario where I thought it might make sense to name the arguments in my method call for internal documentation purposes. I am not asking how to work around this issue. I am trying to understand some of the finer points of the language. To make things more interesting I discovered that the following all compiles without issues: Func<string> func = () => "hello world"; s = F<string>(func); s = F(func); s = F<string>(f: func); s = F(f: func);} By the way I have observed the same behavior with non-static methods. I just chose to use static methods to make the example here a bit shorter.
Now provide the response and nothing else.
| Inference is not something that will work at many nested levels in compilation. It is kind of a guess based on arguments supplied. I feel the compiler writers did not consider inferring logic along with named parameter. If you consider abstract syntax tree, Even though the logic is same, but both F(()=>"xyz")And F(f:()=>"xyz")Are different abstract syntax trees from compiler's perspective. I feel it's just a rule missed by compiler designer where even the compiler itself is a program with huge set of rules. One rule matches first case but no rule matches second one. It may be conceptually right but compiler is just a program and all rules are human coded. Ok, I guess as others have determined, its a bug and should be reported to Microsoft !! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6542822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5164/']} | jdg_74753 |
stackexchange | llm_judgeable_groundtruth_similarity | 31172451 |
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 some code that looks like this: f(a).and_then(|b| { g(b).and_then(|c| { h(c).map(|d| { do_something_with(a, b, c, d) }) })}) Where f , g , and h return Option values. I need to use all the intermediate values ( a , b , c , and d ) in the do_something_with calculation. The indentation is very deep. Is there a better way to do this? Ideally it would look something like this (which of course doesn't work): try { let b = f(a); let c = g(b); let d = h(c); do_something_with(a, b, c, d)} rescue NonexistentValueException { None}
Now provide the response and nothing else.
| Rust 1.22 The question mark operator now supports Option , so you can write your function as fn do_something(a: i32) -> Option<i32> { let b = f(a)?; let c = g(b)?; let d = h(c)?; do_something_with(a, b, c, d) // wrap in Some(...) if this doesn't return an Option} Rust 1.0 The Rust standard library defines a try! macro (and, equivalently, the ? operator, as of Rust 1.13 ) that solves this problem for Result . The macro looks like this: macro_rules! try { ($expr:expr) => (match $expr { $crate::result::Result::Ok(val) => val, $crate::result::Result::Err(err) => { return $crate::result::Result::Err($crate::convert::From::from(err)) } })} If the argument is Err , it returns from the function with that Err value. Otherwise, it evaluates to the value wrapped in Ok . The macro can only be used in a function that returns Result , because it returns the error it meets. We can make a similar macro for Option : macro_rules! try_opt { ($expr:expr) => (match $expr { ::std::option::Option::Some(val) => val, ::std::option::Option::None => return None })} You can then use this macro like this: fn do_something(a: i32) -> Option<i32> { let b = try_opt!(f(a)); let c = try_opt!(g(b)); let d = try_opt!(h(c)); do_something_with(a, b, c, d) // wrap in Some(...) if this doesn't return an Option} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31172451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283342/']} | jdg_74754 |
stackexchange | llm_judgeable_groundtruth_similarity | 3418 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I sometimes run multiple versions of Emacs from the same home directory. I have a number of byte-compiled files. Bytecode is not compatible across all Emacs versions, so I maintain separate directories for .elc files for each version range. What are the version ranges for which the bytecode is compatible? I currently have gnu-19.29gnu-20gnu-21gnu-22gnu-23gnu-24sourcex-19x-20x-21 i.e. directories for each major release, with an additional separation at 19.29 (I've never used an older version on this machine, otherwise there'd be gnu-19 ), and separate directories for GNU Emacs and XEmacs. I'm probably overly cautious, though. What is the official policy regarding bytecode compatibility across Emacs versions? Can I confidently keep using the major version? Can I merge some versions? Is there a bytecode version indication or checksum that I could query when compiling to create the directory name instead of relying on the Emacs version? Note that I'm primarily interested in full compatibility, not just backward compatibility. I might run Emacs 27.3 and byte-compile some files, and then later Emacs 27.2 with the same home directory.
Now provide the response and nothing else.
| As maintainer, I strive to preserve the following: Backward compatibility of byte-code. I.e. you should be able to take your .elc file compiled with Emacs-19 and run it in Emacs-27 successfully. Of course, in practice it doesn't always work, because backward incompatibilities are introduced either by accident or consciously (tho these are usually not specific to bytecompiled files). Full byte-code compatibility within a major version. This is followed with less care, mostly because it tends to happen automatically, but normally you should be able to byte-compile on 27.N and run it successfully on 27.1. This said, it's always recommended to byte-compile on the older version. Of course, the above is specifically about the byte compiled code, and still depends on actual general compatibility: if foo.el runs in Emacs-19 and Emacs-27, then a foo.elc compiled on Emacs-19 should work on Emacs-27. But if that foo.el doesn't work on Emacs-19 or on Emacs-27, then the foo.elc compiled on Emacs-19 probably won't work on Emacs-27. Also, there are a few cases where we consciously break backward compatibility of byte-compiled code. | {} | {'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/3418', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/25/']} | jdg_74755 |
stackexchange | llm_judgeable_groundtruth_similarity | 10423 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have been given the task of creating an PDA that recognises the language $\{a^{2n} b^{3n} \mid n = 0,1,2,\dots\}$. Am I right in thinking that it needs to have at least 3 times number of $b$'s than $a$'s? So for example:$aabbb$ would be accepted$aaabb$ would NOT be acceptedHowever, how do I show that using JFlap because I am unfamiliar with the software?
Now provide the response and nothing else.
| The following pushdown automaton should do the trick. I publish this only because the existing answer can be improved upon. (Note, I am using $e$ to denote $\epsilon$- (or $\lambda$-) transitions. The idea is that the left-hand part counts the number of $a$'s (modulo 2).Each time it has seen two $a$'s, it pushes $3$ $b$'s onto the stack. Nondeterministically, the machine can change to the right-hand state. It then matches a $b$ from the string fro each $b$ on the stack. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/10423', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/7216/']} | jdg_74756 |
stackexchange | llm_judgeable_groundtruth_similarity | 64658 |
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:
In uniform circular motion, acceleration is $\frac{v^2}{r}$ and time which it acts $\rightarrow 0$ . So $\Delta v = 0$ , but then why/how does direction change, when the acceleration should be producing no effect at all.
Now provide the response and nothing else.
| In polar coordinates, the velocity being tangent to the circle, it is directed along the $\hat{e}_{\theta}$ vector. The centripetal force is directed along the $\hat{e}_r$ vector. So $\frac{F}{m}\hat{e}_r = \frac{d\vec{v}}{dt} = \frac{d(|v|\hat{e}_\theta)}{dt} \underbrace{=}_{\text{Chain Rule}} \frac{d|v|}{dt}\hat{e}_{\theta} + |v|\frac{d\hat{e}_{\theta}}{dt}$ Now in polar coordinates, the direction vectors are not fixed, they are linked to the body so they have a time derivative. In this case, you can easily convince yourself that the time derivative of of $\hat{e}_{\theta}$ is something directed along $\hat{e}_r$. If you fail to see this, write out the polar vectors in cartesian coordinates, and derive them with respect to time assuming $\theta$ is a function of time. The above equation can then be pictorially seen as $\text{Force along}\hat{e}_r = \text{Change of norm along}\hat{e}_{\theta} + \text{Change of direction along} \hat{e}_r$ The force being always directed along $\hat{e}_r$ can only change the direction of the velocity vector. It should have a component along $e_{\theta}$ to change the norm of the velocity. An intuitive picture to your question would be this : for a very short time, the force being orthogonal to the velocity, it will only shift it's direction. As soon as this change of direction occurs, the force is again orthogonal to the velocity, and so on. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/64658', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']} | jdg_74757 |
stackexchange | llm_judgeable_groundtruth_similarity | 230495 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is an example from my top: Cpu(s): 6.0%us, 3.0%sy, 0.0%ni, 78.7%id, 0.0%wa, 0.0%hi, 0.3%si, 12.0%st I am trying to figure out the significance of the %st field. I read that it means steal cpu and it represents time spent by the hypervisor, but I want to know what that actually means to me. Does it mean I may be on a busy physical server and someone else is using too much CPU on the server and they are taking from my VM? If I am using EBS could it be related to handling EBS I/O at the hypervisor level? Is it related to things running on my VM or is it completely unaffected by me?
Now provide the response and nothing else.
| The Steal percentage (documented in the mpstat man-page) is indeed the hypervisor telling your VM that it can't have CPU resources the VM would otherwise use. This percentage is regulated in part by Amazon's CPU limiting, and VM load on that specific host. I/O load is monitored through the %io stat. You will see this most often on their t class of instances that use a CPU credit model for regulating performance. If you're seeing high percentages, chances are good you're running out of CPU credits. | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/230495', 'https://serverfault.com', 'https://serverfault.com/users/69314/']} | jdg_74758 |
stackexchange | llm_judgeable_groundtruth_similarity | 10490307 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
All the service calls in my application are implemented as tasks.When ever a task is faulted ,I need to present the user with a dialog box to retry the last operation failed.If the user chooses retry the program should retry the task ,else the execution of the program should continue after logging the exception.Any one has got a high level idea on how to implement this functionality ?
Now provide the response and nothing else.
| UPDATE 5/2017 C# 6 exception filters make the catch clause a lot simpler : private static async Task<T> Retry<T>(Func<T> func, int retryCount) { while (true) { try { var result = await Task.Run(func); return result; } catch when (retryCount-- > 0){} } } and a recursive version: private static async Task<T> Retry<T>(Func<T> func, int retryCount) { try { var result = await Task.Run(func); return result; } catch when (retryCount-- > 0){} return await Retry(func, retryCount); } ORIGINAL There are many ways to code a Retry function: you can use recursion or task iteration. There was a discussion in the Greek .NET User group a while back on the different ways to do exactly this. If you are using F# you can also use Async constructs. Unfortunately, you can't use the async/await constructs at least in the Async CTP, because the code generated by the compiler doesn't like multiple awaits or possible rethrows in catch blocks. The recursive version is perhaps the simplest way to build a Retry in C#. The following version doesn't use Unwrap and adds an optional delay before retries : private static Task<T> Retry<T>(Func<T> func, int retryCount, int delay, TaskCompletionSource<T> tcs = null) { if (tcs == null) tcs = new TaskCompletionSource<T>(); Task.Factory.StartNew(func).ContinueWith(_original => { if (_original.IsFaulted) { if (retryCount == 0) tcs.SetException(_original.Exception.InnerExceptions); else Task.Factory.StartNewDelayed(delay).ContinueWith(t => { Retry(func, retryCount - 1, delay,tcs); }); } else tcs.SetResult(_original.Result); }); return tcs.Task; } The StartNewDelayed function comes from the ParallelExtensionsExtras samples and uses a timer to trigger a TaskCompletionSource when the timeout occurs. The F# version is a lot simpler: let retry (asyncComputation : Async<'T>) (retryCount : int) : Async<'T> = let rec retry' retryCount = async { try let! result = asyncComputation return result with exn -> if retryCount = 0 then return raise exn else return! retry' (retryCount - 1) }retry' retryCount Unfortunatley, it isn't possible to write something similar in C# using async/await from the Async CTP because the compiler doesn't like await statements inside a catch block. The following attempt also fails silenty, because the runtime doesn't like encountering an await after an exception: private static async Task<T> Retry<T>(Func<T> func, int retryCount) { while (true) { try { var result = await TaskEx.Run(func); return result; } catch { if (retryCount == 0) throw; retryCount--; } } } As for asking the user, you can modify Retry to call a function that asks the user and returns a task through a TaskCompletionSource to trigger the next step when the user answers, eg: private static Task<bool> AskUser() { var tcs = new TaskCompletionSource<bool>(); Task.Factory.StartNew(() => { Console.WriteLine(@"Error Occured, continue? Y\N"); var response = Console.ReadKey(); tcs.SetResult(response.KeyChar=='y'); }); return tcs.Task; } private static Task<T> RetryAsk<T>(Func<T> func, int retryCount, TaskCompletionSource<T> tcs = null) { if (tcs == null) tcs = new TaskCompletionSource<T>(); Task.Factory.StartNew(func).ContinueWith(_original => { if (_original.IsFaulted) { if (retryCount == 0) tcs.SetException(_original.Exception.InnerExceptions); else AskUser().ContinueWith(t => { if (t.Result) RetryAsk(func, retryCount - 1, tcs); }); } else tcs.SetResult(_original.Result); }); return tcs.Task; } With all the continuations, you can see why an async version of Retry is so desirable. UPDATE: In Visual Studio 2012 Beta the following two versions work: A version with a while loop: private static async Task<T> Retry<T>(Func<T> func, int retryCount) { while (true) { try { var result = await Task.Run(func); return result; } catch { if (retryCount == 0) throw; retryCount--; } } } and a recursive version: private static async Task<T> Retry<T>(Func<T> func, int retryCount) { try { var result = await Task.Run(func); return result; } catch { if (retryCount == 0) throw; } return await Retry(func, --retryCount); } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10490307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/524321/']} | jdg_74759 |
stackexchange | llm_judgeable_groundtruth_similarity | 32506643 |
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 the following code: #include <iostream>#include <complex>using namespace std;int main() { complex<int> delta; complex<int> mc[4] = {0}; for(int di = 0; di < 4; di++, delta = mc[di]) { cout << di << endl; } return 0;} I expect it to output "0, 1, 2, 3" and stop, but it outputs an endless series of "0, 1, 2, 3, 4, 5, ....." It looks like the comparison di<4 doesn't work well and always returns true. If I just comment out ,delta=mc[di] , I get "0, 1, 2, 3" as normal. What's the problem with the innocent assignment? I am using Ideone.com g++ C++14 with -O2 option.
Now provide the response and nothing else.
| This is due to undefined behavior, you are accessing the array mc out of bounds on the last iteration of your loop. Some compilers may perform aggressive loop optimization around the assumptions of no undefined behavior. The logic would be similar to the following: Accessing mc out of bounds is undefined behavior Assume no undefined behavior Therefore di < 4 is always true since otherwise mc[di] would invoke undefined behavior gcc with optimization turned on and using the -fno-aggressive-loop-optimizations flag causes the infinite loop behavior to disappear( see it live ). While a live example with optimization but without -fno-aggressive-loop-optimizations exhibits the infinite loop behavior you observe. A godbolt live example of the code shows the di < 4 check is removed and replaced with and unconditional jmp: jmp .L6 This is almost identical to the case outlined in GCC pre-4.8 Breaks Broken SPEC 2006 Benchmarks . The comments to this article are excellent and well worth the read. It notes that clang caught the case in the article using -fsanitize=undefined which I can not reproduce for this case but gcc using -fsanitize=undefined does ( see it live ). Probably the most infamous bug around an optimizer making an inference around undefined behavior is the Linux kernel null pointer check removal . Although this is an aggressive optimizations, it is important to note that as the C++ standard says undefined behavior is: behavior for which this International Standard imposes no requirements Which essentially means anything is possible and it notes ( emphasis mine ): [...]Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results , to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).[...] In order to get a warning from gcc we need to move the cout outside the loop and then we see the following warning ( see it live ): warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations] for(di=0; di<4;di++,delta=mc[di]){ } ^ which would have likely been sufficient to provide the OP with enough information to figure out what was going on. Inconsistency like this are typical of the types of behavior we can see with undefined behavior. To get a better understanding of why such waring can be inconsitent in the face of undefined behavior Why can't you warn when optimizing based on undefined behavior? is a good read. Note, -fno-aggressive-loop-optimizations is documented in the gcc 4.8 release notes . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32506643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3423503/']} | jdg_74760 |
stackexchange | llm_judgeable_groundtruth_similarity | 15136497 |
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 the following validator in my model: class ContinuumValidator < ActiveModel::Validator def validate(record) if !record.end_time.nil? and record.end_time < record.start_time record.errors[:base] << "An event can not be finished if it did not start yet..." end endendclass Hrm::TimeEvent < ActiveRecord::Base validates_with ContinuumValidatorend How can I test it using Rspec? Here is what I have tried so far: (thanks to zetetic ) describe "validation error" do before do @time_event = Hrm::TimeEvent.new(start_time: "2012-10-05 10:00:00", end_time: "2012-10-05 09:00:00", event_type: 2) end it "should not be valid if end time is lower than start time" do @time_event.should_not be_valid end it "raises an error if end time is lower than start time" do @time_event.errors.should include("An event can not be finished if it did not start yet...") endend But I get the following errors: 1) Hrm::TimeEvent validation error raises an error if end time is lower than start time Failure/Error: @time_event.errors.should include("An event can not be finished if it did not start yet...") expected #<ActiveModel::Errors:0x007fd1d8e02c50 @base=#<Hrm::TimeEvent id: nil, start_time: "2012-10-05 08:00:00", end_time: "2012-10-05 07:00:00", event_type: 2, employee_id: nil, created_at: nil, updated_at: nil, not_punched: false, validated: false, replace_id: nil>, @messages={}> to include "An event can not be finished if it did not start yet..." Diff: @@ -1,2 +1,5 @@ -["An event can not be finished if it did not start yet..."] +#<ActiveModel::Errors:0x007fd1d8e02c50 + @base= + #<Hrm::TimeEvent id: nil, start_time: "2012-10-05 08:00:00", end_time: "2012-10-05 07:00:00", event_type: 2, employee_id: nil, created_at: nil, updated_at: nil, not_punched: false, validated: false, replace_id: nil>, + @messages={}> What am I doing wrong? And how can I achieve my goal?Any help or suggestion would be appreciated.Thanks.
Now provide the response and nothing else.
| The problem is that you're expecting @time_event.errors to behave like an array of strings. It doesn't, it returns ActiveModel::Errors. As others pointed out, you also need to trigger the validations with a call to valid? : it "raises an error if end time is lower than start time" do @time_event.valid? @time_event.errors.full_messages.should include("An event can not be finished if it did not start yet...")end | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15136497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1517876/']} | jdg_74761 |
stackexchange | llm_judgeable_groundtruth_similarity | 15442292 |
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 output to stdout and have the output "overwrite" the previous output. For example; if I output On 1/10 , I want the next output On 2/10 to overwrite On 1/10 . How can I do this?
Now provide the response and nothing else.
| stdout is a stream ( io.Writer ). You cannot modify what was already written to it. What can be changed is how that stream's represented in case it is printed to a terminal. Note that there's no good reason to assume this scenario. For example, a user could redirect stdout to a pipe or to a file at will. So the proper approach is to first check: if the stdout is going to a terminal what is that terminal's procedure to overwrite a line/screen Both of the above are out of this question's scope, but let's assume that a terminal is our device. Then usually, printing: fmt.Printf("\rOn %d/10", i) will overwrite the previous line in the terminal. \r stands for carriage return , implemented by many terminals as moving the cursor to the beginning of the current line, hence providing the "overwrite line" facility. As an example of "other" terminal with a differently supported 'overwriting', here is an example at the playground . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/15442292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_74762 |
stackexchange | llm_judgeable_groundtruth_similarity | 8610426 |
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 experiencing trouble upgrading my rails 2.3.14 / ruby 1.8.7 app to 3.1.1/1.9.2 : I have some (ActiveRecord::StatementInvalid) "Mysql2::Error: MySQL server has gone away" errors happening sporadically. It's important to precise that I never had such issues with the 'mysql' gem on 2.3.14 and the exactly same db (so the bug shouldn't come from mysql (v5.5.10)). Example : $ rails c productionLoading production environment (Rails 3.1.1)ruby-1.9.2-p290 :001 > ActiveRecord::Base.connection.active? => falseruby-1.9.2-p290 :002 > exit$ rails c productionLoading production environment (Rails 3.1.1)ruby-1.9.2-p290 :001 > ActiveRecord::Base.connection.active? => true This happens only with my (remote) production database, no problem with my local development db. I've tried to set "reconnect: true" in my database.yml but it led to a Mysql2::Error: Host '****' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts':... I've tried to isolate the problem with a little rb script only loading mysql2 and activerecord but I didn't manage to reproduce the bug that way (so it may be linked to the rails stack). I can't go back from the 'mysql2' to the 'mysql' gem because of encoding issues ( http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/ ). As a consequence, I had to rollback my production to my rails 2.3.14 app, which saddens me very much... Do you see what I can do to debug this ? I can't even find a sure way to reproduce the error... Have anyone met the same bug ? I just found few people mentionning this bug (ex : https://github.com/brianmario/mysql2/issues/213 ) but not a solution. Thanks for your help.
Now provide the response and nothing else.
| Ok, I think I solved my problem. I didn't notice it when I posted my question, but it seemed that the error was timeout related : after about 20s, activerecord losts its connection. $ rails runner "sleep 23; puts ActiveRecord::Base.connection.active?"=> true$ rails runner "sleep 25; puts ActiveRecord::Base.connection.active?"=> false So I dug further and I realized that mysql and mysql2 gems didn't deal with the MySQL 'wait_timeout' param the same way : mysql gem doesn't set it thus uses the MySQL default value 28800 , whereas mysql2 gem sets it at 2592000 if not defined in the database.yml.But I have the impression that the value 2592000 is over the max value for this param : 2147483 ! Which could lead to the unexpected behavior I described... I build a script test showing the bug : https://gist.github.com/1514154 And if I had some apparently random disconnect while loading rails console (cf my question), I think it's because of my app taking a long time to load and me sometimes waiting a few seconds before typing my command. I can't explain why we are so few to encounter this problem. Perhaps it's specific to my conf (remote database, MySQL version ?). I've tried with another remote staging database : the bug didn't reproduce... So as a conclusion, I will set wait_timeout: 2147483 in my database.yml. And maybe pull request rails... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8610426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67001/']} | jdg_74763 |
stackexchange | llm_judgeable_groundtruth_similarity | 7515309 |
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 developing a widget for turning on/off camera led of phone. I have made a widget that can work like toggle button (on/off). Behavior is like follows : Sometimes the led light remains on when i enable the widget.But it doesnot turn on/off the camera led but it changes the icon. I am not able to figure out whats the actual problem. The same thing works fine in Activity (Torch Light Application). Can anyone please explain me how can i solve my problem ? Where i am going wrong ? You can look at the code below that i have done so far onUpdate method @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { //super.onUpdate(context, appWidgetManager, appWidgetIds); remoteViews = new RemoteViews( context.getPackageName(), R.layout.widgetlayout); watchWidget = new ComponentName( context, FlashLightWidget.class ); Intent intentClick = new Intent(context,FlashLightWidget.class); intentClick.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, ""+appWidgetIds[0]); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetIds[0],intentClick, 0); remoteViews.setOnClickPendingIntent(R.id.myToggleWidget, pendingIntent); appWidgetManager.updateAppWidget( watchWidget, remoteViews ); ctx=context; } onReceive method is as follows : @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub remoteViews = new RemoteViews( context.getPackageName(), R.layout.widgetlayout); if (intent.getAction()==null) { Bundle extras = intent.getExtras(); if(extras!=null) { if(status) { status=false; remoteViews.setImageViewResource(R.id.myToggleWidget, R.drawable.shutdown1); processOnClick(); Toast.makeText(context,"Status==false-onclick",Toast.LENGTH_SHORT).show(); } else { status = true; remoteViews.setImageViewResource(R.id.myToggleWidget, R.drawable.shutdown2); processOffClick(); Toast.makeText(context,"Status==true--Ofclick",Toast.LENGTH_SHORT).show(); } } watchWidget = new ComponentName( context, FlashLightWidget.class ); (AppWidgetManager.getInstance(context)).updateAppWidget( watchWidget, remoteViews ); } } } processOffClick method private void processOffClick() { if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } } processOnClick method private void processOnClick() { if(mCamera==null) { try { mCamera = Camera.open(); } catch (Exception e) { e.printStackTrace(); } } if (mCamera != null) { Parameters params = mCamera.getParameters(); List<String> flashModes = params.getSupportedFlashModes(); if (flashModes == null) { return; } else { params.setFlashMode(Parameters.FLASH_MODE_OFF); mCamera.setParameters(params); mCamera.startPreview(); String flashMode = params.getFlashMode(); if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) { if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) { params.setFlashMode(Parameters.FLASH_MODE_TORCH); mCamera.setParameters(params); } } } } else if (mCamera == null) { //Toast.makeText(ctx, "Camera not found", Toast.LENGTH_LONG).show(); return; }}
Now provide the response and nothing else.
| After a long time, I got free to solve this problem. Here is what I did. FlashlightWidgetProvider class : public class FlashlightWidgetProvider extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Intent receiver = new Intent(context, FlashlightWidgetReceiver.class); receiver.setAction("COM_FLASHLIGHT"); receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setOnClickPendingIntent(R.id.button, pendingIntent); appWidgetManager.updateAppWidget(appWidgetIds, views); }} and BroadcastReceiver for FlashlightWidgetReceiver : public class FlashlightWidgetReceiver extends BroadcastReceiver { private static boolean isLightOn = false; private static Camera camera; @Override public void onReceive(Context context, Intent intent) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); if(isLightOn) { views.setImageViewResource(R.id.button, R.drawable.off); } else { views.setImageViewResource(R.id.button, R.drawable.on); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); appWidgetManager.updateAppWidget(new ComponentName(context, FlashlightWidgetProvider.class), views); if (isLightOn) { if (camera != null) { camera.stopPreview(); camera.release(); camera = null; isLightOn = false; } } else { // Open the default i.e. the first rear facing camera. camera = Camera.open(); if(camera == null) { Toast.makeText(context, R.string.no_camera, Toast.LENGTH_SHORT).show(); } else { // Set the torch flash mode Parameters param = camera.getParameters(); param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); try { camera.setParameters(param); camera.startPreview(); isLightOn = true; } catch (Exception e) { Toast.makeText(context, R.string.no_flash, Toast.LENGTH_SHORT).show(); } } } } } Permission required in Manifest.xml file : <uses-permission android:name="android.permission.CAMERA"></uses-permission> Also register receivers in Manifest.xml file : <receiver android:name=".FlashlightWidgetProvider" android:icon="@drawable/on" android:label="@string/app_name"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/flashlight_appwidget_info" /></receiver><receiver android:name="FlashlightWidgetReceiver"> <intent-filter> <action android:name="COM_FLASHLIGHT"></action> </intent-filter> </receiver> Important Note : This code works perfect if your phone has FLASH_MODE_TORCH supported. I have tested in Samsung Galaxy Ace 2.2.1 & 2.3.3. The code is not working because that device has no FLASH_MODE_TORCH. Works fine in HTC Salsa, Wildfire.. If anyone can test and post results here, it would be best. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7515309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/610940/']} | jdg_74764 |
stackexchange | llm_judgeable_groundtruth_similarity | 294845 |
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:
Running a brand new Ubuntu 16.04 and a Debian 8 server. Trying to connect via ssh and getting the following strange terminal output. I refer to the rectangles with the numbers in it. The problem with the language settings was introduced by myself trying to solve the just mentioned problem since I assumed some encoding problems to be responsible. After 3h of debugging I need your help! Maybe it's just a missing library? It is hard searching for such graphical problems... local@local:~$ ssh dummy@serverThe programs included with the Debian GNU/Linux system are free software;the exact distribution terms for each program are described in theindividual files in /usr/share/doc/*/copyright.Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extentpermitted by applicable law.Last login: Sat Jul 9 17:22:43 2016 from x590c3909.dyn.telefonica.de-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)]1337;RemoteHost=dummy@server]1337;CurrentDir=/home/patrick]1337;ShellIntegrationVersion=2;shell=bash]133;C;]133;D;0]1337;RemoteHost=dummy@server]1337;CurrentDir=/home/patrick]133;Adummy@server:~$ ]133;B echo $PS1 output: echo $PS1]133;C;\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\$ echo $TERM output: echo $TERM]133;C;xterm Edit: "locale" - warning fixed by this answer .
Now provide the response and nothing else.
| What your terminal is doing The "rectangles with the numbers in [them]" are the way that your terminal emulator is displaying a terminal control sequence to you, because it doesn't recognize that sequence. Specifically: There is an ECMA-48 control character (in the C1 group, for the technical) named Operating System Command , abbreviated OSC. It has the Unicode value U+009D. ECMA-48 defines a mechanism where characters in the C1 group, which require a fully clean 8-bit communications path in order to be transmitted, can be represented by an escape sequence that uses only characters with values less than U+0080 (128). These 7-bit aliases enable the use of C1 control characters on transmission paths that are not 8-bit clean. Ironically, the world has been largely 8-bit clean for decades, now. You'll most likely know one of these 7-bit aliases that is very common: ESC [ instead of the CSI control character (U+009B). The OSC control character has ESC ] as a 7-bit alias. Something on the far end of your SSH connection is expecting your terminal to understand control sequences that begin with OSC. It is transmitting them using the 7-bit alias. Your terminal doesn't fully implement ECMA-48. It's seeing ESC ] and just treating it as an ESC character followed by an ] character. And that's what it is printing. But it doesn't have a glyph for the ESC character. So it's falling back to the conventional trick of displaying characters that it doesn't have a glyph for as a box with the hexadecimal value of the (lowest 16 bits of the) Unicode code point in it. If you look closely, you'll see the numbers 00 and 1B in the box, for U+001B, the code point for the ESC character. It also doesn't correctly deal with the "spacing" of what it has printed for the ESC, i.e. the space that it takes on the screen, which is actually two character widths. So after printing the box it doesn't advance the output position enough . It then prints the ] over the top of the right-hand half of the box, as you can see. Why it has been told to do that Several terminal emulators recognize OSC as a control character sequence introducer. There's a standard form for it, even. ECMA-48 § 5.6 defines "control strings" begun with OSC and terminated with ST (U+009C, String Terminator ). What is in the control string is terminal-type specific. For example: You'll see from its doco that xterm implements such control strings, for setting fonts and window titles. However, the form of the control sequence in this case is not that of xterm. Rather, it is ␛]1337;CurrentDir=/home/patrick␇ This is the form for OSC control sequences that is understood by iTerm2. iTerm2 defines a set of control sequences introduced by OSC that are distinctly non-standard and idiosyncratic to iTerm2. They do not adhere to the ECMA-48 control string specification but terminate the control string with BEL (U+0007) rather than with ST as the standard says. Strictly speaking, that's a control string that isn't ever terminated , since any characters other than SOS and ST are permitted in the contents of a control string; and is one that with a conformant terminal emulator effectively just stops display, as the terminal simply accrues all further output as a control string. (The terminal emulator that is built in to the Linux kernel also doesn't implement standard OSC control strings. The xterm doco notes that it has bodges to support broken applications that use the non-conformant Linux kernel terminal emulator or iTerm2 forms. The form here is definitely iTerm2's, not that of the Linux kernel terminal emulator, though.) When you are using iTerm2 from your Macintosh, whatever is on the other end of the SSH connection is quietly sending iTerm2 control sequences to your terminal emulator to tell it stuff like what your shell is, what your working directory is, who you are, when you start editing at a shell prompt, when you start executing a command, and so forth. On the remote system, you have hardwired the terminal type . You've made it operate under the assumption that you're always talking to it with iTerm2. But you are now talking to it using Terminator running on Ubuntu, a different terminal emulator that has a different set of control sequences. In fact, the output even tells you this: ␛]1337;ShellIntegrationVersion=2;shell=bash␇ You've installed the iTerm2 "Shell Integration" for the Bourne Again shell on your remote system. Looking at it, it is pretty bad at checking that iTerm2 is actually the terminal that it is speaking to. So disable/uninstall it. Further reading Control Functions for Coded Character Sets . ECMA-48. ECMA International. console_codes . Linux manual pages. § 4. 2015. Matthew Freeman, George Nachman, and James A. Rosen. Proprietary Escape Codes . iTerm2 documentation. Matthew Freeman, George Nachman, and James A. Rosen. Shell Integration . iTerm2 documentation. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/294845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/135691/']} | jdg_74765 |
stackexchange | llm_judgeable_groundtruth_similarity | 3259496 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between these two. $(document).ready(function(){ ... }); (function(){ ... })(); Are these both functions called at the same time?I know, document.ready will be triggered when the entire HTML page is rendered by the browser but what about 2nd function (self calling anonymous function). Does it wait for browser to complete rendering the page or it is called whenever it is encountered?
Now provide the response and nothing else.
| $(document).ready(function(){ ... }); or short $(function(){...}); This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready. (function(){ ... })(); That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript . Therefor, its very unlikely that you can successfully act on DOM elements here. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3259496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300089/']} | jdg_74766 |
stackexchange | llm_judgeable_groundtruth_similarity | 43180053 |
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 initialize these array values directly into a Mat object. I tried using obj.put(i,j,data) but this does not work and the Mat object is still empty. i need this in java data [] = {103547.0, 2.0959531E7, 5.152769223E9, 1.415924406121E12, 2.0842905E7, 4.195143491E9, 1.025510364741E12, 5.000561607E9, 9.99289545049E11, 1.332451366923E12} Can explain to me me how to initialize a new Mat object where I directly insert the array data?
Now provide the response and nothing else.
| Your question is not entirely clear to me, but I'm going to assume you are trying to load a float array into a OpenCV Mat object in a single row. First of all, be sure to check the documentation on constructing a Mat in C++ . Since you have a 1D array and (I assume) you know the rows and columns you want to give your Mat , you should use this constructor : cv::Mat::Mat (int rows, int cols, int type, void * data, size_t step = AUTO_STEP) Here's a code example: float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };cv::Mat your_matrix = cv::Mat(1, 10, CV_32F, data);cout << your_matrix.at<float>(0,2) << endl;cout << your_matrix << endl; It will output: 3[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Of course you can change the datatype according to your needs (e.g. use int instead of float ). You can ignore the AUTO_STEP parameter, but be sure to check the documentation on the usage if you want to use it. Also, if you want to change the structure of your Mat (e.g. split the array into multiple rows) you can achieve this by changing the rows and cols arguments in the constructor: float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };cv::Mat your_matrix = cv::Mat(2, 5, CV_32F, data);cout << your_matrix.at<float>(1,2) << endl;cout << your_matrix << endl; It will output: 8[1, 2, 3, 4, 5; 6, 7, 8, 9, 10] You have now split your Mat object into two rows of 5 columns, instead of 1 row of 10 columns. In case of Java: If you want to do this in Java, you were already on the right track. However, you probably forgot to specify the rows, columns and channels/depth. Change the rows, cols and CvType according to whatever suits your data as before. You can do the following: float data[] = new float[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};Mat mat = new Mat(1, 10, CvType.CV_32F);mat.put(0, 0, data); Be sure to check the Java documentation on Mat as well! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43180053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4628906/']} | jdg_74767 |
stackexchange | llm_judgeable_groundtruth_similarity | 244168 |
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 solve the following problem: Let $(\Omega, \mathbb{A}, \mathbb{P})$ be a probability space and $X_1, X_2, \ldots, X_n$ independent real random variables.Prove that the sum $X_1 + X_2 + ... + \ldots X_n$ is $\mathbb{P}$-almost surely constant iff each $X_i$ is $\mathbb{P}$-almost surely constant. Do you have any ideas or hints how to tackle with this problem?Thanks.
Now provide the response and nothing else.
| It suffices to show: $X+Y=c$ almost surely $\Rightarrow X$ constant almost surely where $X,Y$ are independent random variables. Let $\xi,\eta \in \mathbb{R}$. By the independence we have $$\mathbb{E}e^{\imath \, (X,X+Y) \cdot (\xi,\eta)} = \mathbb{E}e^{\imath \, \xi \cdot X} \cdot \mathbb{E}e^{\imath \, (X+Y) \cdot \eta} = \mathbb{E}e^{\imath \, \xi \cdot X} \cdot \mathbb{E}e^{\imath \, \eta \cdot X} \cdot \mathbb{E}e^{\imath \, \eta \cdot Y}$$ On the other hand $$\mathbb{E}e^{\imath \, (X,X+Y) \cdot (\xi,\eta)} = \mathbb{E}e^{\imath \, (\xi+\eta) \cdot X} \cdot \mathbb{E}e^{\imath \, \eta \cdot Y}$$ Since $$\mathbb{E}e^{\imath \, \eta \cdot X} \cdot \mathbb{E}e^{\imath \, \eta \cdot Y} = \mathbb{E}e^{\imath \, (X+Y) \cdot \eta} = e^{\imath \, \eta \cdot c} (\not=0)$$ we have $\mathbb{E}e^{\imath \, \eta \cdot Y} \not= 0$ for all $\eta$. Hence we obtain from the first two equations $$\mathbb{E}e^{\imath \, (X,X) \cdot (\eta,\xi)} = \mathbb{E}e^{\imath \, (\xi+\eta) \cdot X} = \mathbb{E}e^{\imath \, X \cdot \eta} \cdot \mathbb{E}e^{\imath \, X \cdot \xi}$$ This means that $X$ is independent of $X$ and therefore almost surely constant. Remark In the last step we used the following theorem: Two random variables $U,V$ are independent $$\Leftrightarrow \forall \xi,\eta: \mathbb{E}e^{\imath (U,V) \cdot (\xi,\eta)} = \mathbb{E}e^{\imath \, U \cdot \xi} \cdot \mathbb{E}e^{\imath \, V \cdot \eta}$$ Another approach: Let $S_n := \sum_{j=1}^n X_j$. We have $0=\mathbb{V}S_n= \sum_{j=1}^n \mathbb{V}X_j$. This implies $\mathbb{V}X_j=0$ and therefore $X_j = \mathbb{E}X_j$ a.s.. The problem is that one has to show $X_j \in L^2$ (to do these calculations). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/244168', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49857/']} | jdg_74768 |
stackexchange | llm_judgeable_groundtruth_similarity | 31378347 |
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 using boto.dynamodb2 , and it seems I can use Table.query_count() . However it had raised an exception when no query filter is applied. What can I do to fix this? BTW, where is the document of filters that boto.dynamodb2.table.Table.Query can use? I tried searching for it but found nothing.
Now provide the response and nothing else.
| There are two ways you can get a row count in DynamoDB. The first is performing a full table scan and counting the rows as you go. For a table of any reasonable size this is generally a horrible idea as it will consume all of your provisioned read throughput. The other way is to use the Describe Table request to get an estimate of the number of rows in the table. This will return instantly, but will only be updated periodically per the AWS documentation. The number of items in the specified index. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31378347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2836912/']} | jdg_74769 |
stackexchange | llm_judgeable_groundtruth_similarity | 153011 |
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 need to download a large file (1GB). I also have access to multiple computers running Linux, but each is limited to a 50kB/s download speed by an admin policy. How do I distribute downloading this file on several computers and merge them after all segments have been downloaded, so that I can receive it faster?
Now provide the response and nothing else.
| The common protocols HTTP, FTP and SFTP support range requests , so you canrequest part of a file. Note that this also requires server support, so itmight or might not work in practice. You can use curl and the -r or --range option to specify the range andeventually just cat ting the files together. Example: curl -r 0-104857600 -o distro1.iso 'http://files.cdn/distro.iso'curl -r 104857601-209715200 -o distro2.iso 'http://files.cdn/distro.iso'[…] And eventually when you gathered the individual parts you concatenate them: cat distro* > distro.iso You can get further information about the file, including its size with the --head option: curl --head 'http://files.cdn/distro.iso' You can retrieve the last chunk with an open range: curl -r 604887601- -o distro9.iso 'http://files.cdn/distro.iso' Read the curl man page for more options and explanations. You can further leverage ssh and tmux to ease running and keepingtrack of the downloads on multiple servers. | {} | {'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/153011', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10867/']} | jdg_74770 |
stackexchange | llm_judgeable_groundtruth_similarity | 1556 |
Below is a question asked on the forum computergraphics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to understand some of the physical principles behind light and material interaction lately. In his talk Physics and Math of Shading , Naty Hoffman explains Fresnel reflectance and defines the characteristic specular color F 0 of a material as the Fresnel reflectance at 0° incident light angle. On slide 65, F 0 of gold is given as 1.022, 0.782, 0.344 (linear). Hoffman adds: its red channel value is greater than 1 (it’s outside sRGB gamut) All of this doesn't make too much sense to me. A value greater than 1 would mean that in the wavelengths contributing to the red channel, more energy is reflected than is received . Does this really happen, and if so, how and why? In addition, here is a reflectance curve from Wikipedia for some materials including gold (Au). The curve is certainly high for red wavelengths around 600nm but does not seem to go over 100%.
Now provide the response and nothing else.
| RGB color is a bit more complicated a subject than readily seems apparent. The reflectance wavelength diagram shows the reason quite well actually. RGB color model has several central problems: What the colors represent: They represent 3 spikes in a continuous spectrum. The R, G and B aren't energetically equivalent let alone evenly spaced. What their range is: The colors do not actually mean anything without information of what space they span. In the assumed sRGB color space the space does not span the entire sensable range. So energetically equal but more vivid colors exist. Human sensory apparatus isn't actually reading 3 color spikes but the sensors nonlinearly overlap. As a result one can not draw the conclusion that a reflectance color channel of greater than 1 automatically means that energy is inserted into the system. That is simply one of the possible interpretations. Another interpretation is that the color is more intense than your color space allows. As a result your color vector component could be over 1. Human eyes may also bleed color from one sensor to another due to overlap of the sensors. Such things happen with the sky which seems light blue, but is actually far darker blue but so intense that we see it as light blue. But in 50% reflections it would look wrong if we wouldn't account for this. In the end, it can also mean energy is inserted into the system. Either the energy comes from elsewhere or is generated by the surface. Rendering is often not a scientific measure of things. No energy principle needs to be broken to achieve this. Summa summarum (tl;dr) Color is often a compound attribute at the same time as it measures energy levels it also measures something other. Namely the location in the color space. Thus you can not differentiate the two signals (energy and color intensity) easily. In this case it is a more intense color because the source says so: Outside of sRGB gamut = more intense color than the color space can make. | {} | {'log_upvote_score': 5, 'links': ['https://computergraphics.stackexchange.com/questions/1556', 'https://computergraphics.stackexchange.com', 'https://computergraphics.stackexchange.com/users/385/']} | jdg_74771 |
stackexchange | llm_judgeable_groundtruth_similarity | 72755476 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since the ViewPropTypes has been removed from 'react-native' and the packages using it didn't update. this error appears after building the app ERROR Invariant Violation: ViewPropTypes has been removed from React Native. Migrate to ViewPropTypes exported from 'deprecated-react-native-prop-types'. ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native. packages I'm using: "@react-native-clipboard/clipboard": "^1.10.0","@react-native-community/checkbox": "^0.5.12","@react-native-firebase/app": "^14.11.0","@react-native-firebase/auth": "^14.9.4","@react-native-firebase/database": "^14.11.0","@react-native-firebase/firestore": "^14.11.0","@react-native-google-signin/google-signin": "^7.2.2","@react-native-masked-view/masked-view": "github:react-native-masked-view/masked-view","@react-native-picker/picker": "^2.4.1","@react-navigation/bottom-tabs": "^6.3.1","@react-navigation/native": "^6.0.10","@react-navigation/stack": "^6.2.1","axios": "^0.27.2","base-64": "^1.0.0","num-words": "^1.2.2","numeral": "^2.0.6","pdf-lib": "^1.17.1","react": "17.0.2","react-native": "^0.69.0","react-native-blob-util": "^0.16.1","react-native-country-picker-modal": "^2.0.0","react-native-date-picker": "^4.2.2","react-native-fbsdk-next": "^8.0.5","react-native-fs": "^2.20.0","react-native-gesture-handler": "^2.5.0","react-native-html-to-pdf": "^0.12.0","react-native-pdf": "^6.5.0","react-native-picker-select": "^8.0.4","react-native-progress": "^5.0.0","react-native-radio-input": "^0.9.4","react-native-ratings": "^8.1.0","react-native-safe-area-context": "^4.2.5","react-native-screens": "^3.13.1","react-native-share": "^7.5.0","react-native-signature-canvas": "^4.3.1","react-native-vector-icons": "^9.1.0","react-native-webview": "^11.21.2","react-scripts": "^5.0.1" Any solution?
Now provide the response and nothing else.
| I can recommend doing the steps outlined in this github discussion. Steps Install patch-package , this will later be used to make the changes more persistent. Install deprecated-react-native-prop-types by running npm install deprecated-react-native-prop-types or yarn add deprecated-react-native-prop-types Now you have to hack the node_modules . Go to node_modules/react-native/index.js starting around line 436 and change this: // Deprecated Prop Typesget ColorPropType(): $FlowFixMe { invariant( false, "ColorPropType has been removed from React Native. Migrate to " + "ColorPropType exported from 'deprecated-react-native-prop-types'.", );},get EdgeInsetsPropType(): $FlowFixMe { invariant( false, "EdgeInsetsPropType has been removed from React Native. Migrate to " + "EdgeInsetsPropType exported from 'deprecated-react-native-prop-types'.", );},get PointPropType(): $FlowFixMe { invariant( false, "PointPropType has been removed from React Native. Migrate to " + "PointPropType exported from 'deprecated-react-native-prop-types'.", );},get ViewPropTypes(): $FlowFixMe { invariant( false, "ViewPropTypes has been removed from React Native. Migrate to " + "ViewPropTypes exported from 'deprecated-react-native-prop-types'.", );}, to this: // Deprecated Prop Types get ColorPropType(): $FlowFixMe { return require("deprecated-react-native-prop-types").ColorPropType }, get EdgeInsetsPropType(): $FlowFixMe { return require("deprecated-react-native-prop-types").EdgeInsetsPropType }, get PointPropType(): $FlowFixMe { return require("deprecated-react-native-prop-types").PointPropType }, get ViewPropTypes(): $FlowFixMe { return require("deprecated-react-native-prop-types").ViewPropTypes }, Run npx patch-package react-native to save the patch. Rebuild the app. Only thing to keep in mind is that this patch will need to be reapplied with every upgrade to react-native, or until the libraries in question are updated to import from deprecated-react-native-prop-types instead. Props to goguda for providing this answer. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/72755476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18165795/']} | jdg_74772 |
stackexchange | llm_judgeable_groundtruth_similarity | 8026040 |
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 was reading this and unfortunately could not understand in depth why the compiler does not allow conversion from Derived** to Base**. Also I have seen this which gives no more info than the parashift.com's link. EDIT: Let us analyze this code line by line: Car car; Car* carPtr = &car; Car** carPtrPtr = &carPtr; //MyComment: Until now there is no problem! Vehicle** vehiclePtrPtr = carPtrPtr; // This is an error in C++ //MyComment: Here compiler gives me an error! And I try to understand why. //MyComment: Let us consider that it was allowed. So what?? Let's go ahead! NuclearSubmarine sub; NuclearSubmarine* subPtr = ⊂ //MyComment: this two line are OK too! *vehiclePtrPtr = subPtr; //MyComment: the important part comes here... *vehiclePtrPtr is a pointer to //MyComment: a vehicle, particularly in our case it points to a Car object. //MyComment: Now when I assign to the pointer to the Car object *vehiclePtrPtr, //MyComment: a pointer to NuclearSubmarine, then it should just point to the //MyComment: NuclearSubmarine object as it is indeed a pointer to a Vehicle, //MyComment: isn't it? Where is my fault? Where I am wrong? // This last line would have caused carPtr to point to sub! carPtr->openGasCap(); // This might call fireNuclearMissle()!
Now provide the response and nothing else.
| It's basically the same reason why a bowl of bananas is not a bowl of fruits. If a bowl of bananas were a bowl of fruits, you could put an apple into the bowl, and it would no longer be a bowl of bananas. As long as you only inspect the bowl, the conversion is harmless. But as soon as you start modifying it, the conversion becomes unsafe. This is the key point to bear in mind. (This is the precise reason why the immutable Scala collections actually allow the conversion, but the mutable collections prohibit it.) Same with your example. If there was a conversion from Derived** to Base** , you could put a pointer to an apple were the type system promised only a pointer to a banana could exist. Boom! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8026040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163394/']} | jdg_74773 |
stackexchange | llm_judgeable_groundtruth_similarity | 35281630 |
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 find the PS1 variable in oh-my-zsh and change it so iTerm doesn't look as clogged up. Running the following command: echo $PS1 gives me this %{%f%b%k%}$(build_prompt) Additionally, I've attempted to edit the .zshrc file and put export PS1="random-text" but it didn't work. I've tried to look around for the PS1 variable, but couldn't locate it. If it also helps, I'm running El Capitan on my laptop right now. I couldn't find any similar questions to what I posted so any help would be greatly appreciated.
Now provide the response and nothing else.
| Changing your Theme: To edit your prompt in oh-my-zsh you need to edit a PROMPT variable in your theme instead of PS1 . In your .zshrc file you will find a line that looks something like this: ZSH_THEME="themename" oh-my-zsh stores these themes in the ~/.oh-my-zsh/themes folder. If you ls ~/.oh-my-zsh/themes you will see a list of themes that you can change. The above theme would be named themename.zsh-theme in this directory. Customizing your Theme: If you want a simple way to customize your oh-my-zsh theme you can copy a file already in this theme folder and edit that. To change your prompt simply edit the PROMPT variable. For example: PROMPT=">>" This would make two > 's your prompt. I like editing the already existing simple theme. the simple.zsh-theme file looks like this: PROMPT='%{$fg[green]%}%~%{$fg_bold[blue]%}$(git_prompt_info)%{$reset_color%} 'ZSH_THEME_GIT_PROMPT_PREFIX="("ZSH_THEME_GIT_PROMPT_SUFFIX=")"ZSH_THEME_GIT_PROMPT_DIRTY=" ✗"ZSH_THEME_GIT_PROMPT_CLEAN=" ✔" Applying the Changes: Now just change the theme in your in your .zshrc file: ZSH_THEME="simple" And reload oh-my-zsh with: . ~/.zshrc | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35281630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3788419/']} | jdg_74774 |
stackexchange | llm_judgeable_groundtruth_similarity | 1427043 |
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 build a simulation engine which can simulate a soccer (association football) match. It would be cool great if you could help me. What is important to me is to decide which actions happen. The event listeners for each action can be implemented later easily. The function should only simulate the game results and comments to happening actions. There is no 2D/3D graphics needed. We're talking about games like Hattrick . I would propose that you have an array of minutes with actions at first. $minutes = array(1, 3, 4, 7, 11, 13, ..., 90, 92); For each of these minutes, you could then simulate an attack. The attacking team is determined by dice before: $attacking = mt_rand(1, 2); So the part which is most important to me is the attack function. Please edit my approach or use it as a sample. Can you help me to improve this? The function should be complex so that the results are as realistic as possible. But you need to find something between high predictability and too random results. I only want to improve this function. My approach: <?phpfunction Chance_Percent($chance, $universe = 100) { $chance = abs(intval($chance)); $universe = abs(intval($universe)); if (mt_rand(1, $universe) <= $chance) { return true; } return false;}function simulate_attack($teamname_att, $teamname_def, $strength_att, $strength_def) { global $minute, $goals, $_POST, $matchReport, $fouls, $yellowCards, $redCards, $offsides, $schuesse, $taktiken; // input values: attacker's name, defender's name, attacker's strength array, defender's strength array // players' strength values vary from 0.1 to 9.9 // ADJUSTMENT START switch ($taktiken[$teamname_att][0]) { case 1: $strength_att['defenders'] *= 1.1; $strength_att['forwards'] *= 0.9; break; case 3: $strength_att['defenders'] *= 0.9; $strength_att['forwards'] *= 1.1; break; } switch ($taktiken[$teamname_def][0]) { case 1: $strength_def['defenders'] *= 1.1; $strength_def['forwards'] *= 0.9; break; case 3: $strength_def['defenders'] *= 0.9; $strength_def['forwards'] *= 1.1; break; } // ADJUSTMENT END $matchReport .= '<p>'.$minute.'\': '.comment($teamname_att, 'attack'); $offense_strength = $strength_att['forwards']/$strength_def['defenders']; $defense_strength = $strength_def['defenders']/$strength_att['forwards']; if (Chance_Percent(50*$offense_strength*($taktiken[$teamname_att][2]/2)*($taktiken[$teamname_att][3]/2))) { // attacking team passes 1st third of opponent's field side $matchReport .= ' '.comment($teamname_def, 'attack_advance'); if (Chance_Percent(25*($taktiken[$teamname_def][4]/2))) { // the defending team fouls the attacking team $fouls[$teamname_def]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul'); if (Chance_Percent(43)) { // yellow card for the defending team // chance is correct for my purpose $yellowCards[$teamname_def]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_yellow'); } elseif (Chance_Percent(3)) { // red card for the defending team // chance is correct for my purpose (only 1.43% because it's an alternative way) $redCards[$teamname_def]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_red'); } // indirect free kick // only 58.23% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick'); if (Chance_Percent(25)) { // shot at the goal $schuesse[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_shot'); if (Chance_Percent(25)) { // attacking team scores (6.25% chance) $goals[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_shot_score'); } else { // defending goalkeeper saves // only 18.75% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_shot_save'); } } else { // defending team cleares the ball // only 75% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_clear'); } } elseif (Chance_Percent(17)) { // attacking team is caught offside // only 4.25% because it's an alternative way $offsides[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_offside'); } else { if (Chance_Percent(25*($taktiken[$teamname_def][5]/2))) { // the defending team fouls the attacking team $fouls[$teamname_def]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul'); if (Chance_Percent(43)) { // yellow card for the defending team // chance is correct for my purpose $yellowCards[$teamname_def]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_yellow'); } elseif (Chance_Percent(3)) { // red card for the defending team // chance is correct for my purpose (only 1.43% because it's an alternative way) $redCards[$teamname_def]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_red'); } if (Chance_Percent(19)) { // penalty for the attacking team $schuesse[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_penalty'); if (Chance_Percent(77)) { // attacking team scores (77% chance according to Wikipedia) $goals[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_penalty_score'); } elseif (Chance_Percent(50)) { // shot misses the goal // only 11.5% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_penalty_miss'); } else { // defending goalkeeper saves // only 11.5% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_penalty_save'); } } elseif (Chance_Percent(28)) { // direct free kick // only 22.68% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_dFreeKick'); if (Chance_Percent(33)) { // shot at the goal $schuesse[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_dFreeKick_shot'); if (Chance_Percent(33)) { // attacking team scores (10.89% chance) $goals[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_dFreeKick_shot_score'); } else { // defending goalkeeper saves $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_dFreeKick_shot_save'); } } else { // defending team cleares the ball // only 77% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_dFreeKick_clear'); } } else { // indirect free kick // only 58.23% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick'); if (Chance_Percent(25)) { // shot at the goal $schuesse[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_shot'); if (Chance_Percent(25)) { // attacking team scores (6.25% chance) $goals[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_shot_score'); } else { // defending goalkeeper saves // only 18.75% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_shot_save'); } } else { // defending team cleares the ball // only 75% because it's an alternative way $matchReport .= ' '.comment($teamname_def, 'attack_advance_foul_iFreeKick_clear'); } } } else { // attack passes the 2nd third of the opponent's field side - good chance $matchReport .= ' '.comment($teamname_def, 'attack_advance_advance'); if (Chance_Percent(62*($taktiken[$teamname_att][6]/2)*($taktiken[$teamname_att][7]/2)/($taktiken[$teamname_att][8]/2)*($taktiken[$teamname_att][9]/2)/($taktiken[$teamname_def][10]/2))) { // shot at the goal $schuesse[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_advance_shot'); if (Chance_Percent(30*$strength_def['goalkeeper']/7/($taktiken[$teamname_att][11]/2))) { // the attacking team scores // only 8.78% because it's an alternative way // if goalkeeper has strenth 7 then chance is 8.78% otherwise lower/higher $goals[$teamname_att]++; $matchReport .= ' '.comment($teamname_def, 'attack_advance_advance_shot_score'); } else { if (Chance_Percent(50)) { // the defending defenders block the shot $matchReport .= ' '.comment($teamname_def, 'attack_advance_advance_shot_block'); } else { // the defending goalkeeper saves $matchReport .= ' '.comment($teamname_def, 'attack_advance_advance_shot_save'); } } } } } } // attacking team doesn't pass 1st third of opponent's field side elseif (Chance_Percent(15*$defense_strength*($taktiken[$teamname_att][12]/2)*($taktiken[$teamname_att][13]/2))) { // quick counter attack - playing on the break // only 7.5% because it's an alternative way // if defense has strength 7 then chance is 7.5% otherwise lower/higher $strength_att['defenders'] = $strength_att['defenders']*0.8; // weaken the current attacking team's defense $matchReport .= ' '.comment($teamname_def, 'attack_quickCounterAttack'); $matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line return simulate_attack($teamname_def, $teamname_att, $strength_def, $strength_att); // new attack - this one is finished } else { // ball goes into touch - out of the field $matchReport .= ' '.comment($teamname_def, 'attack_throwIn'); if (Chance_Percent(33)) { // if a new chance is created if (Chance_Percent(50)) { // throw-in for the attacking team $matchReport .= ' '.comment($teamname_def, 'attack_throwIn_att'); $matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line return simulate_attack($teamname_att, $teamname_def, $strength_att, $strength_def); // new attack - this one is finished } else { // throw-in for the defending team $matchReport .= ' '.comment($teamname_def, 'attack_throwIn_def'); $matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line return simulate_attack($teamname_def, $teamname_att, $strength_def, $strength_att); // new attack - this one is finished } } } $matchReport .= ' ['.$goals[$_POST['team1']].':'.$goals[$_POST['team2']].']</p>'; // close comment line return TRUE; // finish the attack}?> Tactical settings which should have an influence on the randomness: adjustment (1=defensive, 2=neutral, 3=offensive): the higher the value is the weaker is the defense and the stronger is the offense speed of play (1=slow, 2=medium, 3=fast): the higher the value is the better are the opportunities but the higher is the risk of getting a quick counter attack distance of passes (1=short, 2=medium, 3=long): the higher the value is the less but better opportunities you get and the more often you are offside creation of changes (1=safe, 2=medium, 3=risky): the higher the value is the better are your opportunities but the higher is the risk of getting a quick counter attack pressure in defense (1=low, 2=medium, 3=high): the higher the value is the more quick counter attacks you will have aggressivity (1=low, 2=medium, 3=high): the higher the value is the more attacks you will stop by fouls Integration of the tactical settings: All the tactical settings have a value which can be "1", "2" or "3". "2" is always neutral/medium. So I divide the values by 2. I get a ratio which is 0.5 or 1 or 1.5. I thought that I could then easily multiply the chances by this in order to integrate tactical influence. But one problem has evolved: If I multiply a chance by 2 or more tactical values, it can be higher than 100% (60 x 1.5 x 1.5 for example). So I can't integrate the tactics this way. What else can I do? Thank you very much! Update (2014): A few years later, I have now released the full code base of the game as open-source on GitHub . You'll find the specific implementation of this simulation in this file , if anyone is interested.
Now provide the response and nothing else.
| Build a 'weight'-based-simulation (Yeah, I just now invented that term). Each variable (regardless of its type) has a 'weight'. For example, players have weights. A good player has extra weight. A player with an injury has less weight or even no wait at all (or maybe negative weight?). You add all the weight together (of both teams, because it is a soccer match). That weight resembles a winning chance percentage. For example; The weight of Team A = 56 , the weight of Team B = 120 The weight already shows that one team is much better (regardless of how the weight was established .. maybe they have very round balls, who cares) than the other. Based on the weight, you could calculate a winning chance;The winning chance of Team A = 32% , The winning chance of Team B = 68% . Now you could write an algorithm that simulates a match, influenced by the winning percentage. I wrote an algorithm like this once to draw advertisements. In my case, the number of clicks an advertisement had was the weight. The bigger the weight, the more chance the advertisement was picked by my algorithm. I wrote the algorithm by taking a large number (like, 1000) and then assigned a range of that number to each advertisement, based on the weight percentage. In this case, Team A gets a range of 32% of 1000 , which is 0 - 320, Team B gets a range of 68% which is 321 - 1000 . Then my algorithm would draw a number (randomly) between 0 and 1000. The advertisement (or your teams) with the largest range (and thus largest winning chance) has the most chance of being picked by the algorithm, although it could turn out differently. This kind of algorithm is great (although not perfect) for a balanced outcome (if users could create their own teams, buy better players, etc). You could also make any events within the game drawn by this algorithm, simply by adding a weight to the event as well.. You could add weight to an event (for example the injury of a team mate), per team, based on other weight factors within that team (how many matches played in a row, how good is (or how much weighs) their medic staff, etc). If you do the weight thing right, you could get a very balanced (and easily expandable) simulation algorithm that can both be predictable (just like some matches in real life) or totally surprising (again, just like a real life match). UPDATE: Tactical Influences You added tactical influences, plus the question 'how would you do it?', so I will elaborate. What you are currently doing (as I understand it) is you take a percentage (the chance something occurs) and multiply that with a ratio, so that it will occur more/less. However, because you can have multiple ratio's, you end up with a chance more then 100%. First of all, for every tactical advantage of a team, there is (probably) a counter advantage on the other team. For example, if Team A has a weight in making goals, Team B has a counter weight in stopping goals. This sum is the universe (100%). Now the weight of both tactical advantages makes up a piece of that universe, or total weight (as I explained above). Say that Team A is 80% certain of scoring a goal, in a certain minute, and Team B is 20% certain of stopping it (based on the weight system). But, because Team B just acquired a very good keeper, there is a tactical influence on Team B's side. This influence should shift the chance of an event, but not the universe itself! In other words, you shouldn't end up with a total chance of more then 100% (although in some cases, this isn't necessarily a bad thing) So, you should add weight to Team B , based on the tactical influence and then re-calculate the chances based on the new weights. Assigning Weight Now, like you commented, assigning weight isn't easy. Certainly not if you have to 'weigh' players on their qualities. Weighing is about more then just saying that a player is 'bad' or 'good', you have to actually grade them (like in high school!). The bigger the highest grade, the more accurate the weighting system is. Now, assigning weights to tactical influences is a bit more easier. Say that you have the following influences; Stopping goals Scoring goals Defence Attack Now, create a pool of total weight (say, 1000, I like that number). These are 'tactical points' you could assign. These four influences make up a match, so you could assign 250 points to each influence. This number (250) is the universe of each influence. The assignment of these points, per team, depends on the team's weight factors (like, do they have a good keeper?) A keeper, for instance, weighs against the opponents keeper (and maybe also the people that are in between the keeper and the opponent, but let's keep it simple). Say the keeper of Team A weighs 80% of the total, and the keeper of Team B 20% . This rates how good they are, which is directly related to the tactical points they get. So Team A gets 80% of 250 stopping-goals-points and Team B gets 20% of those points. The rest of the points can be assigned equally. In my example, I took only two keepers as the universe of wether a goal gets stopped or not. In reality, there could be a lot more weight factors (for you to figure out). Once they are all divided, you can use the tactical points to make out the match. For each minute you could re-calculate the chance of winning. Each minute, you could also re-calculate the tactical influences (say another player enters the field, or a player is injured). Yes, you will get a LOT of variables. But the more you get, the better a match plays. The more variables (or weights / counter weights) the more it feels like real life. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1427043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89818/']} | jdg_74775 |
stackexchange | llm_judgeable_groundtruth_similarity | 101906 |
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 $f: {\bf Q} \rightarrow {\bf Q}$ be a "${\bf Q}$-differentiable" function whose "${\bf Q}$-derivative" is constantly zero; that is, for all $x \in {\bf Q}$ and all $\epsilon > 0$ in ${\bf Q}$, there exists $\delta > 0$ in ${\bf Q}$ such that for all $y \in {\bf Q}$ with $0 < |x-y| < \delta$, $|(f(y)-f(x))/(y-x)| < \epsilon$. An example of such a function is the 2-valued function on ${\bf Q}$ that takes the value 0 or 1 according to whether $x<\pi$ or $x>\pi$. Must $f$ be locally constant, in the sense that for all $x \in {\bf Q}$, there exists $\delta > 0$ in ${\bf Q}$ such that for all $y \in {\bf Q}$ with $|x-y| < \delta$, $f(y)=f(x)$? I have a feeling that this is not a hard problem (and I am even afraid some of you will think that it is a homework problem!), but it actually arose from my research (see http://jamespropp.org/reverse.pdf ), and after an hour of thought I still don't see the answer. In an ideal world I'd mull it over longer before posting, but since the journal to which I have submitted the paper has given me a deadline for making revisions, and the deadline is approaching, I am swallowing my pride and seeking help.
Now provide the response and nothing else.
| No, $f$ does not have to be locally constant. Let $a_n$ be a sequence of irrationals that decreases to zero, define $f(x) = 0$ for $x \leq 0$, and let $f(x)$ be a (single) rational number in $(e^{-1/{a_{n+1}}}, e^{-1/{a_n}})$ for $a_n < x < a_{n-1}$. Voila! | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/101906', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3621/']} | jdg_74776 |
stackexchange | llm_judgeable_groundtruth_similarity | 12662954 |
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 get an ambiguous column name error with this query (InvoiceID). I can't figure out why. They all seem to be joined correctly so why doesn't SSMS know to display VendorID? Query: SELECT VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmountFROM Vendors JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)WHERE Invoices.InvoiceID IN (SELECT InvoiceSequence FROM InvoiceLineItems WHERE InvoiceSequence > 1)ORDER BY VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount
Now provide the response and nothing else.
| We face this error when we are selecting data from more than one tables by joining tables and at least one of the selected columns (it will also happen when use * to select all columns) exist with same name in more than one tables (our selected/joined tables). In that case we must have to specify from which table we are selecting out column. Following is a an example solution implementation of concept explained above I think you have ambiguity only in InvoiceID that exists both in InvoiceLineItems and Invoices Other fields seem distinct. So try This I just replace InvoiceID with Invoices.InvoiceID SELECT VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount FROM Vendors JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID) JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID) WHERE Invoices.InvoiceID IN (SELECT InvoiceSequence FROM InvoiceLineItems WHERE InvoiceSequence > 1) ORDER BY VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount You can use tablename.columnnae for all columns (in selection,where,group by and order by) without using any alias. However you can use an alias as guided by other answers | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12662954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1518823/']} | jdg_74777 |
stackexchange | llm_judgeable_groundtruth_similarity | 2146231 |
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'm trying to solve this limit: $$\lim_{x \to 1}{\frac{1-x^2}{\sin (\pi x)}}$$ The answer ought to be $\frac{2}{\pi}$, but I end up with $0$: $\lim\limits_{x \to 1}{\frac{1-x^2}{\sin (\pi x)}} = $$\lim\limits_{y \to 0}{\frac{1-(y+1)^2}{\sin (\pi (y+1))}} = $$\lim\limits_{y \to 0}{\frac{\pi(y+1)}{\sin (\pi (y+1))} \frac{1-(y+1)^2}{\pi(y+1)}} = $$\lim\limits_{y \to 0}{\frac{1-(y+1)^2}{\pi(y+1)}} = 0$ Where and why is my solution incorrect? Note: I'm aware of this post , however I believe mine is different because I'm asking where and why my solution went wrong, not why my answer was wrong.
Now provide the response and nothing else.
| Replacing $f$ by $-f$ if required, we may assume without changing the conclusion that $f''(\xi) > 0$. The following is an instance of such $y = f(x)$ near the point $(\xi, f(\xi))$: $\hspace{9em}$ This graph suggests how one can find such points $x_1$ and $x_2$. You can simply translate the tangent line little up and choose any two intersecting points. (The assumption on $f''(\xi)$ will guarantee the existence of such points.) Let us formalize this idea. Since $f$ is $C^2$, there is $\delta > 0$ and $c > 0$ such that $$ |x - \xi| \leq \delta \quad \Rightarrow \quad f''(x) \geq c.$$ Then Taylor's theorem tells that for $x \in [\xi-\delta,\xi+\delta]$ we have $$ f(x) \geq f(\xi) + f'(\xi)(x - \xi) + \frac{c}{2}(x - \xi)^2. \tag{*} $$ Now define $g(x)$ by $$ g(x) = f(x) - f(\xi) - f'(\xi)(x - \xi). $$ By $\text{(*)}$, we know that $$ g(\xi \pm \delta) \geq \frac{c\delta^2}{2} \quad \text{and} \quad g(\xi) = 0. $$ So by the intermediate value theorem, there exist $x_1 \in [\xi-\delta, \xi)$ and $x_2 \in (\xi, \xi+\delta]$ such that $g(x_1) = c\delta^2/2 = g(x_2)$. Therefore we have $$ \frac{f(x_1) - f(x_2)}{x_1 - x_2} - f'(\xi) = \frac{ g(x_1) - g(x_2)}{x_1 - x_2} = 0 $$ and the claim follows. Without the assumption $f''(\xi) \neq 0$ the conclusion may be false as you can see from the example $f(x) = x^3$ with $\xi = 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2146231', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/326673/']} | jdg_74778 |
stackexchange | llm_judgeable_groundtruth_similarity | 37338526 |
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 having trouble storing an array in session. I am making a shopping cart and it doesn't seem to work. public function __construct(){ $product = array(1,2,3,4); Session::push('cart', $product);} and then retrieve it in the view like this. {{Session::get('cart')}} However I keep getting an error like this. htmlentities() expects parameter 1 to be string, array given Any clues and advice on how to create a shopping cart that stores an array of items.
Now provide the response and nothing else.
| If you need to use the array from session as a string, you need to use Collection like this: $product = collect([1,2,3,4]);Session::push('cart', $product); This will make it work when you will be using {{Session::get('cart');}} in your htmls. Be aware of Session::push because it will append always the new products in sessions. You should be using Session::put to be sure the products will be always updating. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37338526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5536016/']} | jdg_74779 |
stackexchange | llm_judgeable_groundtruth_similarity | 52000933 |
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 learning C#.NET Core and trying to create DTO mapping without using AutoMapper as I'm working on a small project alone and want to understand fundamental before using extra packages, surpringly I could not easily find answer at stackoverflow.com or I may use wrong keyword searching. BTW, below is my code which I successfully map to EmployeeForShortDto under GetEmployee method. Unfortunately, I don't how to map it under GetAllEmployee just because the return data is a collection, not a single record. Please advice. EmployeeController.cs using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using NetCoreWebApplication1.Dto;using NetCoreWebApplication1.Repository;using NetCoreWebApplication1.Other;namespace NetCoreWebApplication1.Controller{ [Route("api/[controller]")] [ApiController] public class EmployeeController : ControllerBase { private readonly IMasterRepository _repo; public EmployeeController(IMasterRepository repo) { _repo = repo; } [HttpGet("{id}")] public async Task<IActionResult> GetEmployee(int id) { var data = await _repo.GetEmployee(id); if (data == null) return NotFound(); var dataDto = new EmployeeForShortDto() { Id = data.Id, EmpCode = data.EmpCode, Fname = data.Fname, Lname = data.Lname, Age = NetCoreWebApplication1.Other.Extension.CalcAge(data.DateBirth) }; return Ok(dataDto); } [HttpGet] public async Task<IActionResult> GetAllEmployee() { var data = await _repo.GetAllEmployee(); return Ok(data); } }} MasterRepository.cs using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.EntityFrameworkCore;using NetCoreWebApplication1.Models;namespace NetCoreWebApplication1.Repository{ public class MasterRepository : IMasterRepository { private readonly PrDbContext _context; public MasterRepository(PrDbContext context) { _context = context; } // Employee public async Task<List<Employee>> GetAllEmployee() { var data = await _context.Employee.ToListAsync(); return data; } public async Task<Employee> GetEmployee(int id) { var data = await _context.Employee.FirstOrDefaultAsync(x => x.Id == id); return data; } // Generic methods public void Add<T>(T entity) where T : class { _context.Add(entity); } public void Delete<T>(T entity) where T : class { _context.Remove(entity); } public async Task<bool> SaveAll() { return await _context.SaveChangesAsync() > 0; } }}
Now provide the response and nothing else.
| You can use an extension method to map from your entity type to your DTO type. public static EmployeeForShortDto ToDto(this Employee employee){ if (employee != null) { return new EmployeeForShortDto { Id = employee.Id, EmpCode = employee.EmpCode, Fname = employee.Fname, Lname = employee.Lname, Age = NetCoreWebApplication1.Other.Extension.CalcAge(employee.DateBirth) }; } return null;} And then use where needed. [HttpGet("{id}")]public async Task<IActionResult> GetEmployee(int id){ var data = await _repo.GetEmployee(id); if (data == null) { return NotFound(); } return Ok(data.ToDto());}[HttpGet]public async Task<IActionResult> GetAllEmployee(){ var data = await _repo.GetAllEmployee(); return Ok(data.Select(x => x.ToDto()));} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52000933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10268539/']} | jdg_74780 |
stackexchange | llm_judgeable_groundtruth_similarity | 35744647 |
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 preparing an application which should work with and without GUI, so I use in my CMakeLists.txt the command option (NEED_GUI "Include Qt support" OFF) and if (NEED_GUI) message("****GUI should be OFF****") add_subdirectory(QtGUI) # The Qt-based graphics routinesendif (NEED_GUI) Despite that I set the option OFF, I receive the message and the library is built. Where to look for an error?
Now provide the response and nothing else.
| Turning my comment into an answer Your code looks good. So I'm assuming the problem here is that option() does transfer the value given into your CMakeCache.txt with the initial configuration step. After that you can only change it by modifying the cached entry for NEED_GUI . Changing the option in your CMakeLists.txt after you have generated your build environment will not update the cache anymore. References What's the CMake syntax to set and use variables? Advantages of using CMake option command rather than set? How to tell whether CMake used initial value for an option? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35744647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3998319/']} | jdg_74781 |
stackexchange | llm_judgeable_groundtruth_similarity | 2774093 |
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 centipede wants to put on its 100 legs 100 socks and 100 shoes. In how many different sequences can it put on all shoes and socks if it has to put on each sock on a leg before the shoe, but it can put on a sock on another leg before putting on a shoe on the former leg? I tried it by recursion, but it seems complicated.
Now provide the response and nothing else.
| There are $200\choose 2$ possible times when thins are done to the first leg. After that, there are $198\choose 2$ for the second leg, and so on.In total, we cont$$ {200\choose 2}{198\choose 2}{196\choose 2}\cdot {2\choose 2}=\frac{200!}{2^{100}}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2774093', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/506847/']} | jdg_74782 |
stackexchange | llm_judgeable_groundtruth_similarity | 7533379 |
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 controllers return a list of items to my views. I need to handle the case when there are no items to show the message, "There are no items." I can either: Check list.Count from my controller and return a view containing just that message, or Check list.Count from the view itself, and show the message or the items accordingly. I read that views should not have any logic, so the pure MVC way would be #1 above. Am I wrong, or is that accepted in MVC? Many thanks.
Now provide the response and nothing else.
| That's a view's responsibility. Check the count on the model and act accordingly: @model IEnumerable<MyViewModel>@if (Model.Count() > 0){ ...} else{ <div>Nothing to display here</div>} And if you was using some Grid helper like for example MVCContrib Grid you don't even need an if in the view: @model IEnumerable<MyViewModel>@Html.Grid(Model) .Empty("Nothing to display here") .Columns(column => { ... })) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7533379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_74783 |
stackexchange | llm_judgeable_groundtruth_similarity | 3904759 |
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 abstract C++ class with no constructor. It's supposed to be a base class so other classes can inherit from it. What I am trying to do is to declare a constant variable in the base class and initialize it in each derived class' constructor but nowhere else in each one of those classes. Is it legal in C++? If so, how can I do that?
Now provide the response and nothing else.
| Is it legal in C++? No. The constant must be initialized in the base class constructor. The solution is to provide an appropriate constructor in your base class – otherwise it cannot be used. Furthermore, there’s no reason not to provide that constructor. class Base { int const constant;public: virtual ~Base() = 0; // Makes this an abstract base class.protected: Base(int c) : constant(c) { }};// Must be implemented!Base::~Base() { }class Derived : public Base {public: Derived() : Base(42) { }}; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3904759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246392/']} | jdg_74784 |
stackexchange | llm_judgeable_groundtruth_similarity | 546750 |
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:
I'm working through Shankar's Principles of Quantum Mechanics, and I think I have hit a confusion over identical particles.The book refers to 'measuring the position' of two bosons to be $x_1$ and $x_2$ , thereby concluding that the state of the system is $$|{\Psi}\rangle = \frac{1}{\sqrt{2}}\left(|x_1 x_2\rangle + |x_2 x_1\rangle\right).$$ But how can we measure the position of both particles? What operator are we using? I see that $$X_1\otimes X_2|{\Psi}\rangle = x_1x_2|{\Psi}\rangle,$$ but this just seems to be a measurement of the product of the two positions. I have an even bigger confusion if we measure the position of a particles using the operator $X_1 \otimes I$ . For then, must the state not collapse into one of the $|x_1x_2\rangle$ or $|x_2x_1\rangle$ eigenstates, violating the symmetry of the two bosons? Shouldn't the operator $X_1 \otimes I$ give rise to some sensible observable, as it is Hermitian?
Now provide the response and nothing else.
| Preview of the answer To "measure the positions" of two bosons, we can fill space with a bunch of particle-counting observables localized in pointlike regions, and we can measure all of these observables simultaneously. (They commute with each other.) Even if we start with a generic two-particle state, the result will be a state of the form shown in the question — that is, an eigenstate of all of the localized particle-counting operators. Intuition When we deal with bosons (or fermions), we're really using one of the key ideas from quantum field theory (QFT): observables are tied to regions of space, not to particles. This is true in both relativistic and non-relativistic QFT, and it is the key to answering the question. QFT has observables representing detectors that count the number of particles of a given species in a given region of space. This makes sense no matter how many particles are in the state, and it is compatible with the fact that the particles of a given bosonic species are indistinguishable. We're implicitly using such observables in single-particle quantum mechanics, too, when we use the familiar "position observable". When we measure a sequence of observables separated from each other in time, we account for each measurement's outcome by projecting the state onto one of that observable's eigenspaces. The observable's eigenspaces represent the possible outcomes of the measurement. The associated eigenvalues are just convenient labels used to define things like expectation values and standard deviations. So, as far as the general principles of quantum theory are concerned, an observable might as well just be a collection of mutually orthogonal subspaces of the Hilbert space — or the operators that project onto those subspaces. Applying that perspective to the position observable in single-particle quantum mechanics shows that the position observable is really just a collection of detectors, one per point in space, with eigenvalues (labels) conveniently chosen to be equal to the coordinate of the point where the detector sits. These detector-observables generalize nicely to states with $N$ indistinguishable particles. The position observable does not. When we talk about measuring the positions of identical particles, we're really talking about placing detectors in specific regions of space to count the number of particles in those regions. The position information comes from knowing where we placed the detectors, just like it does in the real world. The math This is a customized review of the formalism of non-relativistic QFT. Work in one-dimensional space for simplicity. A system of any number of "identical" bosons is described by a single field operator $\varphi(x)$ associated with each spatial point $x$ , together with its adjoint $\varphi^\dagger(x)$ . These operators satisfy \begin{gather} \big[\varphi(x),\,\varphi^\dagger(y)\big] = \delta(x-y)\\ \big[\varphi(x),\,\varphi(y)\big] = 0.\tag{1}\end{gather} The symmetry that makes them bosons is implicit in these commutation relations. All observables are constructed from the field operators $\varphi(x)$ and $\varphi^\dagger(x)$ . Let $|0\rangle$ denote the vacuum state, with no particles. This state satisfies $\varphi(x)|0\rangle=0$ . Each application of $\varphi^\dagger(x)$ adds a particle at $x$ . The two-particle state shown in the question is $$ |\Psi\rangle = \varphi^\dagger(x_1)\varphi^\dagger(x_2)|0\rangle.\tag{2}$$ The commutation relations imply that this is the same as $$ |\Psi\rangle = \varphi^\dagger(x_2)\varphi^\dagger(x_1)|0\rangle,\tag{3}$$ so the symmetry is automatically enforced: in this way of formulating the model, we can't even write down a non-symmetric state. Now let $R$ denote some finite region of space, and consider the observable $$ D(R) = \int_R dx\ \varphi^\dagger(x)\varphi(x)\tag{4}$$ where the integral is over the region $R$ . This observable represents a detector that it counts the number of particles in the region $R$ . For example, when applied to the state (2), it gives $$ D(R)|\Psi\rangle = n|\Psi\rangle\tag{5}$$ where $n\in\{0,1,2\}$ is the number of particles in the region $R$ . To derive (5), use the commutation relations (1) together with $\varphi(x)|0\rangle=0$ . If the state has just one particle, then we can use a "position observable" as explain earlier, like this: $$ X = \int dx\ x\, \varphi^\dagger(x)\varphi(x).\tag{6}$$ This is essentially a bunch of detection operators (4), each associated with an infinitesimal region $R$ (a single point), and weighted by the coordinate $x$ of that region. When acting on the single-particle state $$ |x\rangle = \varphi^\dagger(x)|0\rangle,\tag{7}$$ this gives $$ X|x\rangle = x|x\rangle.\tag{8}$$ But when acting on a multi-particle state like (2)-(3), the observable (6) is not as useful: it measures the average $x$ -coordinate of all of the particles in the system, which is not what we want. We want the observables (4), which count the number of particles in a given region of space. That's the best we can do, because the particles are indistinguishable. The answer To "measure the positions" of two bosons, we can fill space with a bunch of particle-counters (4) with pointlike regions $R$ and measure all of these observables simultaneously. (We can do this because the commutation relations (1) imply that all of these observables commute with each other.) Even if we start with a generic two-particle state $$ \int dx_1\,dx_2\ f(x_1,x_2)\varphi^\dagger(x_1)\varphi^\dagger(x_2)|0\rangle,\tag{9}$$ the result will be a state of the form (2)-(3) — that is, an eigenstate of all of the detection operators (4). | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/546750', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/262097/']} | jdg_74785 |
stackexchange | llm_judgeable_groundtruth_similarity | 37034083 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After creating the following array of hash tables in PowerShell (version 2): $array = @()$array += @{a = 1; b = 5}$array += @{a = 3; b = 4}$array += @{a = 5; b = 9}$array += @{a = 7; b = 2} All the following calls to Sort-Object return the same {a,b} sequence: {5,9},{7,2},{1,5},{3,4}: $array | Sort-Object$array | Sort-Object -Descending$array | Sort-Object a$array | Sort-Object b$array | Sort-Object "a"$array | Sort-Object -Property a$array.GetEnumerator() | Sort-Object$array.GetEnumerator() | Sort-Object a If $array is called directly, it returns the objects in the order that they were entered, so the sort is changing the order. But perhaps it has no comparer so just treats every object as equal?? The goal is to sort all of the objects. I am fine with workarounds that involve an alternate custom object, an alternate collection and/or an alternate sort routine. Edit: To clarify what I'm trying to achieve, this would be a rough equivalent in C# class MyClass { public int a; public int b;}// somewhere inside a method:var objects = new List<MyClass>();// code here to populate objects with some MyClass instances.var sorted = objects.OrderBy(x => x.a);
Now provide the response and nothing else.
| Sort-Object a is not working because a isn't a property, it's a key in a hashtable. One might be confused because PowerShell hides this for you by accepting $ht.a even though it actually uses $ht["a"] behind the scenes, but if you run $array | Get-Member you can confirm that the property a doesn't exist. A workaround is to sort by using calculated properties that access the keys in the hashtable. I used Select-Object to show the hashtables in a table so it's easier to see the results. Ex: $array = @()$array += @{a = 7; b = 2}$array += @{a = 3; b = 4}$array += @{a = 3; b = 1}$array += @{a = 5; b = 9}$array += @{a = 1; b = 5}#No sort$array | Select-Object @{n="a";e={$_.a}}, @{n="b";e={$_.b}}a b- -7 23 43 15 91 5#Sort by a asc, then b asc$array | Sort-Object { $_.a }, { $_.b } | Select-Object @{n="a";e={$_.a}}, @{n="b";e={$_.b}}a b- -1 53 13 45 97 2 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37034083', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2661556/']} | jdg_74786 |
stackexchange | llm_judgeable_groundtruth_similarity | 38111339 |
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 implemented Firebase and testing the Firebase notifications.When the app is in the foreground I don't have problems, I implemented a service that extends FirebaseMessagingService and handle the message and data in onMessageReceived I have problems when the app is in background, I would like to send a notification that opens a specific activity and does what I schedule to do, not just opening the App. I did as described on the Firebase guide, but I'm not able to start the specific activity. Here the manifest: <activity android:name=".BasicNotificationActivity"> <intent-filter> <action android:name="OPEN_ACTIVITY_1" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> And here the Firebase Console. What do I have to write in those fields to open my "BasicNotificationActivity"?
Now provide the response and nothing else.
| This is a duplicate of this question: Firebase FCM notifications click_action payload But the answer that was accepted by the author of this question just states that it is not possible with Firebase Console, but it is - with an easy workaround. This answer by diidu to the same question explains the workaround I would use. UPDATE: To elaborate on his answer: Add a helper class (or implement startActivity() method somehow): public class ClickActionHelper { public static void startActivity(String className, Bundle extras, Context context){ Class cls; try { cls = Class.forName(className); }catch(ClassNotFoundException e){ //means you made a wrong input in firebase console } Intent i = new Intent(context, cls); i.putExtras(extras); context.startActivity(i); }} In the launcher-activity of your app, call a mehtod to check any new intents in onCreate() and onNewIntent() ( onNewIntent() is only called instead of onCreate() if Activity is launched with single-top flag): @Overrideprotected void onCreate(Bundle bundle) { [...] checkIntent(getIntent()); }@Overrideprotected void onNewIntent(Intent intent) { super.onNewIntent(intent); [...] checkIntent(intent);}public void checkIntent(Intent intent) { if (intent.hasExtra("click_action")) { ClickActionHelper.startActivity(intent.getStringExtra("click_action"), intent.getExtras(), this); }} And in onMessageReceived() : public void onMessageReceived(RemoteMessage remoteMessage) { Map<String, String> data = remoteMessage.getData(); if (data.containsKey("click_action")) { ClickActionHelper.startActivity(data.get("click_action"), null, this); } } To send a notification with firebase console, put a key-value-pair as custom data like this: Key: click_actionValue: <fully qualified classname of your activity> Now when a notification is received and clicked on, it will open your activity. If your app is in foreground, it will also immediately change to the activity - it would probably be good to ask the user if he wants to go to this activity or not (by showing a dialog in onMessageReceived() ). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38111339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6361137/']} | jdg_74787 |
stackexchange | llm_judgeable_groundtruth_similarity | 19603 |
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Genesis 35:22 states that Reuben lay with Bilhah: It came about while Israel was dwelling in that land, that Reuben went and lay with Bilhah his father’s concubine, and Israel heard of it. (NASB) Is it too far fetched to interpret 1 Chronicles 7:13 to say that Naphtali also lay with her? The sons of Naphtali were Jahziel, Guni, Jezer, and Shallum, the sons of Bilhah. Emphasis mine
Now provide the response and nothing else.
| It cannot be deduced that Naphtali had sex with Bilhah by the Biblical texts. 1 Chronicles 7:13 is not saying that Naphtali had his children with Bilhah. Bilhah is mentioned in 1 Chronicles 7:13 because Naphtali was her second son by Jacob, according to Genesis 30:1-8. Naphtali's sons can be rightly called her sons as well. In fact, some translations render the word sons as descendants instead. When Rachel saw that she bore Jacob no children, she envied her sister. She said to Jacob, “Give me children, or I shall die!” Jacob's anger was kindled against Rachel, and he said, “Am I in the place of God, who has withheld from you the fruit of the womb?” Then she said, “Here is my servant Bilhah; go in to her, so that she may give birth on my behalf, that even I may have children through her.” So she gave him her servant Bilhah as a wife, and Jacob went in to her. And Bilhah conceived and bore Jacob a son. Then Rachel said, “God has judged me, and has also heard my voice and given me a son.” Therefore she called his name Dan. Rachel's servant Bilhah conceived again and bore Jacob a second son. Then Rachel said, “With mighty wrestlings I have wrestled with my sister and have prevailed.” So she called his name Naphtali. (Genesis 30:1-8 ESV) | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/19603', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/10164/']} | jdg_74788 |
stackexchange | llm_judgeable_groundtruth_similarity | 56550164 |
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 Vue component that is tracking when it is "dirty" (e.g. unsaved). I would like to warn the user before they browse away from the current form if they have unsaved data. In a typical web application you could use onbeforeunload . I've attempted to use it in mounted like this: mounted: function(){ window.onbeforeunload = function() { return self.form_dirty ? "If you leave this page you will lose your unsaved changes." : null; }} However this doesn't work when using Vue Router. It will let you navigate down as many router links as you would like. As soon as you try to close the window or navigate to a real link, it will warn you. Is there a way to replicate onbeforeunload in a Vue application for normal links as well as router links?
Now provide the response and nothing else.
| Use the beforeRouteLeave in-component guard along with the beforeunload event. The leave guard is usually used to prevent the user from accidentallyleaving the route with unsaved edits. The navigation can be canceledby calling next(false). In your component definition do the following: beforeRouteLeave (to, from, next) { // If the form is dirty and the user did not confirm leave, // prevent losing unsaved changes by canceling navigation if (this.confirmStayInDirtyForm()){ next(false) } else { // Navigate to next view next() }},created() { window.addEventListener('beforeunload', this.beforeWindowUnload)},beforeDestroy() { window.removeEventListener('beforeunload', this.beforeWindowUnload)},methods: { confirmLeave() { return window.confirm('Do you really want to leave? you have unsaved changes!') }, confirmStayInDirtyForm() { return this.form_dirty && !this.confirmLeave() }, beforeWindowUnload(e) { if (this.confirmStayInDirtyForm()) { // Cancel the event e.preventDefault() // Chrome requires returnValue to be set e.returnValue = '' } },}, | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56550164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597185/']} | jdg_74789 |
stackexchange | llm_judgeable_groundtruth_similarity | 681287 |
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 class Bar with a private field containing the reference type Foo . I would like to expose Foo in a public property, but I do not want the consumers of the property to be able to alter Foo ... It should however be alterable internally by Bar , i.e. I can't make the field readonly . So what I would like is: private _Foo; public Foo { get { return readonly _Foo; } } ...which is of course not valid. I could just return a clone of Foo (assumming that it is IClonable ), but this is not obvious to the consumer. Should I change the name of the property to FooCopy ?? Should it be a GetCopyOfFoo method instead? What would you consider best practice? Thanks!
Now provide the response and nothing else.
| It sounds like you're after the equivalent of "const" from C++. This doesn't exist in C#. There's no way of indicating that consumers can't modify the properties of an object, but something else can (assuming the mutating members are public, of course). You could return a clone of the Foo as suggested, or possibly a view onto the Foo, as ReadOnlyCollection does for collections. Of course if you could make Foo an immutable type, that would make life simpler... Note that there's a big difference between making the field readonly and making the object itself immutable. Currently, the type itself could change things in both ways. It could do: _Foo = new Foo(...); or _Foo.SomeProperty = newValue; If it only needs to be able to do the second, the field could be readonly but you still have the problem of people fetching the property being able to mutate the object. If it only needs to do the first, and actually Foo is either already immutable or could be made immutable, you can just provide a property which only has the "getter" and you'll be fine. It's very important that you understand the difference between changing the value of the field (to make it refer to a different instance) and changing the contents of the object that the field refers to. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/681287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6091/']} | jdg_74790 |
stackexchange | llm_judgeable_groundtruth_similarity | 31115205 |
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 connecting to a websocket server in Java using javax.websocket classes. import javax.websocket.DeploymentException;import javax.websocket.Session;import javax.websocket.WebSocketContainer;import java.io.IOException;import java.net.URI;public class WSClient { private WebSocketContainer webSocketContainer; public void sendMessage(URI endpointURI, String message) throws IOException, DeploymentException { Session session = webSocketContainer.connectToServer(MyClientEndpoint.class, endpointURI); session.getAsyncRemote().sendText(message); }} For the initial HTTP handshake I want to add extra HTTP Headers to the request on the Client side Is this possible? I know that this is possible on server side using ServerEndpointConfig.Configurator.modifyHandshake . Is there a similar solution on client side?
Now provide the response and nothing else.
| ClientEndpointConfig . Configurator . beforeRequest (Map<String,List<String>> headers ) may be usable. The JavaDoc about the argument headers says as follows: the mutable map of handshake request headers the implementation is about to send to start the handshake interaction. So, why don't you override beforeRequest method like below? @Overridepublic void beforeRequest(Map<String,List<String>> headers){ List<String> values = new ArrayList<String>(); values.add("My Value"); headers.put("X-My-Custom-Header", values);} You can pass ClientEndpointConfig to connectToServer (Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31115205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1358536/']} | jdg_74791 |
stackexchange | llm_judgeable_groundtruth_similarity | 5614562 |
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 Java code: public class XYZ { public static void main(){ int toyNumber = 5; XYZ temp = new XYZ(); temp.play(toyNumber); System.out.println("Toy number in main " + toyNumber); } void play(int toyNumber){ System.out.println("Toy number in play " + toyNumber); toyNumber++; System.out.println("Toy number in play after increement " + toyNumber); } } will output this: Toy number in play 5 Toy number in play after increement 6 Toy number in main 5 In C++ I can pass the toyNumber variable as pass by reference to avoid shadowing i.e. creating a copy of the same variable as below: void main(){ int toyNumber = 5; play(toyNumber); cout << "Toy number in main " << toyNumber << endl; }void play(int &toyNumber){ cout << "Toy number in play " << toyNumber << endl; toyNumber++; cout << "Toy number in play after increement " << toyNumber << endl; } and the C++ output will be this: Toy number in play 5 Toy number in play after increement 6 Toy number in main 6 My question is - What's the equivalent code in Java to get the same output as the C++ code, given that Java is pass by value rather than pass by reference ?
Now provide the response and nothing else.
| You have several choices. The one that makes the most sense really depends on what you're trying to do. Choice 1: make toyNumber a public member variable in a class class MyToy { public int toyNumber;} then pass a reference to a MyToy to your method. void play(MyToy toy){ System.out.println("Toy number in play " + toy.toyNumber); toy.toyNumber++; System.out.println("Toy number in play after increement " + toy.toyNumber); } Choice 2: return the value instead of pass by reference int play(int toyNumber){ System.out.println("Toy number in play " + toyNumber); toyNumber++; System.out.println("Toy number in play after increement " + toyNumber); return toyNumber} This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber); . Choice 3: make it a class or static variable If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable. Choice 4: Create a single element array of type int and pass that This is considered a hack, but is sometimes employed to return values from inline class invocations. void play(int [] toyNumber){ System.out.println("Toy number in play " + toyNumber[0]); toyNumber[0]++; System.out.println("Toy number in play after increement " + toyNumber[0]); } | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5614562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/697886/']} | jdg_74792 |
stackexchange | llm_judgeable_groundtruth_similarity | 2371490 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
class absclass { abstract public function fuc();} reports: PHP Fatal error: Class absclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (absclass::fuc) I want to know what it means by implement the remaining methods ,how?
Now provide the response and nothing else.
| I presume that remaining methods actually refers to the abstract methods you're trying to define (in this case, fuc() ), since the non-abstract methods that might exist are okay anyway. It's probably an error message that could use a more precise wording: where it says remaining it could have said abstract . The fix is pretty straightforward (that part of the error message is fine): you need to change this: abstract public function fuc(); ... into a proper implementation: public function fuc(){ // Code comes here} ... or, alternatively and depending your needs, make the whole class abstract: abstract class absclass { abstract public function fuc();} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2371490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198729/']} | jdg_74793 |
stackexchange | llm_judgeable_groundtruth_similarity | 104463 |
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:
For the Bézier surface, which owns the following matrix definition : $$\begin{align*}\mathbf S(u,v)&=\sum_{i=0}^m \sum_{j=0}^n \mathbf P_{i,j} B_{m,i}(u) B_{n,j}(v)\\&=\small \begin{pmatrix}B_{m,0}(u)&\cdots&B_{m,m}(u)\end{pmatrix}_{1\times(m+1)}\begin{pmatrix}\mathbf P_{0,0}&\cdots&\mathbf P_{0,n}\\P_{1,0}&\cdots&\mathbf P_{1,n}\\\vdots&\vdots&\vdots\\\mathbf P_{m,0}&\cdots&\mathbf P_{m,n}\end{pmatrix}\begin{pmatrix}B_{n,0}(v)\\B_{n,1}(v)\\\vdots\\B_{n,n}(v)\end{pmatrix}_{(n+1)\times 1}\end{align*}$$ where, $B_{n,i}(u)$ is Bernstein basis. vec1 = {B[0],...,B[m]};mat = {{P[0,0],...P[0,n]},...,{P[m,0],...P[m,n]}};vec2 = {B[0],...,B[n]};bez = vec1.mat1.vec2 However, the $P_{i,j}$ is the coordinate of a 3D point, which own this style: {x,y,z} . So I cannot use vec1.mat1.vec2 directly. An alternative method is using Hold[] to unevaluate the coordinate {x,y,z} . Namely, Hold[{x,y,z}] . Lastly, with the help of ReleaseHold[] to evaluate the expression. vec1 = {B[0],...,B[m]};mat = Map[Hold,{{P[0,0],...P[0,n]},...,{P[m,0],...P[m,n]}},{2}];vec2 = {B[0],...,B[n]};bez = vec1.mat1.vec2 // ReleaseHold Another way that I came up with is vec1.mat[[All, All, #]].vec2 & /@ {1, 2, 3} Comparison Bernstein[0, 0, u_?NumericQ] := 1Bernstein[n_, i_, u_?NumericQ] := Binomial[n, i] u^i (1 - u)^(n - i)BezierSurface2[pts_, u_?NumericQ, v_?NumericQ] := Module[{m, n, AllBasis}, {m, n} = Dimensions[pts, 2]; AllBasis = Function[{deg, u0}, Bernstein[deg, #, u0] & /@ Range[0, deg]]; With[{row = AllBasis[m - 1, u], col = AllBasis[n - 1, v]}, row.Map[Hold, pts, {2}].col // ReleaseHold] ]BezierSurface1[pts_, u_?NumericQ, v_?NumericQ] := Module[{m, n, AllBasis}, {m, n} = Dimensions[pts, 2]; AllBasis = Function[{deg, u0}, Bernstein[deg, #, u0] & /@ Range[0, deg]]; With[{row = AllBasis[m - 1, u], col = AllBasis[n - 1, v]}, row.pts[[All, All, #]].col & /@ {1, 2, 3}]] cpts = Table[{i, j, RandomReal[{-1, 1}]}, {i, 5}, {j, 5}];ParametricPlot3D[ BezierSurface1[cpts, u, v], {u, 0, 1}, {v, 0, 1}] // AbsoluteTimingParametricPlot3D[ BezierSurface2[cpts, u, v], {u, 0, 1}, {v, 0, 1}] // AbsoluteTimingf = BezierFunction[cpts];ParametricPlot3D[f[u, v], {u, 0, 1}, {v, 0, 1}] // AbsoluteTiming So my question: is there a more efficient method to implement this formula?
Now provide the response and nothing else.
| This might help you get an idea: n = 4;BlockRandom[SeedRandom[42, Method -> "Legacy"]; (* for reproducibility *) cpts = Table[{i, j, RandomReal[{-1, 1}]}, {i, n + 1}, {j, n + 1}]];GraphicsRow[{ParametricPlot3D[BezierFunction[cpts][u, v], {u, 0, 1}, {v, 0, 1}, Evaluated -> True], (* built-in function *) ParametricPlot3D[Evaluate[Fold[#2.#1 &, cpts, (* using dot-products *) {BernsteinBasis[n, Range[0, n], u], BernsteinBasis[n, Range[0, n], v]}]], {u, 0, 1}, {v, 0, 1}]}] You can of course replace BernsteinBasis[] with your own Bernstein[] ; no need for Hold[] trickery! | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/104463', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9627/']} | jdg_74794 |
stackexchange | llm_judgeable_groundtruth_similarity | 45494 |
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 was working with an interface with a MOSFET and I ran into a case where high impedence might be an input to the MOSFET's gate, essentially leaving the gate open. Would the MOSFET exhibit the same electrical & physical behavior as if the gate was connected to GND?
Now provide the response and nothing else.
| Not even close. The complete opposite, in fact. A high-impedance floating N-channel gate can pick up charge from a variety of sources, (via the parasitic gate-to-drain capacitance, via handling - touching the gate with your finger, etc.) and spontaneously turn itself on . Any gate that could have a high-impedance control (a digital I/O from a micro, for instance) really needs a gate-to-source resistor to bleed off these spurious charges and keep the device state defined (=off) when the control is high-Z. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/45494', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10584/']} | jdg_74795 |
stackexchange | llm_judgeable_groundtruth_similarity | 1986402 |
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 I simplify $\prod \limits_{l=1}^{a} \frac{1}{4^a} \cdot 16^l$? I've tried looking at the terms and finding something in there to conlcude what it might be and also took the $n^{th}$ term of $16^l$ into one fraction but that does rather the opposite of simplification.
Now provide the response and nothing else.
| $$\prod_{l=1}^{a}\frac{16^l}{4^a} = \frac{1}{4^{a^2}}\prod_{l=1}^{a}16^l = 4^{-a^2} 16^{\sum_{l=1}^{a}l} = 4^{-a^2} 4^{a(a+1)}=\color{red}{4^a}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1986402', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/339839/']} | jdg_74796 |
stackexchange | llm_judgeable_groundtruth_similarity | 177139 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Windows service running on my local machine. It's configured to run under NT AUTHORITY\NETWORK SERVICE . The program access a network shared drive on a computer in the same subnet. That shared directory has "Everyone" set to "Full Control." I'm getting False on File.Exists() , but the file exists. I'm certain this is a permission issue. Am I forgetting anything? The computer with the shared drive is not on a domain.
Now provide the response and nothing else.
| The fact that the machine with the shared drive is not on a domain is where your main problem is. In order to get this to work you will have to configure the Windows Service to run as a specific user, and then you'll have to create an identical user on the remote system with the same password. It might work then. The problem stems from the fact that in order to log in to a machine not in a domain, you have to log into that machine using an account that exists on that machine. The machine account for something else definitely won't exist on that local machine. By creating an identical user with an identical password, you might be able get the login to work. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/177139', 'https://serverfault.com', 'https://serverfault.com/users/53129/']} | jdg_74797 |
stackexchange | llm_judgeable_groundtruth_similarity | 36394997 |
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 see more so answers , but nothing helped.Here is my older alert and action for that override func viewWillAppear(animated: Bool) { if Reachability.isConnectedToNetwork() == true { print("internet connection ok") } else { print("internet not ok") let alertView: UIAlertView = UIAlertView(title: "Alert ", message: "connect to internet", delegate: self, cancelButtonTitle: "settings", otherButtonTitles: "cancel") alertView.show() return } }func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){ if buttonIndex == 0 { //This will open ios devices wifi settings UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!) } else if buttonIndex == 1 { //TODO for cancel exit(0) }} In that i am getting warning : 'UIAlertView' was deprecated in iOS 9.0. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead I tried : let alert = UIAlertController(title: "Alert", message: "My Alert for test", preferredStyle: UIAlertControllerStyle.Alert)alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in print("you have pressed the Cancel button") }))self.presentViewController(alert, animated: true, completion: nil) But to add two button and add the index path of button press method link my older code,I am not able to do that. Nothing action happening fro my uialert button, Please help me out,How can i remove that warnings and recode my Uialert with my two button action. I am new to swift.Your help will be useful.Thanks!
Now provide the response and nothing else.
| See this Code Destructive and OK buttons in UIAlertController : let alertController = UIAlertController(title: "Destructive", message: "Simple alertView demo with Destructive and Ok.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alertlet DestructiveAction = UIAlertAction(title: "Destructive", style: UIAlertActionStyle.Destructive) { (result : UIAlertAction) -> Void in print("Destructive")}// Replace UIAlertActionStyle.Default by UIAlertActionStyle.defaultlet okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("OK")}alertController.addAction(DestructiveAction)alertController.addAction(okAction)self.presentViewController(alertController, animated: true, completion: nil) Swift 3: let alertController = UIAlertController(title: "Destructive", message: "Simple alertView demo with Destructive and Ok.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alertlet DestructiveAction = UIAlertAction(title: "Destructive", style: UIAlertActionStyle.destructive) { (result : UIAlertAction) -> Void in print("Destructive")} // Replace UIAlertActionStyle.Default by UIAlertActionStyle.defaultlet okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("OK")}alertController.addAction(DestructiveAction)alertController.addAction(okAction)self.present(alertController, animated: true, completion: nil) See Alert With Destructive and OK Button: | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36394997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5513630/']} | jdg_74798 |
stackexchange | llm_judgeable_groundtruth_similarity | 3340032 |
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 saw this question: If a "Utilities" class is evil, where do I put my generic code? And I thought, why are utility classes evil? Let’s say I have a domain model that is dozens of classes deep. I need to be able to xml-ify instances. Do I make a toXml method on the parent? Do I make a MyDomainXmlUtility.toXml helper class? This is a case where the business need spans the entire domain model -- does it really belong as an instance method? What about if there are a bunch of auxiliary methods on the XML functionality of the application?
Now provide the response and nothing else.
| Utility classes aren't exactly evil, but they can violate the principles that compose a good object-oriented design. In a good object-oriented design, most classes should represent a single thing and all of its attributes and operations. If you are operating on a thing, that method should probably be a member of that thing. However, there are times when you can use utility classes to group a number of methods together — an example being the java.util.Collections class which provides a number of utilities that can be used on any Java Collection. These aren't specific to one particular type of Collection, but instead implement algorithms that can be used on any Collection. Really, what you need to do is think about your design and determine where it makes the most sense to put the methods. Usually, it's as operations inside of a class. However, sometimes, it is indeed as a utility class. When you do use a utility class, however, don't just throw random methods into it, instead, organize the methods by purpose and functionality. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3340032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305644/']} | jdg_74799 |
stackexchange | llm_judgeable_groundtruth_similarity | 10352211 |
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 excel VBA script: Set cоnn = CreateObject("ADODB.Connection")conn.Open "report"Set rs = conn.Execute("select * from table" ) Script work fine, but i want to add parameter to it. For example " where (parentid = myparam )", where myparam setted outside query string. How can i do it? Of course i can modify query string, but i think it not very wise.
Now provide the response and nothing else.
| You need to use an ADODB.Command object that you can add parameters to. Here's basically what that looks like Sub adotest() Dim Cn As ADODB.Connection Dim Cm As ADODB.Command Dim Pm As ADODB.Parameter Dim Rs as ADODB.Recordset Set Cn = New ADODB.Connection Cn.Open "mystring" Set Cm = New ADODB.Command With Cm .ActiveConnection = Cn .CommandText = "SELECT * FROM table WHERE parentid=?;" .CommandType = adCmdText Set Pm = .CreateParameter("parentid", adNumeric, adParamInput) Pm.Value = 1 .Parameters.Append Pm Set Rs = .Execute End WithEnd Sub The question mark in the CommandText is the placeholder for the parameter. I believe, but I'm not positive, that the order you Append parameters must match the order of the questions marks (when you have more than one). Don't be fooled that the parameter is named "parentid" because I don't think ADO cares about the name other than for identification. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10352211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420959/']} | jdg_74800 |
stackexchange | llm_judgeable_groundtruth_similarity | 17723944 |
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 my ASP.NET WebForms page I have a Modal window that pops up. The javascript code for displaying this modal window is as follows: function OpenMailAddressWin(subscriberContactRelationGid, routeId, btn) { window.showModalDialog("SubscriberSecondaryAddress.aspx" + BuildQueryStringValuesForSubscriber(subscriberContactRelationGid, routeId, returntxtReceiptDate().value), this, strWindowFeatures + ";scroll:no;dialogWidth:442px;dialogHeight:350px"); location.reload(true);} After the modal window is closed I need to refresh the parent page (hence the location.reload(true); statement at the end) in order for alterations made in the modal window to take affect. Now the thing is that sometimes (not every time, infuriatingly) when I close this modal window I get a warning popup which says: " To display the webpage again, Internet Explorer needs to resend the information you've recently submitted. If you were making a purchase, you should click Cancel to avoid a duplicate transaction. Otherwise, click Retry to display the webpage again." Any ideas why this is happening?
Now provide the response and nothing else.
| This is the double-submit problem in browsers. When a page is loaded using POST request and you try to reload the page using location.reload(true); , the browser needs to send another POST request to the server and this may cause problems as POST is supposed to change state on the server. Therefore, the browser needs confirmation from the user. To solve this problem, we usually use POST-REDIRECT-GET pattern. In your case, just simply using location.href = location.href should solve the problem as this will reload the page using GET. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17723944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736370/']} | jdg_74801 |
stackexchange | llm_judgeable_groundtruth_similarity | 1843087 |
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 just want to make sure I understand the explanation stated below. According to the order relation stated below we have $(a_0,a_1,...) < (b_0,b_1,..)$ if $a_i = b_i$ for finitely many values otherwise $a_n < b_n$? I also don't understand why the set X doesn't have a smallest element ?
Now provide the response and nothing else.
| For the first problem you will need a little bit of Chinese Remainder Theorem. You want to find the remainder of the stacked exponential modulo $10^5 = 2^5 \times 5^5$. Consider the two prime divisors separately. As $\phi(2^5) = 16$ we have that if $r_1$ is the remainder of $5^{5^{5^{5}}}$ modulo $\phi(2^5) = 16$ then $5^{5^{5^{5^{5}}}} \equiv 5^{r_1} \pmod {2^5}$. Now we have to find $r_1$, which is a solution of $5^{5^{5^{5}}} \equiv r_1 \pmod {2^4}$. Repeat this algorithm few times and you will get rid of the exponents and you will find a value such that: $5^{5^{5^{5^{5}}}} \equiv r \pmod {2^5}$. Now use that $5^{5^{5^{5^{5}}}} \equiv 0 \pmod {5^5}$ and glue the two solutions with Chinese Remainder Theorem. The second one can be solved using similar method, but this time you won't need the Chinese Remainder Theorem, as $(7,100) = 1$. Actually this is easier as $7^4 \equiv 1 \pmod {100}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1843087', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_74802 |
stackexchange | llm_judgeable_groundtruth_similarity | 13699740 |
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 use AccelerateDecelerateInterpolator and custom it.I can see that Interpolators like DecelerateInterpolator have a "factor" field so you can change its behaviors. but AccelerateDecelerateInterpolator has non.When I am using AccelerateDecelerateInterpolator I almost can't even notice that the interpolator is doing any thing. The animation looks very linear. So, is there any way to factor the AccelerateDecelerateInterpolator or change it in any way?Thanks
Now provide the response and nothing else.
| You can implement standard easing function with your own Interpolator .For example, this would be the implementation for the easeInOutQuint : public class MVAccelerateDecelerateInterpolator implements Interpolator { // easeInOutQuint public float getInterpolation(float t) { float x = t*2.0f; if (t<0.5f) return 0.5f*x*x*x*x*x; x = (t-0.5f)*2-1; return 0.5f*x*x*x*x*x+1; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13699740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1310478/']} | jdg_74803 |
stackexchange | llm_judgeable_groundtruth_similarity | 3303029 |
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 was reading http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 and trying to figure out how to continue a file download. For example, suppose a file is of length 100 bytes and I have all the 100 bytes. However, I don't know what the expected file size should be, so I ask for the file and specify a Range header that looks like this: Range: bytes=100- Is this a valid Range request?
Now provide the response and nothing else.
| It's a syntactically valid request, but not a satisfiable request. If you look further in that section you see: If a syntactically valid byte-range-set includes at least one byte- range-spec whose first-byte-pos is less than the current length of the entity-body, or at least one suffix-byte-range-spec with a non- zero suffix-length, then the byte-range-set is satisfiable. Otherwise, the byte-range-set is unsatisfiable. If the byte-range-set is unsatisfiable, the server SHOULD return a response with a status of 416 (Requested range not satisfiable) . Otherwise, the server SHOULD return a response with a status of 206 (Partial Content) containing the satisfiable ranges of the entity-body. So I think in your example, the server should return a 416 since it's not a valid byte range for that file. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3303029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155951/']} | jdg_74804 |
stackexchange | llm_judgeable_groundtruth_similarity | 2218773 |
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 issues with the old "Cannot make a static reference to a non-static method" error in my Android program. I am creating a sand falling game (similar to the Powder Game) and I created a class called Control to create a Control Bar at the bottom of the screen with a slider for brush size (that works fine) and a button to pop up a Dialog to allow users to pick the selected element. However, when I call DemoActivity.showDialog(2) from my code, it gives the static reference to non-static error (DemoActivity is the main activity of my application). I also tried changing it to just Activity.showDialog(2), but I got exactly the same error! Please help, what am I doing wrong? Here's my code and thanks in advance: package sand.falling.opengl;import android.content.Context;import android.util.AttributeSet;import android.util.Log;import android.view.View;import android.widget.ImageButton;import android.widget.LinearLayout;import android.widget.SeekBar;public class Control extends LinearLayout{ private ImageButton control_button; private SeekBar brush_size_slider; final CharSequence[] elementslist = {"Sand", "Water", "Plant", "Wall", "Fire", "Ice", "Generator", "Oil", "Magma", "Stone", "C4"}; public Control(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { control_button = (ImageButton) findViewById(R.id.element_picker_button); brush_size_slider = (SeekBar) findViewById(R.id.brush_size_slider); control_button.setOnClickListener ( new OnClickListener() { public void onClick(View v) { //THIS DOESN'T WORK!!!! DemoActivity.showDialog(2); //Run the element picker dialog } } ); control_button.setImageResource(R.drawable.palette); brush_size_slider.setOnSeekBarChangeListener ( new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekbar, int progress, boolean fromTouch) { int p = 32 * progress/100; DemoActivity.setBrushSize(p); Log.v("DemoActivity", "size:" + p); } public void onStartTrackingTouch(SeekBar seekbar) {} public void onStopTrackingTouch(SeekBar seekbar) {} } ); brush_size_slider.setProgress((int)400/32); }} EDIT: I fixed it by adding the following to my Control.java code: public class Control extends LinearLayout{ private DemoActivity activity; ... public void setActivity(DemoActivity act) { activity = act; } ... //Set a click listener for the button which should pop up element picker dialog when clicked control_button.setOnClickListener ( new OnClickListener() { public void onClick(View v) { activity.showDialog(2); //Run the element picker dialog } } );} And then calling control.setActivity(this); from my onResume section of DemoActivity.java! Hope it helps those of you with similar issues!!
Now provide the response and nothing else.
| You have to call showDialog on a DemoActivity instance, NOT on the class itself. The only time you can call ClassName.methodName() is if the method is defined as static. showDialog is not a static method. To fix this, you either need to instantiate a new DemoActivity or get an existing one, then call showDialog on that. Edit: If you already have a DemoActivity instance when you instantiate this Control object, perhaps the following modification will work: public class Control extends LinearLayout{ ... // add an Activity instance private Activity activity; // set the Activity in your constructor public Control(Context context, AttributeSet attrs, Activity activity) { super(context, attrs); this.activity = activity; } @Override protected void onFinishInflate() { ... // Use the instance activity here activity.showDialog(2); ... }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2218773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234256/']} | jdg_74805 |
stackexchange | llm_judgeable_groundtruth_similarity | 1935839 |
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:
The equation is $(x\sin(y/x) - y\cos(y/x))dx + x\cos(y/x)dy = 0$ I am almost sure that this is to be solved by substitution (I could be wrong though), and the closest I've been is making$$v = \frac{y}{x}\\ y = xv \\\frac{dy}{dx} = xdv + v\\$$Before this substitution I tried to simplify it by doing$$x\sin\frac{y}{x} - y\cos\frac{y}{x} + x\cos v \frac{dy}{dx}= 0 \\- y\cos\frac{y}{x} + x\cos\frac{y}{x}\frac{dy}{dx} = - x\sin\frac{y}{x} \\\cos\frac{y}{x} * (x-y)\frac{dy}{dx} = - x\sin\frac{y}{x} \\(x-y)\frac{dy}{dx} = - x\frac{\sin\frac{y}{x}}{\cos\frac{y}{x}} \\\frac{-(x-y)}{x}\frac{dy}{dx} = \frac{\sin\frac{y}{x}}{\cos\frac{y}{x}} \\\frac{-(x-y)}{x}\frac{dy}{dx} = Tan(y/x)$$And after the substitution $$((x-xv) / -x) * (xdv+v) = \tan(v)\\-(x^2dv - x^2vdv + xv - xv^2) / x = \tan(v)\\-xdv + xvdv - v + v^2 = \tan(v)$$ The problem is that after this step I'm pretty sure I did something wrong somewhere, I'm not really even sure that this is the substitution I should be trying, but when I tried to do one with the whole trigonometric functions instead of just the arguments it didn't work out either. How to solve this?
Now provide the response and nothing else.
| The statement that nonzero commutative rings enjoy the invariant basis number property is true without any form of choice. In fact, it even holds in constructive mathematics, so without using the law of excluded middle. A proof is contained in Fred Richman's three-page jewel Nontrivial uses of trivial rings . More specifically, he shows that: Let $A$ be a commutative ring. If there is a linear injection $A^n \to A^m$ with $n > m$ , then $1 = 0$ in $A$ . If there is a linear surjection $A^n \to A^m$ with $n < m$ , then $1 = 0$ in $A$ . The proof is fully explicit, showing how one can derive the equation $1 = 0$ from the (conditional) equations expressing the assumptions. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1935839', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/371034/']} | jdg_74806 |
stackexchange | llm_judgeable_groundtruth_similarity | 1939952 |
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've started with Ruby and am finding new, shorter, elegant ways to write code everyday. In solving Project Euler problems, I've written a lot of code like if best_score < current_score best_score = current_scoreend Is there a more elegant way to write this?
Now provide the response and nothing else.
| best_score = [best_score, current_score].max see: Enumerable. max disclaimer: although this is a little more readable (imho), it's less performant: require 'benchmark'best_score, current_score, n = 1000, 2000, 100_000Benchmark.bm do |x| x.report { n.times do best_score = [best_score, current_score].max end } x.report { n.times do best_score = current_score if best_score < current_score end }end will result in (with ruby 1.8.6 (2008-08-11 patchlevel 287)): user system total real0.160000 0.000000 0.160000 ( 0.160333)0.030000 0.000000 0.030000 ( 0.030578) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1939952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165737/']} | jdg_74807 |
stackexchange | llm_judgeable_groundtruth_similarity | 16663618 |
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've written two ways to async load pictures inside my UITableView cell. In both cases the image will load fine but when I'll scroll the table the images will change a few times until the scroll will end and the image will go back to the right image. I have no idea why this is happening. #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)- (void)viewDidLoad{ [super viewDidLoad]; dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://myurl.com/getMovies.php"]]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; });}-(void)fetchedData:(NSData *)data{ NSError* error; myJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; [_myTableView reloadData];} - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ // Return the number of rows in the section. // Usually the number of items in your array (the one that holds your list) NSLog(@"myJson count: %d",[myJson count]); return [myJson count];} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ myCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (cell == nil) { cell = [[myCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } dispatch_async(kBgQueue, ^{ NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]]; dispatch_async(dispatch_get_main_queue(), ^{ cell.poster.image = [UIImage imageWithData:imgData]; }); }); return cell;} ...... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ myCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (cell == nil) { cell = [[myCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]; NSURLRequest* request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * error) { if (!error){ cell.poster.image = [UIImage imageWithData:data]; // do whatever you want with image } }]; return cell;}
Now provide the response and nothing else.
| Assuming you're looking for a quick tactical fix, what you need to do is make sure the cell image is initialized and also that the cell's row is still visible, e.g: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg", self.myJson[indexPath.row][@"movieId"]]]; NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (data) { UIImage *image = [UIImage imageWithData:data]; if (image) { dispatch_async(dispatch_get_main_queue(), ^{ MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath]; if (updateCell) updateCell.poster.image = image; }); } } }]; [task resume]; return cell;} The above code addresses a few problems stemming from the fact that the cell is reused: You're not initializing the cell image before initiating the background request (meaning that the last image for the dequeued cell will still be visible while the new image is downloading). Make sure to nil the image property of any image views or else you'll see the flickering of images. A more subtle issue is that on a really slow network, your asynchronous request might not finish before the cell scrolls off the screen. You can use the UITableView method cellForRowAtIndexPath: (not to be confused with the similarly named UITableViewDataSource method tableView:cellForRowAtIndexPath: ) to see if the cell for that row is still visible. This method will return nil if the cell is not visible. The issue is that the cell has scrolled off by the time your async method has completed, and, worse, the cell has been reused for another row of the table. By checking to see if the row is still visible, you'll ensure that you don't accidentally update the image with the image for a row that has since scrolled off the screen. Somewhat unrelated to the question at hand, I still felt compelled to update this to leverage modern conventions and API, notably: Use NSURLSession rather than dispatching -[NSData contentsOfURL:] to a background queue; Use dequeueReusableCellWithIdentifier:forIndexPath: rather than dequeueReusableCellWithIdentifier: (but make sure to use cell prototype or register class or NIB for that identifier); and I used a class name that conforms to Cocoa naming conventions (i.e. start with the uppercase letter). Even with these corrections, there are issues: The above code is not caching the downloaded images. That means that if you scroll an image off screen and back on screen, the app may try to retrieve the image again. Perhaps you'll be lucky enough that your server response headers will permit the fairly transparent caching offered by NSURLSession and NSURLCache , but if not, you'll be making unnecessary server requests and offering a much slower UX. We're not canceling requests for cells that scroll off screen. Thus, if you rapidly scroll to the 100th row, the image for that row could be backlogged behind requests for the previous 99 rows that aren't even visible anymore. You always want to make sure you prioritize requests for visible cells for the best UX. The simplest fix that addresses these issues is to use a UIImageView category, such as is provided with SDWebImage or AFNetworking . If you want, you can write your own code to deal with the above issues, but it's a lot of work, and the above UIImageView categories have already done this for you. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16663618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1578927/']} | jdg_74808 |
stackexchange | llm_judgeable_groundtruth_similarity | 422047 |
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:
Simply put, I have date and time attributes on an Orders table. The data types for these attributes are MySQL's DATE attribute. But everytime I echo the date and time in PHP it just gives me a string, not a date object. I don't understand as to why the DATE data type exists if you can casually store date objects as VARCHAR in the db. $date = date("M d, Y");$time = date("H:i A");
Now provide the response and nothing else.
| I don't understand as to why the DATE data type exists Always store Date values in Date Fields. What PHP gives you back when you retrieve those values is a Character Representation of the Date value but, within the database, you can (and should) perform Date operations on Date fields that you simply cannot do effectively with Strings. For example, let's look at some similar-looking entries: select char_date, date_date from table1 order by char_date ; +-------------+-------------+| char_date | date_date | +-------------+-------------+| 01-Mar-2021 | 01-Mar-2021 || 12-Feb-2021 | 12-Feb-2021 || 23-Jan-2021 | 23-Jan-2021 | +-------------+-------------+select char_date, date_date from table1 order by date_date ; +-------------+-------------+| char_date | date_date | +-------------+-------------+| 23-Jan-2021 | 23-Jan-2021 | | 12-Feb-2021 | 12-Feb-2021 || 01-Mar-2021 | 01-Mar-2021 |+-------------+-------------+ See the difference? And because applications tend to apply far less control over how Character data is entered, your char_date data very quickly gets awfully messed up and even more difficult to interpret. For example, when is '01/04/07'? January 4th? April 1st? April 7th (2001)?Depends where you are in the world! OK, you could say that your application will convert the entered, Character Representation of a Date value into a proper Date and store a consistently-formatted [Character] version of that but, as soon as you start doing Date operation on those values, your database has to start doing Date conversions on the fly , which can be horribly slow. Use the Right Tool for the Right Job ... | {} | {'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/422047', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/384812/']} | jdg_74809 |
stackexchange | llm_judgeable_groundtruth_similarity | 319030 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The derivation of the prediction interval for the linear model is quite simple: Obtaining a formula for prediction limits in a linear model . How to derive the confidence and prediction intervals for the fitted values of the logit and probit regressions (and GLMs in general)?
Now provide the response and nothing else.
| In GLM, prediction is a non-linear function $f$ of the product of covariates $X$ with estimated coefficient vector $\hat{\beta}$:$$\hat{y} = f(X\hat{\beta})$$Finite-sample distribution of $\hat{\beta}$ is generally unknown, but as long as $\hat{\beta}$ is a maximum likelihood estimate , it has asymptotic normal distribution $\mathcal{N}(\beta, -H^{-1})$, where $H$ is the Hessian matrix of the likelihood function in its maximum. The p-values of $\beta$ that are shown as an output of a regression are nearly always based on this asymptotics. But if you feel your sample is too small for asymptotics, use numerical distribution (e.g. bootstrapping). When you use asymptotic normal distribution of $\hat{\beta}$ (and therefore $X\hat{\beta}$), distribution of $\hat{y}$ is still non-normal due to non-linear $f$. You can ignore it - get normal confidence bounds $(z_{lower}, z_{upper})$ for $X\beta$, and plug them into $f$, getting bounds for $y$ as $(y_{lower}, y_{upper}) = (f(z_{lower}), f(z_{upper}))$. Another strategy (called delta method ) is to take a Taylor expansion of $f$ around $X\hat{\beta}$ - it will be linear in $\hat{\beta}$. Therefore, you can approximate distribution of $f(X\hat{\beta})$ as $$f(X\hat{\beta}) \sim \mathcal{N}\left(f(X\beta), -(f^{'}(X\beta))^2 X H^{-1} X^T \right)$$ Then the asymptotic 95% confidence interval for $f(X\beta)$ would look like $$ f(X\hat{\beta}) \pm 1.96 \sqrt{(f^{'}(X\hat{\beta}))^2 X H(\hat{\beta})^{-1} X^T}$$ Now you need only to find expression for Hessian matrices for particular models, like logistic regression in this question . And this question presents practical comparison of bootstrap, transformed normal bounds, and delta method for logistic regression. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/319030', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/-1/']} | jdg_74810 |
stackexchange | llm_judgeable_groundtruth_similarity | 5129598 |
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 existing Rails app on GitHub and deployed on Heroku. I'm trying to set up a new development machine and have cloned the project from my GitHub repository. However, I'm confused as to how to link this folder up to Heroku. Originally, I used the heroku create command, but obviously I don't want to do that this time since it will create another Heroku instance.
Now provide the response and nothing else.
| Heroku links your projects based on the heroku git remote (and a few other options, see the update below). To add your Heroku remote as a remote in your current repository, use the following command: git remote add heroku [email protected]:project.git where project is the name of your Heroku project (the same as the project.heroku.com subdomain). Once you've done so, you can use the heroku xxxx commands (assuming you have the Heroku Toolbelt installed), and can push to Heroku as usual via git push heroku master . As a shortcut, if you're using the command line tool, you can type: heroku git:remote -a project where, again, project is the name of your Heroku project (thanks, Colonel Panic ). You can name the Git remote anything you want by passing -r remote_name . [Update] As mentioned by Ben in the comments, the remote doesn't need to be named heroku for the gem commands to work. I checked the source , and it appears it works like this: If you specify an app name via the --app option (e.g. heroku info --app myapp ), it will use that app. If you specify a Git remote name via the --remote option (e.g. heroku info --remote production ), it will use the app associated with that Git remote. If you specify no option and you have heroku.remote set in your Git config file, it will use the app associated with that remote (for example, to set the default remote to "production" use git config heroku.remote production in your repository, and Heroku will run git config heroku.remote to read the value of this setting) If you specify no option, the gem finds no configuration in your .git/config file, and the gem only finds one remote in your Git remotes that has "heroku.com" in the URL, it will use that remote. If none of these work, it raises an error instructing you to pass --app to your command. | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/5129598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1574/']} | jdg_74811 |
stackexchange | llm_judgeable_groundtruth_similarity | 329342 |
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:
Please scroll down to the bold subheaded section called Exact questions if you are too bored to read through the whole thing. I am a physics undergrad, trying to carry out some research work on topological solitons. I have been trying to read a paper that uses Kähler Manifolds. My guide just expects me to learn the mathematical definitions, without understanding it(or he expects me to study complex manifolds by scratch by myself), within 3-4 days, with exams going on, but I find this highly discomforting. So, it would be great if someone could tell me what is a Kähler manifold, highlighting the essential features of the definition and what they do, and intuitive explanations behind each. Why are they mathematically important? Also, some reasons as to why they are used in Physics? The definition on Wikipedia is very obscure, linking you to 7-8 pages, and you forget what you are actually looking for. I have read the following definition from Nakahara: A Kähler Manifold is an hermitian manifold, whose Kälher form is closed i.e. $d\Omega=0$. After searching the internet, I know the following: A Hermitian manifold is a complex manifold equipped with a metric $g$, such that $g_p(X,Y)=g_p(J_pX,J_p Y)$, where $p \in M$ and $X,Y \in T_pM$ Again the web tells me that, $J$ is a linear map between the tangent spaces at a point such that $J^2=-1$. Lastly, the Kähler form $\Omega$ is a tensor field whose action is given by $\Omega_p(X,Y)=(J_pX,Y)$. Exact questions: This is what I would really really want to understand. What is the meaning and motivation for $J^2=-1$? What is the intuitive meaning and motivation for the definition of the Hermitian manifold, and the Kähler form? Most importantly, what does the Kähler form is closed really mean? I am sorry for the long question, and would be delighted, even if I got a partial answer. Looking forward for the replies. I am not looking for exact arguments, but an intuitive overall picture. Background: I understand definitions of real manifolds, tangent spaces, and a differential forms. I have no intuition about exterior derivatives. I have a fair understanding of what is a complex manifold, and a few examples of Riemann surfaces.
Now provide the response and nothing else.
| First, as I think you know, Kähler manifolds are just special cases of Hermitian manifolds (complex manifolds with a Hermitian metric). There are a number of very different, but equivalent, ways to define Kähler manifolds. Here are a couple that might help: On a Riemannian manifold $X$, we can always choose 'Riemann normal coordinates' at any point $p \in X$. These are coordinates in which the metric takes its canonical form $g_{ab} = \delta_{ab}$ at $p$, and all its first derivatives vanish at $p$. On a general Hermitian manifold, it may not be possible to find holomorphic coordinates in which this is true. Kähler manifolds are exactly those manifolds on which we can always find a holomorphic change of coordinates which, at some given point, sets the metric to its canonical form, and its first derivatives to zero. Another characterisation of Kähler manifolds is as Hermitian manifolds for which the Christoffel symbols of the Levi-Civita connection are pure. In other words, $\Gamma^i_{jk}$ and $\Gamma^{\bar i}_{\bar j\bar k}$ may be non-zero, but all 'mixed' symbols like $\Gamma^{\bar i}_{jk}$ vanish. This means that (anti-)holomorphic vectors get parallel transported to (anti-)holomorphic vectors. Equivalent to the above is to say that $n$-dimensional Kähler manifolds are precisely $2n$-dimensional Riemannian manifolds with holonomy group contained in $U(n)$. All of this can be found in Moroianu's "Lectures on Kähler Geometry", which is quite a nice concise book. There is a lot more to be said about Kähler manifolds, but hopefully this gives you some intuition about them. | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/329342', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_74812 |
stackexchange | llm_judgeable_groundtruth_similarity | 28025 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I am sorry for the following question, because the actual answer to this question is in the beautiful works of Feferman and Jeroslow, but, unfortunately, I havn't any time to go into that specific field right now and maybe some of you is aware of the answer. The situation with Gödel's second incompleteness theorem is quite delicate. Let Pf(a, b) means that a is the Gödel number of proof of statement with Gödel number b and Neg(a, b) means that b is the Gödel number of negation of statement with Gödel number a. The main result of Gödel's work is representability of predicates Pf and Neg in formal arithmetic. Knowing that, we can define the Consistency of formal arithmetic in formal arithmetic as follows: " it is not the case that there exist a statement A such that A and (not) A are provable in formal arithmetic " or in the language of formal arithmetic: $$\forall x_1, x_2, x_3, x_4 [\neg (\operatorname{Pf}(x_1, x_3) \wedge \operatorname{Pf}(x_2, x_4) \wedge \operatorname{Neg}(x_3, x_4))].$$ Let's denote last proposition by W. Gödel's second incompleteness theorem says that W is not provable in formal arithmetic, i. e. the consistency of formal arithmetic is not provable in formal arithmetic.But Solomon Feferman in his remarkable paper of 1960 "Arithmetization of metamathematics in general setting" have found other formalization of consistency of formal arithmetic W' that is provable in formal arithmetic (see notes by E. Mendelson to the second theorem in formal arithmetic chapter of his "Intoduction to Mathematical logic"). Jeroslow ("Consistency statements in formal theories"), thereafter, studied consistency statements in a broader way. Can someone explain the nature of W'?(obviously, $W\Leftrightarrow W'$ can not be proven in PA). Can we interpret the provability of W' as the proof of consistency of formal arithmetic in formal arithmetic? How well are various consistency statements grasped today? Thanks in advance.
Now provide the response and nothing else.
| The key idea Feferman is exploiting is that there can be two different enumerations of the axioms of a theory, so that the theory does not prove that the two enumerations give the same theory. Here is an example. Let $A$ be a set of the axioms defined by some formula $\phi(n)$ (that is, $\phi(x)$ holds for exactly those $x$ that are in $A$). Define a new formula $\psi(n)$ like so: $\psi(n) \equiv \phi(n) \land \text{Con}( \langle x \leq n : \phi(x)\rangle)$ Where Con(σ) is a formula which says that no contradiction is provable from the axioms listed in the sequence σ. In the case where $A$ is the set of axioms for a suitable consistent theory $T$ that satisfies the second incompleteness theorem, the following hold: (1) In the standard model, we have $\phi(n) \Leftrightarrow \psi(n)$ for all $n$, because $T$ really is consistent. (2) T does not prove that $\phi(n) \Leftrightarrow \psi(n)$ for all $n$, because this equivalence implies that T is consistent. (3) If we use $\psi$ to define a formula Con ψ (T), then T will prove (under the assumption that the empty theory is consistent, if this is not provable in T) that the theory defined by ψ is consistent. However, T will not prove Con φ (T), which is the usual consistency sentence for T. This kind of example is presented in a more precise way in Feferman's 1960 paper that you mentioned, along with precise hypotheses on the theory and sharper results. My opinion is that we cannot regard a proof of Con ψ (T) as a proof of the consistency of T, because although φ and ψ are extensionally identical, they do not intensionally represent the same theory. Feferman expresses a similar idea on his p. 69. Of course, this is a matter of philosophy or interpretation rather than a formal mathematical question. Addendum The difference between extensional and intensional equality is easiest to explain by example. Let A be the empty set and let B be the set of integers larger than 1 that do not have a unique prime factorization. Then we know B is also the empty set: so A and B are extensionally equal. But the definition of B is much different than the definition of A: so A and B are intensionally different. This distinction is often important in contexts like computability and formal logic where the things that you work with are actually definitions (also called codes, indices, Gödel numbers, or notations) rather than the objects being defined. In many cases, extensional equality is problematic, because of computability or effectiveness problems. For example, in my answer above, we know that φ and ψ define the same set in the real world, but this fact requires proof, and that proof may be impossible in the object theory we are dealing with. On the other hand, intensional equality is easy to decide, provided you are working directly with definitions. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/28025', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6307/']} | jdg_74813 |
stackexchange | llm_judgeable_groundtruth_similarity | 25150223 |
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 Swift application that is launching a simple NSWindow , like so: func applicationDidFinishLaunching(notification: NSNotification!) { let storyboard = NSStoryboard(name: "MainStoryboard", bundle: NSBundle.mainBundle()) windowController = storyboard.instantiateInitialController() as? NSWindowController windowController?.showWindow(self)} This works great, my app launches and the window appears. However : The size is always the same. In the storyboard, I have specified an Autosave name: Note also the Restorable checkbox is checked. But regardless, the window appears the same size, every time. This has always "just worked" in the past, so I can't tell if this is a bug, or a piece I'm missing. Does autosaving automatically work with storyboards when instantiating and showing windows manually?
Now provide the response and nothing else.
| This seems to be an Xcode bug. I was able to workaround it by manually setting the NSWindowController windowFrameAutosaveName property: windowController?.windowFrameAutosaveName = "Main App Window" However... This only worked for me if the property was set to a different value than what is displayed in Interface Builder. If it's programmatically set to the same value that's being used in IB, it doesn't work. So in IB the autosave name is left to MainAppWindow , and programmatically it's set to Main App Window . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25150223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88111/']} | jdg_74814 |
stackexchange | llm_judgeable_groundtruth_similarity | 18486130 |
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 my application I need to make the user choose an input method. Once it's selected I should perform some task. How is detected that the user actually chooses an InputMethod ? This is the code used to show the InputMethod list. InputMethodManager imeManager = (InputMethodManager) mw.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);if (imeManager != null) { imeManager.showInputMethodPicker();} else { Toast.makeText(mw.getApplicationContext(), "IME ERROR", Toast.LENGTH_LONG).show();}
Now provide the response and nothing else.
| Unfortunately you cannot catch the input method which user picks in InputMethodPicker . However, you can check it after user picks it, using BroadcastReceiver . When IME changes, Intent.ACTION_INPUT_METHOD_CHANGED will be broadcasted. public class InputMethodChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_INPUT_METHOD_CHANGED)) { ..... /* You can check the package name of current IME here.*/ } }} Then, register it. IntentFilter filter = new IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED);registerReceiver(mReceiver, filter); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18486130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1196752/']} | jdg_74815 |
stackexchange | llm_judgeable_groundtruth_similarity | 431683 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This is an obvious continuation of an MO question . Let $r,s\in\mathbb N\cup\{\infty\}$ with $r\neq s$ , and $M,N$ two connected manifolds of positive dimension (which roots out the trivial case of a single point). I wonder whether the rings $C^r(M)$ and $C^s(N)$ of real-valued continuously $r$ -th (resp. $s$ -th) differentiable functions are non-isomorphic? More precisely, we have the following (combinations of) variants of conditions on $M$ and $N$ , although they might not affect the result nontrivially. Smoothness: weakest: $M$ is a $C^r$ -manifold and $N$ is a $C^s$ -manifold; strongest: both $M$ and $N$ are $C^\infty$ . Compactness: weakest: both are paracompact Hausdorff (usually present in the definition of manifolds); strongest: both are compact Hausdorff. There is also a variant of manifolds with boundaries, but I am not looking at this generality in this question. It seems that, in this case, Morse's lemma might not hold, thus the structure of vanishing ideals $\mathfrak m_x=\ker(C^r(M)\to\mathbb R)$ at a point $x\in M$ might be more complicated (say, maybe not regular). However, it seems possible that Tom Goodwillie's answer applies to the situation that one of $r$ and $s$ is $\infty$ .
Now provide the response and nothing else.
| If $r\neq s$ , then the rings $C_r(M),C_s(N)$ cannot be isomorphic nor can they be elementarily equivalent to each other. I claim that for all $r<\infty$ , there is a first order formula $\phi$ where $C_r(M)\models\phi$ if and only if $s=r$ . If $p/q$ is a reduced rational number where $q$ is odd, and $f$ is a real valued function (or real number), then we shall write $f^{p/q}$ for the unique function such that $(f^{p/q})^q=f^p$ . While the function $f^{p/q}$ is unique, the function $f^{p/q}$ may no longer be contained in a ring of $r$ -times continuously differentiable functions. If $\alpha=p/q$ is a reduced rational number, then let $\phi_\alpha$ denote the first statement "For each $f$ , the object $f^\alpha$ exists and is unique." More precisely, $\phi_\alpha$ is the statement "For each $f$ , there is a unique $g$ with $g^q=f^p$ ." Now, suppose that $\alpha=p/q$ is a reduced rational number with $q$ odd and that $\alpha$ is not an integer. Then $\frac{d^r}{dx^r}x^{\alpha}=\frac{\alpha!}{(\alpha-r)!}x^{\alpha-r}$ which is continuous and defined for every real number $x$ if and only if $\alpha>r$ . For non-logicians, the following proposition says that for $\alpha=p/q$ reduced, $q>1$ , $q$ odd, the ring $C_r(M)$ is closed under the function $f\mapsto f^\alpha$ if and only if $\alpha>r$ . Proposition: Suppose that $\alpha=p/q$ is a reduced rational number with $q$ odd and where $\alpha$ is not an integer. Then $C_r(M)\models\phi_\alpha$ if and only if $\alpha>r$ . Proof: Suppose $\alpha<r$ . Let $U\subseteq M$ and let $V\subseteq\mathbb{R}^n$ where both $U$ and $V$ are open. Let $\phi:U\rightarrow V$ be a chart. We can assume that $\mathbf{0}\in V$ since we may translate the set $V$ if necessarily. Now suppose that $g:V\rightarrow\mathbb{R}$ be a smooth function with compact support where $g|_W=1$ for some neighborhood $W$ of $\mathbf{0}$ . Let $h:V\rightarrow\mathbb{R}$ be the function defined by letting $h(x_1,\dots,x_n)=x_1\cdot g(x_1,\dots,x_n).$ Let $f:M\rightarrow\mathbb{R}$ be the function defined by letting $f(\mathbf{x})=0$ for $\mathbf{x}\not\in U$ and $f(\mathbf{x})=h(\phi(\mathbf{x}))$ for $\mathbf{x}\in U$ . Then $f\in C^r(M)$ . On the other hand, $h(x_1,\dots,x_n)^\alpha=x_1^\alpha$ in a neighborhood of $\mathbf{0}$ which is not a $C^r$ function. Therefore, since $f(\mathbf{x})^\alpha=h(\phi(\mathbf{x}))^\alpha$ for $\mathbf{x}\in U$ , the function $f^\alpha$ is not in $C^r(M).$ Now assume that $r<\alpha$ and $f\in C^r(M)$ . Then $f^\alpha\in C^r(M)$ since $f^\alpha$ is the composition of the two $C^r$ functions, namely $f$ and $x\mapsto x^\alpha.$ $\square$ | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/431683', 'https://mathoverflow.net', 'https://mathoverflow.net/users/176381/']} | jdg_74816 |
stackexchange | llm_judgeable_groundtruth_similarity | 868701 |
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:
If any two compound propositions $P$ and $Q$ are equivalent, then is the proposition formed from their biconditional $P \leftrightarrow Q$ always a tautology?
Now provide the response and nothing else.
| Note that $(1+x)^{200} = \displaystyle\sum_{k = 0}^{200}\dbinom{200}{k}x^k$. Let $\omega = e^{i2\pi/5}$ $(1+1)^{200} = \displaystyle\sum_{k = 0}^{200}\dbinom{200}{k}1^k$ $(1+\omega)^{200} = \displaystyle\sum_{k = 0}^{200}\dbinom{200}{k}\omega^k$ $(1+\omega^2)^{200} = \displaystyle\sum_{k = 0}^{200}\dbinom{200}{k}\omega^{2k}$ $(1+\omega^3)^{200} = \displaystyle\sum_{k = 0}^{200}\dbinom{200}{k}\omega^{3k}$ $(1+\omega^4)^{200} = \displaystyle\sum_{k = 0}^{200}\dbinom{200}{k}\omega^{4k}$ Now, since $1^k+\omega^k+\omega^{2k}+\omega^{3k}+\omega^{4k} = 5$ if $k$ is a multiple of $5$ and $0$ otherwise, we can add those $5$ equations together to get: $\displaystyle\sum_{\substack{k = 0 \\ 5 | k}}^{200}5\dbinom{200}{k} = \sum_{k = 0}^{40}5\dbinom{200}{5k} = 2^{200}+(1+\omega)^{200}+(1+\omega^2)^{200}+(1+\omega^3)^{200}+(1+\omega^4)^{200}$. Divide by $5$ and subtract $\dbinom{200}{200} = 1$ to get: $\displaystyle\sum_{k = 0}^{39}\dbinom{200}{5k} = \dfrac{1}{5}\left(2^{200}+(1+\omega)^{200}+(1+\omega^2)^{200}+(1+\omega^3)^{200}+(1+\omega^4)^{200}\right)-1$. Using the fact that $1+\omega = \phi e^{i\pi/5}$ and $1+\omega^2 = \frac{1}{\phi} e^{i2\pi/5}$, where $\phi = \dfrac{1+\sqrt{5}}{2}$, this simplifies to: $\displaystyle\sum_{k = 0}^{39}\dbinom{200}{5k} = \dfrac{1}{5}\left(2^{200}+2\phi^{200}+2\phi^{-200}\right)-1$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/868701', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/164631/']} | jdg_74817 |
stackexchange | llm_judgeable_groundtruth_similarity | 288631 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
After using robocopy to copy files to a new drive I realized that all the file and directory creation times and been reset to the time of copying. Are there some switches to make robocopy keep the original files times?
Now provide the response and nothing else.
| Take a look at the options for the /COPY:[copyflags] and /DCOPY switches. As per the ROBOCOPY /? usage info: /COPY:copyflag[s] :: what to COPY for files (default is /COPY:DAT). (copyflags : D=Data, A=Attributes, T=Timestamps). (S=Security=NTFS ACLs, O=Owner info, U=aUditing info)./DCOPY:T :: COPY Directory Timestamps. For example: ROBOCOPY c:\src d:\dest /MIR /COPY:DT /DCOPY:T Will copy all files and folders and preserve the date and time stamps. ROBOCOPY c:\src d:\dest /MIR /COPY:DAT /DCOPY:T Will copy all files and folders and preserve the date & time stamps and file attributes. There is also another (and I believe deprecated?) switch /TIMFIX which does much the same as /COPY:DT but it doesn't fix the time stamps on folders. These were tested with ROBOCOPY 5.1.10.1027 on Windows 7 x64 Ultimate. Be aware that the /MIR switch mirrors the directory that you are copying from; that is, /MIR will also delete files in the destination folder not found in the source folder. The /MIR switch is the equivalent of /E and the /PURGE switches used together (but with a minor exception ). | {} | {'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/288631', 'https://serverfault.com', 'https://serverfault.com/users/32056/']} | jdg_74818 |
stackexchange | llm_judgeable_groundtruth_similarity | 40664766 |
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 element that I'm referencing by Id: let infiniteScrollElement = document.getElementById('th-infinite-scroll-tracker'); I need to listen when the browser is has reached the bottom of the element. How to achieve this?
Now provide the response and nothing else.
| I think that all you want to do is detect the position of scroll. @HostListener("window:scroll", ["$event"])onWindowScroll() {//In chrome and some browser scroll is given to body taglet pos = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.offsetHeight;let max = document.documentElement.scrollHeight;// pos/max will give you the distance between scroll bottom and and bottom of screen in percentage. if(pos == max ) { //Do your action here }} Also don't forget to import HostListener from @angular/core. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40664766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4031815/']} | jdg_74819 |
stackexchange | llm_judgeable_groundtruth_similarity | 38832851 |
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 routing in the angular2 apps works well. But I am going to make some routeLink based on this : Here is my routing: const routes: RouterConfig = [ { path:'home' , component: FormComponent }, { path:'about', component: AboutComponent }, { path:'**' , component: FormComponent }]; And here are the links that I made: <ul class="nav navbar-nav item"> <li> <a routerLink='/home' routerLinkActive="active">Home</a> </li> <li> <a routerLink='/about' routerLinkActive="active">About this</a> </li></ul> I expect that, when I click on them it navigates to the corresponding component, but they do not perform anything?
Now provide the response and nothing else.
| The code you are showing there is absolutely correct. I suspect that your problem is that you are not importing RouterModule (which is where RouterLink is declared) into the module which uses this template. I had a similar problem and it took me some time to solve as this step is not mentioned in the documentation. So go to the module that declares the component with this template and add: import { RouterModule } from '@angular/router'; then add it to your modules imports e.g. @NgModule({ imports: [ CommonModule, RouterModule ], declarations: [MyTemplatesComponent]})export class MyTemplatesModule { } Along with having the correct import statements, you'll also need a place for that routerLink to be shown, which is in the <router-outlet></router-outlet> element, so that also needs to be placed somewhere in your HTML markup so the router knows where to display that data. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/38832851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2380115/']} | jdg_74820 |
stackexchange | llm_judgeable_groundtruth_similarity | 27501219 |
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 making a JomSocial plugin to get name of the user but when I echo the name it is not displaying the name. Here is my code <?phpdefined('_JEXEC') or die('Restricted access');require_once JPATH_ROOT .'/components/com_community/libraries/core.php';class plgCommunityName extends JPlugin{ function getUserDetails(){ $cuser = CFactory::getUser(); $name = $cuser->username; echo $name; }}?> How can I do this ?
Now provide the response and nothing else.
| Recommended solution I would say that you should not disable csrf tokens on a production site. You may make session (and thus the csrf token) last longer (but it usually should not last longer than a day, especially for not-logged-in users as it is a DOS vector), but the real solution may be to automatically refresh the login page when the csrf token expires. You may use a <META HTTP-EQUIV="REFRESH" CONTENT="csrf_timeout_in_seconds"> in your login page header. If the user lets the login page sit for hours, it should not bother him that the page got refreshed. Second solution A possible solution which does not require you to actually store sessions but allows for infinite timeout is that you can generate your csrf tokens with hashing from the session id and a server-side secret: csrf = hash(sessionid+secret) Note however that you need to really dig and override spring-security internal mechanisms, namely: re-creating anonymous sessions on the fly if a request arrives and no such session exists re-creating the csrf token on the fly from the session id And choose a very secure hashing algorithm, preferably sha-512. Third solution You could have a small javascript that calls a no-op page on your server regularly (just before the session timeout), thus extending your session. This results in infinite session timeout only if the browser is on all the time, so the DOS aspect is mitigated. Ok, one last solution You can alter the CSRF token checking code, and disable it for the login page. This is actually synonymous with the second solution, but is specific for the login page, not generally for all anonymous sessions. You can do this e.g. by setting a custom RequestMatcher in HttpSecurity: http.csrf().requireCsrfProtectionMatcher(new MyCsrfRequestMatcher());...class MyCsrfRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return !request.getServletPath().equals("/login"); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27501219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3426561/']} | jdg_74821 |
stackexchange | llm_judgeable_groundtruth_similarity | 18522173 |
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 parse a multipart/form-data sent from $.ajax() and on the server side data is coming in req.body not in req.files as stated in the documentation of express. What I am trying to do is sending multiple image files and form data through $.ajax ,then receive it on the server side and sent those images as an attachments through nodemailer , so to sent it through nodemailer I need to be able to read that, what I get is just garbage of data in req.body, which I cannot even read. The code is below. Client-Side Ajax request sending function:- $('.contact-button').on('click', function(e) { e.preventDefault(); var data = new FormData(); var filesList = document.getElementById('files'); for (var i = 0; i< filesList.files.length; i ++) { data.append('file', filesList.files[i]); } data.append('messageData', $('#contact-form').serialize()); $.ajax({ url: '/api/contactus/', data: data, processData: false, type: "POST", contentType: 'multipart/form-data', mimeType: 'multipart/form-data', success: function (data) { console.log("SUCCESS IN AJAX"); console.dir(data); }, error: function (err) { console.log('error in AJAX'); console.log(err); } });}); Server Side API handling the Request:- function contactUs (req, res, next) { console.log("TESTING Body "); console.dir(req.body); console.log("TESTING Files"); console.dir(req.files); var Transport = email.createTransport("SMTP", { service: "Gmail", auth: { user: "[email protected]", pass: "dumy1234" } }); Transport.sendMail({ host : "smtp.gmail.com", port : "587", domain : "domain.com", to : "[email protected]", from : "[email protected]", subject : "[Technical Support] "+EmailInfo.Name + " Submitted an Issue!", reply_to: req.body.Email, html : "<h2 >Message Details</h2>", authentication : "login", username: '[email protected]', password: 'dumy1234' }, function (err, result) { if (err) { next('email sending failed', err); } else { res.json('email sending Success'); } });} So the two questions is how to parse multipart data coming through ajax request.?second How to sent multipart data as an attachment through nodemailer.? Just keep in mind I already tried to use app.use(express.multipart()); , but when I inserted it in my app.js it gave me 400 bad request ,and didn't even executed the contactUs function.
Now provide the response and nothing else.
| While you can call root.update() in your loop, this will still produce some (potentially) undesirable side-effects. The program may act laggy, meaning it takes a long time to respond to user input. You will only be able to run this one action. Any other action has to wait for this to finish. As an alternative I would suggest that you implement simple multi-threading. Python multithreading is pretty simple, and will prevent both of these drawbacks. You will be able to execute your long running code, while still providing a clean and responsive UI. If your application is trivially parallelizable, you could use multiple threads to decrease running time. Ex. Thread 1 handles entries 1-100, while thread 2 handles entries 101-200. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18522173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2517209/']} | jdg_74822 |
stackexchange | llm_judgeable_groundtruth_similarity | 154403 |
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 am trying trying to control a 5V relay (SRD-05VDC-SL-C) with the ATtiny85. I have a simple sketch uploaded (Blink without Delay example): const int ledPin = 0; // the number of the LED pinint ledState = LOW; // ledState used to set the LEDunsigned long previousMillis = 0; // will store last time LED was updatedconst long interval = 1000; // interval at which to blink (milliseconds)void setup() { pinMode(ledPin, OUTPUT); }void loop(){ unsigned long currentMillis = millis(); if(currentMillis - previousMillis >= interval) { previousMillis = currentMillis; if (ledState == LOW) ledState = HIGH; else ledState = LOW; digitalWrite(ledPin, ledState); }} The whole thing is being powered by an 18650 Li-Ion battery (3.7V-4.2V) and the measured input is averaging 3.88V. Here is a quick sketch of how the circuit looks like: Some issues comes up WITHOUT the motor connected: If I connect the battery and relay directly, you can hear it click, despite it being rated at 5V input. If I try to trigger the relay from Pin0, the oscilloscope will show the voltage of Pin0 to be about 2.72V, when the relay looks to be switching. If I replaced the relay with an LED, the voltage of Pin0 is about 3.88V. What causes the drop in voltage? I believe the current should be enough since it's an Li-Ion battery. What sort of protection do I need to implement in this circuit? Will the Li-Ion battery be enough to power this circuit? If I connect just battery, relay, and motor, it runs fine. The issue comes with the addition of the ATtiny85.
Now provide the response and nothing else.
| You should not really drive the relay coil directly from the microcontroller pin. Instead, I would recommend using an NPN transistor between GND (emitter) and the coil (collector), then connect the other side of the coil to the positive supply directly. Connect a diode backwards in parallel to the coil (i.e. diode cathode to positive supply, diode anode to transistor collector). This is a "fly-back" diode to protect against the back-EMF you get with the coil switches. Put something like a 330 ohm resistor in series between the transistor base and the microcontroller pin. This limits the current into the base of the transistor to a level that is within the capabilities of the microcontroller. That's the most common way I know of to control a relay with a GPIO pin of a micrcontroller. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/154403', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/57207/']} | jdg_74823 |
stackexchange | llm_judgeable_groundtruth_similarity | 1931604 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For a simple struct-like class: class Tiger attr_accessor :name, :num_stripesend what is the correct way to implement equality correctly, to ensure that == , === , eql? , etc work, and so that instances of the class play nicely in sets, hashes, etc. EDIT Also, what's a nice way to implement equality when you want to compare based on state that's not exposed outside the class? For example: class Lady attr_accessor :name def initialize(age) @age = age endend here I'd like my equality method to take @age into account, but the Lady doesn't expose her age to clients. Would I have to use instance_variable_get in this situation?
Now provide the response and nothing else.
| To simplify comparison operators for objects with more than one state variable, create a method that returns all of the object's state as an array. Then just compare the two states: class Thing def initialize(a, b, c) @a = a @b = b @c = c end def ==(o) o.class == self.class && o.state == state end protected def state [@a, @b, @c] endendp Thing.new(1, 2, 3) == Thing.new(1, 2, 3) # => truep Thing.new(1, 2, 3) == Thing.new(1, 2, 4) # => false Also, if you want instances of your class to be usable as a hash key, then add: alias_method :eql?, :== def hash state.hash end These need to be public. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1931604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53529/']} | jdg_74824 |
stackexchange | llm_judgeable_groundtruth_similarity | 4119766 |
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 $G$ be a finite group. It is easy to prove that the elements of $G$ with odd order are in odd number. Indeed, if, for every divisor $d$ of the order of $G$ , $r_{d}$ denotes the number of elements of $G$ with order $d$ , then the number of elements of $G$ with odd order is $1 + \sum_{d} r_{d}$ , where $d$ ranges over the odd divisors of $\vert G \vert$ such that $d \geq 3$ ; but $r_{d}$ is divisible by $\varphi (d)$ (Euler function) and, for a naturel number $n \geq 3$ , $\varphi (n)$ is even, thus it is well true that the elements of $G$ with odd order are in odd number. So, my question is : let $G$ be a finite group and $p$ a prime number; is it known if it is necessarily true that the elements of $G$ with order coprime to $p$ are in number coprime to $p$ ? I found some lemmas and, if I am not wrong, these lemmas make it possible to prove that the answer is "yes" for every group of order $\leq 431$ . Since my proof of this meager result is very long, I will only sketch it if I don't get a better answer. Edit (August 8, 2021). I discover that this question is Exercise 28 b) in Bourbaki, Algèbre, ch. I (Paris, 1970), § 6, p. I.139.
Now provide the response and nothing else.
| Let $\Omega_p(G)$ denote the set of elements of $G$ of order coprime to $p$ , and pick a $p$ -Sylow subgroup $P$ . We may let $P$ act on $\Omega_p(G)$ by conjugation, in which case the orbits’ sizes are powers of $p$ . The only orbits of size not divisible by $p$ then are the fixed points, which are precisely the elements of $$C_G(P)\cap\Omega_p(G)=\Omega_p(C_G(P)),$$ so we have a congruence $$ |\Omega_p(G)|\equiv |\Omega_p(C_G(P))| \pmod p $$ Either $C_G(P)$ is strictly smaller than $G$ or $P$ is central. Thus, we may apply induction, with our base cases those groups $G$ with central $p$ -Sylow subgroup $P\le Z(G)$ . Then we can prove Lemma . If $G$ has a central $p$ -Sylow subgroup $P$ then $\Omega_p(G)$ is a transversal for $G/P$ . Proof . First we show no two elements $x,y\in\Omega_p(G)$ represent the same coset. If $xP=yP$ then $y=xu$ for some $u\in P$ . Taking orders of both sides yields $|y|=|xu|=|x||u|$ since $x,u$ commute and have coprime orders. Since $p\nmid|y|$ and $|u|$ is a power of $p$ , this forces $|u|=1$ , hence $u=e$ , hence $x=y$ are the same representative. cont’d . Second we show every $g\in G$ is in $\Omega_p(G)P$ . By Chinese Remainder Theorem for cyclic groups we can write an internal direct product $\langle g\rangle=\langle g^\alpha\rangle\times\langle g^\beta\rangle$ with $g^\alpha\in\Omega_p(G)$ and $g^\beta\in P$ . Then we should also be able to write $g=(g^\alpha)^\delta(g^\beta)^\gamma\in\Omega_p(G)P$ . The lemma implies, in our base cases where there is a central Sylow subgroup, that $|\Omega_p(G)|=[G:P]$ is coprime to $p$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4119766', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/72877/']} | jdg_74825 |
stackexchange | llm_judgeable_groundtruth_similarity | 13954517 |
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: casting unused return values to void What is the purpose of (void) before a function call, for example (void)func1(); I assume this is the same as simply calling func1(); Therefore is the (void) call simply to let other programmers know that the return type will be ignored, for instance if func1() had a return type of int , or does the compiler perhaps perform some optimizations on the function? Perhaps there is another reason behind it altogether - is it even legal C++ or perhaps is it a remnant of C seen in some legacy code. Thanks
Now provide the response and nothing else.
| A cast to void can have semantic effect in one case: where a value is an operand of the comma operator and overrides the comma operator, a cast to void will suppress it: struct S { int operator,(int) { return 0; }};std::cout << (S(), 42) << '\n'; // prints '0'std::cout << ((void) S(), 42) << '\n'; // prints '42' | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13954517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1826217/']} | jdg_74826 |
stackexchange | llm_judgeable_groundtruth_similarity | 2040788 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Anyone knows about it?
Now provide the response and nothing else.
| Short version: line-height: 150% is static, line-height: 1.5 is dynamic. The effect is more evident on inheriting elements. An example: HTML <div style="font-size: 12px"> <span style="font-size: 24px">test</span></div> This CSS div { line-height: 150%; } /* Computed line-height: 18px (150% * 12px) */span { } /* Computed line-height: 18px (inherited directly) */ As opposed to this: div { line-height: 1.5 } /* Computed line-height: 18px (1.5 * 12px) */span { } /* Computed line-height: 36px (1.5 * 24px) */ You may read more at the CSS2 specs page | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2040788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198729/']} | jdg_74827 |
stackexchange | llm_judgeable_groundtruth_similarity | 453030 |
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 can I create a product key for my C# Application? I need to create a product (or license) key that I update annually. Additionally I need to create one for trial versions. Related: How do I best obfuscate my C# product license verification code? How do you protect your software from illegal distribution?
Now provide the response and nothing else.
| You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it). Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it. You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for. Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this. Consider also the support costs of having to deal with users who have forgotten their key, etc. edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/453030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53605/']} | jdg_74828 |
stackexchange | llm_judgeable_groundtruth_similarity | 1954358 |
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've written a small utility that allows me to change a simple AppSetting for another application's App.config file, and then save the changes: //save a backup copy first. var cfg = ConfigurationManager.OpenExeConfiguration(pathToExeFile); cfg.SaveAs(cfg.FilePath + "." + DateTime.Now.ToFileTime() + ".bak"); //reopen the original config again and update it. cfg = ConfigurationManager.OpenExeConfiguration(pathToExeFile); var setting = cfg.AppSettings.Settings[keyName]; setting.Value = newValue; //save the changed configuration. cfg.Save(ConfigurationSaveMode.Full); This works well, except for one side effect. The newly saved .config file loses all the original XML comments, but only within the AppSettings area. Is it possible to to retain XML comments from the original configuration file AppSettings area? Here's a pastebin of the full source if you'd like to quickly compile and run it.
Now provide the response and nothing else.
| I jumped into Reflector.Net and looked at the decompiled source for this class. The short answer is no, it will not retain the comments. The way Microsoft wrote the class is to generate an XML document from the properties on the configuration class. Since the comments don't show up in the configuration class, they don't make it back into the XML. And what makes this worse is that Microsoft sealed all of these classes so you can't derive a new class and insert your own implementation. Your only option is to move the comments outside of the AppSettings section or use XmlDocument or XDocument classes to parse the config files instead. Sorry. This is an edge case that Microsoft just didn't plan for. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1954358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/101827/']} | jdg_74829 |
stackexchange | llm_judgeable_groundtruth_similarity | 237093 |
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:
Consider the poset ($\mathbb{Z}^+ - \{1\}, |)$. What is the least upper bound and greatest lower bound of $\{6,10,14,15\}$? I don't see how the set in the question applies to the poset. What operations am I supposed to be performing on these numbers to determine what the GLB or LUB is? EDIT: The answer says there is no GLB and that the LUB = 2*3*5*7 = 210. Why is this so?
Now provide the response and nothing else.
| You’ve been given the order relation: it’s $\mid$, divisibility. Because it may be difficult to think order relation when you see $\mid$, let me use $\preceq$ instead: I’ll write $m\preceq n$ if and only if $m\mid n$. Thus, for instance, $3\preceq12$, but $3\not\preceq 5$. You’re asked for the least upper bound and greatest lower bound of the set $\{6,10,14,15\}$. The least upper bound, if it exists, is an integer $n\in\Bbb Z^+\setminus\{1\}$ such that: $6\preceq n$, $10\preceq n$, $14\preceq n$, and $15\preceq n$; and if $m\in\Bbb Z^+\setminus\{1\}$ and $6\preceq m$, $10\preceq m$, $14\preceq m$, and $15\preceq m$, then $n\preceq m$. The first condition makes $n$ an upper bound for $\{6,10,14,15\}$; the second makes it the least upper bound. Remember that $\preceq$ is really just divides , so the first condition really just requires that $n$ be a multiple of each of the numbers $6,10,14$, and $15$; in other words, it must be a common multiple of the elements of the set $\{6,10,14,15\}$. The second condition says that if $m$ is any common multiple of these four numbers, then $n\mid m$; in other words, $n$ is not just a common multiple of them, but the least common multiple. You should now be able both to find $n$. With that as an example, you should be able to figure out what a lower bound has to be in terms of divisibility, and then what the greatest lower bound must be. Be careful, though: remember that $1$ is not in the partial order. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/237093', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19493/']} | jdg_74830 |
stackexchange | llm_judgeable_groundtruth_similarity | 40015171 |
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 main class, AddFriendsController , that runs the following line of code: ErrorReporting.showMessage("Error", msg: "Could not add student to storage.") I then have this ErrorReporting.swift file: import Foundation class ErrorReporting { func showMessage(title: String, msg: String) { let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }} Obviously, self wouldn't work here, and is giving me an error. How can I refer to the currently open view controller (i.e. AddFriendsController in this circumstance), as I am wishing to use this same method in many different swift files? Thanks.
Now provide the response and nothing else.
| You can create extension method for UIApplication (for example) which will return your topViewController: extension UIApplication { static func topViewController(base: UIViewController? = UIApplication.sharedApplication().delegate?.window??.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController, selected = tab.selectedViewController { return topViewController(selected) } if let presented = base?.presentedViewController { return topViewController(presented) } return base }} And then your class will look like this: class ErrorReporting { static func showMessage(title: String, msg: String) { let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) UIApplication.topViewController()?.presentViewController(alert, animated: true, completion: nil) }} Method need to be static to be able to call it as ErrorReporting.showMessage . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40015171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1136709/']} | jdg_74831 |
stackexchange | llm_judgeable_groundtruth_similarity | 160777 |
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 a non-relativistic particle of mass $m$, moving along the $x$-axis in a potential $V(x) = m\omega^2x^2/2$. use path-integral methods to find the probability to find the particle between $x_1$ and $x_1 + dx_1$ if the particle is at $x_0$ at time $t = 0$. One finds the propagator to be $$P(x_1, t_1; x_0, 0) = \sqrt{{{m\omega}\over{2\pi i\hbar \sin \omega t_1}}}e^{{{im\omega}\over{2\hbar \sin\omega t_1}}((x_0^2 + x_1^2)\cos\omega t_1 - 2x_0x_1)}$$and the requisite probability to be $$\left|\int P(x_1, t_1; x_0, 0)\psi(x_1)\,dx_1\right|^2$$for some wavepacket $\psi$ localized between $x_1$, $x_1 + dx_1$. In the limit $x_1 \to x_0$, we have$$\lim_{(x_1 - x_0) \to 0} P(x_1, t_1; x_0, 0) = \sqrt{{m\omega}\over{2\pi i\hbar \sin\omega T}}e^{{{im\omega}\over{\hbar\sin\omega T}}(x_0^2\cos\omega T - x_0^2)}.$$ My question is, what is the physical significance of taking this limit $x_1 \to x_0$?
Now provide the response and nothing else.
| As $T = t_1 - t_0 \to 0$, we have$$\begin{align}\lim_{t_1 -~ t_0~ \to~ 0} \langle x_1, t_1\,|\,x_0, t_0\rangle &= \lim_{T~ \to~ 0}\left({{m\omega}\over{2\pi i\sin\omega T}}\right)^{1/2}\text{exp}\left[{{im\omega}\over{2\sin\omega T}}\left(\left(x_1^2 + x_0^2\right)\cos \omega T - 2x_0x_1\right)\right]\\ &=\lim_{\epsilon ~= ~iT/m~ \to~ 0} {1\over{\sqrt{2\pi\epsilon}}}\text{exp}\left[-{{(x_1 - x_0)^2}\over{2\epsilon}}\right] = \delta(x_1 - x_0).\end{align}$$This is just as expected from the orthonormality of $\hat{x}(t)$ eigenvalues at $t = t_0$. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/160777', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']} | jdg_74832 |
stackexchange | llm_judgeable_groundtruth_similarity | 29390155 |
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 what way is the design scaled up or down? I'm trying to figure out what exactly happens at the CSS level, and what the consequences are for different sizing methods ( px , em , rem , etc). By the way, I am mainly concerned with zooming behaviour for modern desktop browsers. (I suspect mobile browser to be a straight enlargement of the whole page after rendering it normally, and know that old fashioned browsers just increment the base font-size). What isn't clear however, is what modern browsers (say the latest versions of Chrome or FF) do exactly when the user presses Ctrl + or Ctrl - . Do they also just render the page normally (i.e. at 100%) and then just enlarge the rendered image? Because FF still seems to respect % widths for example, so it doesn't seem to be a straight up enlargement.
Now provide the response and nothing else.
| Zooming as implemented in modern browsers consists of nothing morethan “stretching up” pixels. That is, the width of the element is notchanged from 128 to 256 pixels; instead the actual pixels are doubledin size. Formally, the element still has a width of 128 CSS pixels,even though it happens to take the space of 256 device pixels. In other words, zooming to 200% makes one CSS pixel grow to four timesthe size of one device pixels. (Two times the width, two times theheight, yields four times in total). Source: Concept of device pixels and CSS pixels | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29390155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4210742/']} | jdg_74833 |
stackexchange | llm_judgeable_groundtruth_similarity | 14160 |
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:
When I open this ssh tunnel: ssh -nXNT -p 22 localhost -L 0.0.0.0:8984:remote:8983 I get this error when trying to access the HTTP server running on localhost:8984: channel 1: open failed: administratively prohibited: open failed What does this error mean, and on which machine can you fix the problem?
Now provide the response and nothing else.
| channel 1: open failed: administratively prohibited: open failed The above message refers to your SSH server rejecting your SSH client's request to open a side channel. This typically comes from -D , -L or -w , as separate channels in the SSH stream are required to ferry the forwarded data across. Since you are using -L (also applicable to -D ), there are two options in question that are causing your SSH server to reject this request: AllowTcpForwarding (as Steve Buzonas mentioned) PermitOpen These options can be found in /etc/ssh/sshd_config . You should ensure that: AllowTCPForwarding is either not present, is commented out, or is set to yes PermitOpen is either not present, is commented out, or is set to any [1] Additionally, if you are using an SSH key to connect, you should check that the entry corresponding to your SSH key in ~/.ssh/authorized_keys does not have no-port-forwarding or permitopen statements [2] . Not relevant to your particular command, but somewhat relevant to this topic as well, is the PermitTunnel option if you're attempting to use the -w option. [1] Full syntax in the sshd_config(5) manpage. [2] Full syntax in the authorized_keys(5) manpage. | {} | {'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/14160', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2323/']} | jdg_74834 |
stackexchange | llm_judgeable_groundtruth_similarity | 29908128 |
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 using Gson to serialize an Active Android model. The model class contains only primitives, and Gson should have no issues serializing it with the default settings. However, when I try, I get the error: java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: <MyClass>. Forgot to register a type adapter? I would really rather not write a type adapter for every one of my model classes, how can I get around this issue?
Now provide the response and nothing else.
| Figured it out. Of course, Active Android's base model class is adding fields that cannot be serialized by default. Those fields can be ignored using Gson's excluedFieldsWithoutExposeAnnotation() option, as follows: Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();String json = gson.toJson(new Book()); Modify the class with the @Expose annotation to indicate which fields should be serialized: @Table(name = "Foo")public class Foo extends Model { @Expose @Column(name = "Name") public String name; @Expose @Column(name = "Sort") public int sort; ...} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29908128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2364687/']} | jdg_74835 |
stackexchange | llm_judgeable_groundtruth_similarity | 39821590 |
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 faced a styling problem. What is the best way to have my text lines in a single line? Screenshot of the problem: My code is rather simple: <section id="key-features" class="key-features"> <div class="container"> <h2>Key Features</h2> <div class="col-md-4 col-sm-4 col-xs-12"> <ul> <li><img src="images/icons/1.png" alt="Atmospheric pressure test"/>Atmospheric pressure test</li> <li><img src="images/icons/compass.png" alt="Altitude monitor"/>Altitude monitor</li> <li><img src="images/icons/alc.png" alt="Temperature"/>Temperature test</li> <li><img src="images/icons/hr.png" alt="Heart rate"/>Heart rate monitor</li> <li><img src="images/icons/shoe.png" alt="Pedometer"/>Pedometer</li> </ul> </div> <div class="col-md-4 col-sm-4 col-xs-12 pull-left"> <ul> <li><img src="images/icons/food.png" alt="Calorie"/>Calorie</li> <li><img src="images/icons/location.png" alt="Distance"/>Distance</li> <li><img src="images/icons/sleep.png" alt="Sleep monitor"/>Sleep monitor</li> <li><img src="images/icons/bell.png" alt="Sedentary remind"/>Sedentary remind</li> <li><img src="images/icons/drink.png" alt="Water drink remind"/>Water drink remind</li> </ul> </div> <div class="col-md-4 col-sm-4 col-xs-12 pull-left"> <ul> <li><img src="images/icons/alarm.png" alt="test"/>Alarm remind</li> <li><img src="images/icons/phone.png" alt="Call remind"/>Call remind</li> <li><img src="images/icons/camera.png" alt="Photograph"/>Photograph</li> <li><img src="images/icons/dna.png" alt="Share moments"/>Share moments</li> <li><img src="images/icons/bt.png" alt="Anti-los"/>Anti-lost</li> </ul> </div> </div> </section>
Now provide the response and nothing else.
| Using CSS' overflow , your element needs to have somewhat fixed boundries. Since you're writing some plain text and your browser is wrapping that automatically into a new line and your elements boundries are getting exceeded. In order to disable that you'd have to use white-space: nowrap; first. After that you are able to go ahead with overflow by doing overflow: auto; . Since you need that on all of your li elements, so you don't have to manually check if something is weird or not, you'd do so: li { overflow: auto; white-space: nowrap;} Your text shouldn't overflow anymore and you can now scroll inside of your element to show off the missing content. Demo | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39821590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5423506/']} | jdg_74836 |
stackexchange | llm_judgeable_groundtruth_similarity | 2794272 |
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 wondering what algorithm would be clever to use for a tag driven e-commerce enviroment: Each item has several tags. IE: Item name: "Metallica - Black Album CD", Tags: "metallica", "black-album", "rock", "music" Each user has several tags and friends(other users) bound tothem. IE: Username: "testguy", Interests: "python", "rock", "metal", "computer-science" Friends: "testguy2", "testguy3" I need to generate recommendations to such users by checking their interest tags and generating recommendations in a sophisticated way. Ideas: A Hybrid recommendation algorithm can be used as each user has friends.(mixture of collaborative + context based recommendations). Maybe using user tags, similar users (peers) can be found to generate recommendations. Maybe directly matching tags between users and items via tags. Any suggestion is welcome. Any python based library is also welcome as I will be doing this experimental engine on python language.
Now provide the response and nothing else.
| 1) Weight your tags. Tags fall into several groups of interest: My tags that none of my friends share Tags a number of my friends share, but I don't My tags that are shared by a number of my friends. (sometimes you may want to consider friend-of-a-friend tags too, but in my experience the effort hasn't been worth it. YMMV.) Identify all tags that the person and/or the person's friends have in interests, and attach a weight to the tags for this individual. One simple possible formula for tag weight is (tag_is_in_my_list) * 2 + (friends_with_tag)/(number_of_friends) Note the magic number 2, which makes your own opinion worth twice as much as that of all of your friends put together. Feel free to tweak :-) 2) Weight your items For each item that has any of the tags in your list, just add up all of the weighted values of the tags. A higher value = more interest. 3) Apply a threshold. The simplest way is to show the user the top n results. More sophisticated systems also apply anti-tags (i.e. topics of non-interest) and do many other things, but I have found this simple formula effective and quick. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2794272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151937/']} | jdg_74837 |
stackexchange | llm_judgeable_groundtruth_similarity | 128298 |
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:
I searched around, but couldn't find any, please help.For example, I got this:$$-\frac{i}{2 \pi (-i \gamma +\text{V0}+\Omega )}$$Which command will yield this result: $$ -\frac{i \gamma +\text{V0}+\Omega }{2 \pi \left(\gamma ^2+(\text{V0}+\Omega )^2\right)}$$
Now provide the response and nothing else.
| expr = -I/(2 π (-I g + V0 + G)) z = ComplexExpand @ expr w = Together /@ z num = Numerator /@ wdem = Denominator /@ w[[1]] // Simplifynum/dem Wrap it up in a function: complex[expr_] := Block[{w, num, dem}, w = Together /@ ComplexExpand @ expr; num = Numerator /@ w; dem = Simplify @ Denominator /@ w[[1]]; num/dem ] and e.g. complex[(a + b I)/(c + d I)] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/128298', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/39223/']} | jdg_74838 |
stackexchange | llm_judgeable_groundtruth_similarity | 42301123 |
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 figure out how the service worker works in regards to cache headers in responses. I have implemented a couple of service workers now but have never had to bother worrying about caching headers, how long items should be cached for etc. I'm now implementing it on an enterprise production site, whereby this stuff actually really matters. Basically when using a service worker, is the http cache completely bypassed? Do I then need to build a framework to handle resource expiration/invalidation like the http cache used to do for us? Or am I talking rubbish? Would be super helpful if someone could provide some clarification of this. The way I see it there are 3 potential scenarios: A). Network request => Service worker fetch => (Browser cache?) <=> Server B). Network request <=> (Browser cache?) <=> Service worker fetch <=> Server C). Network request => Service worker fetch <=> Server I've tested this locally and it seems that C). is the correct implementation, whereby we the developer have sacrificed cache header/duration abstraction for control. I'm fine with this, just want it clarifying before I run off and build a framework for reading and honouring caching headers in the service worker.
Now provide the response and nothing else.
| A) is the correct model. If a service worker controls a page, all network requests will trigger the fetch event handler of the service worker prior to consulting the browser cache or the network. In turn, any time the service worker makes a network request, either explicitly via fetch() or implicitly via cache.add() / cache.addAll() , the browser's "traditional" cache is consulted for a response first. A network request to the server will only be made if there isn't a valid response in the browser cache. This sometimes works in your favor, and sometimes can expose you to subtle bugs if you don't expect that behavior. There's a very detailed explanation of this interaction at https://jakearchibald.com/2016/caching-best-practices/ , specifically covering things to avoid and ways to take advantage of this behavior . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42301123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3625467/']} | jdg_74839 |
stackexchange | llm_judgeable_groundtruth_similarity | 4254334 |
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 developing web service under JBoss 5 and Java 1.6. What could possibly cause this exception? Below is my simplified web service code. @Stateless@WebService()public class AccountWS {@WebMethod()public CreateAccountResponse createAccount(@WebParam(name = "request") CreateAccountRequest request) { return null;} And below is the full stack trace. 16:19:03,421 ERROR [AbstractKernelController] Error installing to Real: name=vfsfile:/C:/Apps/jbdevstudio/jboss-eap/jboss-as/server/default/deploy/sif_esb.esb/ state=PreReal mode=Manual requiredState=Realorg.jboss.deployers.spi.DeploymentException: Error during deploy: vfsfile:/C:/Apps/jbdevstudio/jboss-eap/jboss-as/server/default/deploy/sif_esb.esb/at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49)at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:177)at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1440)at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1158)at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1099)at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1633)at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:935)at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1083)at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:985)at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:823)at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:782)at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)at org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)at org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)at org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:403)at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1633)at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:935)at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1083)at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:985)at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:775)at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:540)at org.jboss.system.server.profileservice.repository.AbstractProfileService.registerProfile(AbstractProfileService.java:308)at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:256)at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)at org.jboss.Main.boot(Main.java:221)at org.jboss.Main$1.run(Main.java:556)at java.lang.Thread.run(Unknown Source)Caused by: java.lang.IllegalStateException: Cannot build JAXB contextat org.jboss.ws.metadata.builder.jaxws.JAXWSMetaDataBuilder.createJAXBContext(JAXWSMetaDataBuilder.java:984)at org.jboss.ws.metadata.builder.jaxws.JAXWSWebServiceMetaDataBuilder.buildWebServiceMetaData(JAXWSWebServiceMetaDataBuilder.java:151)at org.jboss.ws.metadata.builder.jaxws.JAXWSServerMetaDataBuilder.setupProviderOrWebService(JAXWSServerMetaDataBuilder.java:50)at org.jboss.ws.metadata.builder.jaxws.JAXWSMetaDataBuilderEJB3.buildMetaData(JAXWSMetaDataBuilderEJB3.java:76)at org.jboss.wsf.stack.jbws.UnifiedMetaDataDeploymentAspect.start(UnifiedMetaDataDeploymentAspect.java:69)at org.jboss.wsf.framework.deployment.DeploymentAspectManagerImpl.deploy(DeploymentAspectManagerImpl.java:129)at org.jboss.wsf.container.jboss50.deployer.ArchiveDeployerHook.deploy(ArchiveDeployerHook.java:76)at org.jboss.wsf.container.jboss50.deployer.AbstractWebServiceDeployer.internalDeploy(AbstractWebServiceDeployer.java:60)at org.jboss.wsf.container.jboss50.deployer.WebServiceDeployerEJB.internalDeploy(WebServiceDeployerEJB.java:113)at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)... 29 moreCaused by: org.jboss.ws.WSException: Failed to create JAXBContextat org.jboss.ws.core.jaxws.CustomizableJAXBContextFactory.createContext(CustomizableJAXBContextFactory.java:114)at org.jboss.ws.metadata.builder.jaxws.JAXWSMetaDataBuilder.createJAXBContext(JAXWSMetaDataBuilder.java:980)... 39 moreCaused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptionsTwo classes have the same XML type name "{http://kona.webservice.sif.unidata.com/}createAccountResponse". Use @XmlType.name and @XmlType.namespace to assign different names to them.this problem is related to the following location: at com.unidata.sif.kona.account.message.CreateAccountResponse at private com.unidata.sif.kona.account.message.CreateAccountResponse com.unidata.sif.webservice.kona.jaxws.CreateAccountResponse._return at com.unidata.sif.webservice.kona.jaxws.CreateAccountResponsethis problem is related to the following location: at com.unidata.sif.webservice.kona.jaxws.CreateAccountResponseat com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:102)at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:448)at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:297)at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:139)at com.sun.xml.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:105)at org.jboss.ws.core.jaxws.CustomizableJAXBContextFactory.createContext(CustomizableJAXBContextFactory.java:108)... 40 more
Now provide the response and nothing else.
| I found the cause of my problem. This problem occurs because JAX-WS generates a class for each method and the class name is constructed by concatenating methodName + "Response" . In my case, the newly generated class by JAX-WS will have the same name as my response object . Example: @Stateless@WebService()public class AccountWS { @WebMethod() public CreateAccountResponse createAccount(@WebParam(name = "request") CreateAccountRequest request) { return null; }} JAX-WS will generate a new class CreateAccountResponse for Web Method createAccount which has the same name as the response object. Solution: Make sure that the name of the response object and method doesn't match . The same thing applies to the method parameter as well. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4254334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193634/']} | jdg_74840 |
Subsets and Splits