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 | 20362 |
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:
Hyperconjugation stabilizes carbocations and that makes sense because electrons are given to the empty p orbital. But how does it stabilize alkenes? Can molecular orbital theory be used to explain it?
Now provide the response and nothing else.
| Since you are familiar with how carbocations are stabilized via hyperconjugation I will keep this brief: With alkenes, it really is the same principle at work. Instead of the empty p orbital, you have to consider the empty $\pi^{*}$ orbitals of the $\ce{C=C}$ double bond. They interact with the filled high-lying neighboring $\ce{C-H}$ or $\ce{C-C}$ $\ce{\sigma}$ bonds in $\pi$-bond-like manner and so from those two fragment orbitals you will get two molecular orbitals: one from the in-phase combination of $\pi^{*} (\ce{C=C})$ with $\sigma (\ce{C-X})$, which will be lower in energy then the fragment orbitals, and one from the out-of-phase combination of $\pi^{*} (\ce{C=C})$ with $\sigma (\ce{C-X})$, which will be higher in energy then the fragment orbitals. Since in this interaction there are only two electrons involved, i.e. the ones in $\sigma (\ce{C-X})$, you get a stabilization from the interaction since those two electrons will now occupy the in-phase MO and have thus lowered their energy. The out-of-phase MO is empty and doesn't contribute to the energy of the molecule. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/20362', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2108/']} | jdg_379841 |
stackexchange | llm_judgeable_groundtruth_similarity | 1172459 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I think I can motivate the definitions of simplicial, singular, de Rham, Čech, and sheaf (co)homology, more or less. I might want to understand bordism, and start by trying to understand submanifolds, then realize that this is really hard to do and try instead to handle a combinatorial approximation. Then I might define simplicial homology. After dealing with simplicial homology for a few decades, I might tire of my confinement to the simplicial setting, but might nonetheless want to reason combinatorially about simplices, and I might then define the singular simplices functor and worry about singular homology. Motivated by Stokes's theorem and Poincaré duality, I might have the idea that Grassmann's differential forms could be considered as dual to smooth submanifolds in some sense, and I might define de Rham cohomology on manifolds. Once I knew about the Mayer–Vietoris sequence and had started to get a feeling for of local–global relations in (co)homology theories, and in particular knew Poincaré's lemma, I might decide it was a good idea to try and understand (co)homology in terms of the combinatorics of a cover of contractible open sets, and I might eventually just define cohomology as the direct limit of a set of algebraic structures derived from covers. This would also have benefit of smoothing out irregularities in my object space. Thinking about the properties of the de Rham complex in terms of supports of differential forms and still keeping the Poincaré lemma in mind, I might also define fine sheaves and ultimately cohomology with coefficients in a sheaf, if, for example, I were exceptionally creative and trying very hard not to look like an analyst while imprisoned by the Nazis in a POW camp. On the other hand, I've looked at Dieudonné's history and the original papers of Alexander and Spanier, but I still have no real idea what would inspire me to define Alexander–Spanier cohomology . Does anyone have any insight? P.S. [7 Dec.]: Massey has an account in his essay "A history of cohomology theory" in the collection History of Topology (ed. Ioan James). On p. 567, he states It is not difficult to see why Whitney and the other participants at the Moscow conference must have been mystified when Kolmogoroff and Alexander wrote down their definitions of a product of cochains. These definitions were pure ad hoc formulas, presented with no motivation. It is hard to guess how Alexander and Kolmogoroff arrived at them. It must have seemed like numerology or magic. I've learned from Massey's account that Alexander(–Kolmogorov!)–Spanier cohomology was likely intended to be dual to Vietoris homology but not exactly how this duality functioned. Vietoris homology was initially defined, as I understand, on compact metric spaces, with simplices ordered sets of points within an $\epsilon$-neighborhood, and $\epsilon$ taken to zero, with cycles being sequences of cycles modulo eventual boundaries. While this approach to zero is reminiscent of modding out functions vanishing on a neighborhood of the diagonal, I still do not know their motivation for doing so.
Now provide the response and nothing else.
| I'm not an expert, the following is all just guesswork -- I similarly found the original papers unenlightening wrt their motivation. As you said, the mystery mainly lies in the motivation of the additional step: modding out the functions from $X^{k+1} \to R$ by the subcomplex of functions which disappear on the neighborhood of the diagonal. First, let's justify looking at neighborhoods of a space. We know from Alexander duality the philosophy of looking at tautness of a subspace $U$ with respect to a space $Y$. We look at neighborhood $N$ of $U$ in Y (by neighborhood, we mean a subset $N$ of $Y$ that contains $U$ in its interior). The intersection of two neighborhoods of $U$ in $Y$ will be another neighborhood of $U$ in $Y$, so this gives us a system of groups $\{H^q(N)\}$ where $N$ ranges over all neighborhoods of $U$ in $Y$. For each $N$, this gives us an inclusion $U \in N$, which induces a homomorphism $H^q(N) \to H^q(U)$. The subspace $U$ is said to be "tautly embedded" in $Y$ if this is an isomorphism for all $q$, all $N$, and all coefficient groups. Being taut implies that $U$ is compact and $Y$ is Hausdorff. This gives us a hint: we are probably modding out by this subcomplex in order to deal with NON compact Hausdorff spaces . Second, let's justify looking at the diagonal. The diagonal embedding $X \xrightarrow{\Delta} X \times X$, is simply a canonical way to embed a space X into an ambient space endowed with the product topology, $\Delta X := \{(x,x) \in X \times X\}$. It is useful when want to look in the neighborhood of a space $X$ (e.g., at germs of functions on $X$), but $X$ sits in no ambient space. The word, "diagonal embedding," comes from the example of embedding of $R^1 \hookrightarrow R^2$ taking $x \mapsto (x,x)$, that is, taking the line $R^1$ and embedding it into $R^2$ as the line $y=x$. With this in mind, let's return our gaze to Alexander-Spanier cochains. Here's my naive guess: modding out functions which disappear on any neighborhood of $X$, $N(X)$, artifically forces $X$ to satisfy the condition that $$H^q(\text{functions which disappear on }N(X)) \simeq H^q(\text{functions which disappear on }X)$$ for all $N$, all $q$, and all coefficient groups. Perhaps modding out by the subcomplex lets us "falsely" satisfy that $X$ is tautly embedded in $X \times X$, so that we may treat $X$ as if it were a compact space. Below are a few additional comments toward why someone might have thought of modding out by that particular subcomplex. Establishing notation: $X^{p+1}$ is the (p+1)-fold product of X with itself, that is, for $x_i \in X$, $(x_1, ..., x_{p+1}) \in X^{p+1}$. $f^p(X) := \{$ functions $X^{p+1} \to \mathbb{Z} \}$, with functional addition as the group operation. $f^p_0(X) :=$ elements of $f^p(X)$ which are zero in the neighborhood of the diagonal $\Delta X^{p+1}$ If we are examining functions defined pointwise on $X$, it’s natural to look at $X$-embedded in an ambient space, rather than the space $X$ itself. That is, $N(X)$ is the natural home of the jet bundle of $X$. Functions which disappear on $N(X)$ form a group. If $f$ and $f’$ are both zero on $N(X)$ then $f-f’$ is zero on $N(X)$. I'm not sure if the following is useful, nor how it fits into the story, but I figured I'd mention it. The natural home of jet bundles (over a space $X$) is over the diagonal of X. From reading this paper , it seems that Grothendieck brought to the fore the kth neighborhood of the diagonal of a manifold $X$ when he was porting notions of differential geometry into algebraic geometry (this was then ported back into differential geometry by Spencer, Kumpera, and Malgrange). We'll use the standard notation $\Delta X \subseteq X_{(k)} \subseteq X \times X$. The only points of $X_{(k)}$ are the diagonal points $(x, x)$, but, we equip our space $X_{(k)}$ with a structure sheaf of functions, and treat $X_{(k)}$ as if it is made of "k-neighbor points" (x,y) where x and y are the closest points to one another, what Weil called "points proches"). To picture $X_{(1)}$, we might imagine $X$ with an infinitesimal normal bundle, for $X_{(2)}$, an infinitesimal bundle that’s ever so slightly larger of the second derivatives (as we need more local information to take the 2nd derivative), and so on. If we think of a function $\omega: X_{(k)} \to R$ which vanishes on $X \subseteq X_{(k)}$ as a “differential k-form,” then maybe: the functions which vanish to the first order can be thought of as closed forms , $d\omega = 0$, the functions which vanish to the second order on the diagonal $X \subseteq X_{(k+1)}$ can be thought of as exact forms for they satisfy $\omega = d\beta$, s.t. $d(\omega) = d(d\beta) = 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1172459', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7112/']} | jdg_379842 |
stackexchange | llm_judgeable_groundtruth_similarity | 46409626 |
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 trouble using the accuracy function from tf.metrics for a multiple classification problem with logits as input. My model output looks like: logits = [[0.1, 0.5, 0.4], [0.8, 0.1, 0.1], [0.6, 0.3, 0.2]] And my labels are one hot encoded vectors: labels = [[0, 1, 0], [1, 0, 0], [0, 0, 1]] When I try to do something like tf.metrics.accuracy(labels, logits) it never gives the correct result. I am obviously doing something wrong but I can't figure what it is.
Now provide the response and nothing else.
| TL;DR The accuracy function tf.metrics.accuracy calculates how often predictions matches labels based on two local variables it creates: total and count , that are used to compute the frequency with which logits matches labels . acc, acc_op = tf.metrics.accuracy(labels=tf.argmax(labels, 1), predictions=tf.argmax(logits,1))print(sess.run([acc, acc_op]))print(sess.run([acc]))# Output#[0.0, 0.66666669]#[0.66666669] acc (accuracy): simply returns the metrics using total and count , doesnt update the metrics. acc_op (update up): updates the metrics. To understand why the acc returns 0.0 , go through the details below. Details using a simple example: logits = tf.placeholder(tf.int64, [2,3])labels = tf.Variable([[0, 1, 0], [1, 0, 1]])acc, acc_op = tf.metrics.accuracy(labels=tf.argmax(labels, 1), predictions=tf.argmax(logits,1)) Initialize the variables: Since metrics.accuracy creates two local variables total and count , we need to call local_variables_initializer() to initialize them. sess = tf.Session()sess.run(tf.local_variables_initializer())sess.run(tf.global_variables_initializer())stream_vars = [i for i in tf.local_variables()]print(stream_vars)#[<tf.Variable 'accuracy/total:0' shape=() dtype=float32_ref>,# <tf.Variable 'accuracy/count:0' shape=() dtype=float32_ref>] Understanding update ops and accuracy calculation: print('acc:',sess.run(acc, {logits:[[0,1,0],[1,0,1]]}))#acc: 0.0print('[total, count]:',sess.run(stream_vars)) #[total, count]: [0.0, 0.0] The above returns 0.0 for accuracy as total and count are zeros, inspite of giving matching inputs. print('ops:', sess.run(acc_op, {logits:[[0,1,0],[1,0,1]]})) #ops: 1.0print('[total, count]:',sess.run(stream_vars)) #[total, count]: [2.0, 2.0] With the new inputs, the accuracy is calculated when the update op is called. Note: since all the logits and labels match, we get accuracy of 1.0 and the local variables total and count actually give total correctly predicted and the total comparisons made . Now we call accuracy with the new inputs (not the update ops): print('acc:', sess.run(acc,{logits:[[1,0,0],[0,1,0]]}))#acc: 1.0 Accuracy call doesnt update the metrics with the new inputs, it just returns the value using the two local variables. Note: the logits and labels dont match in this case. Now calling update ops again: print('op:',sess.run(acc_op,{logits:[[0,1,0],[0,1,0]]}))#op: 0.75 print('[total, count]:',sess.run(stream_vars)) #[total, count]: [3.0, 4.0] The metrics are updated to new inputs For more information on how to use the metrics during training and how to reset them during validation, can be found here . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46409626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5236675/']} | jdg_379843 |
stackexchange | llm_judgeable_groundtruth_similarity | 8001450 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way in C# to wait till the user finished typing in a textbox before taking in values they have typed without hitting enter? Revised this question a little: Okay I have a simple calculator that multiplies by 2. Here is what I want it to do: The user inputs a value like 1000 into a textbox and it automatically displays 2000. Here is what happens: As soon as the user enters in 1 its multiplies by 2 and outputs 2.
Now provide the response and nothing else.
| I define "finished typing" now as "user has typed something but has not typed anything after a certain time". Having that as a definition i wrote a little class that derives from TextBox to extend it by a DelayedTextChanged event. I do not ensure that is complete and bug free but it satisfied a small smoke test. Feel free to change and/or use it. I called it MyTextBox cause i could not come up with a better name right now. You may use the DelayedTextChangedTimeout property to change the wait timeout. Default is 10000ms (= 10 seconds). public class MyTextBox : TextBox{ private Timer m_delayedTextChangedTimer; public event EventHandler DelayedTextChanged; public MyTextBox() : base() { this.DelayedTextChangedTimeout = 10 * 1000; // 10 seconds } protected override void Dispose(bool disposing) { if (m_delayedTextChangedTimer != null) { m_delayedTextChangedTimer.Stop(); if (disposing) m_delayedTextChangedTimer.Dispose(); } base.Dispose(disposing); } public int DelayedTextChangedTimeout { get; set; } protected virtual void OnDelayedTextChanged(EventArgs e) { if (this.DelayedTextChanged != null) this.DelayedTextChanged(this, e); } protected override void OnTextChanged(EventArgs e) { this.InitializeDelayedTextChangedEvent(); base.OnTextChanged(e); } private void InitializeDelayedTextChangedEvent() { if (m_delayedTextChangedTimer != null) m_delayedTextChangedTimer.Stop(); if (m_delayedTextChangedTimer == null || m_delayedTextChangedTimer.Interval != this.DelayedTextChangedTimeout) { m_delayedTextChangedTimer = new Timer(); m_delayedTextChangedTimer.Tick += new EventHandler(HandleDelayedTextChangedTimerTick); m_delayedTextChangedTimer.Interval = this.DelayedTextChangedTimeout; } m_delayedTextChangedTimer.Start(); } private void HandleDelayedTextChangedTimerTick(object sender, EventArgs e) { Timer timer = sender as Timer; timer.Stop(); this.OnDelayedTextChanged(EventArgs.Empty); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8001450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/990951/']} | jdg_379844 |
stackexchange | llm_judgeable_groundtruth_similarity | 268830 |
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 integral $$\int \frac{\sqrt{9 - x^2}}{x^2}dx$$ is solved in my book by letting $x = 3\sin\theta$ where $-\frac {\pi}{2} \le \theta \le \frac {\pi}{2}$. Then, $dx = 3\cos\theta\,d\theta$ and, $$\sqrt{9-x^2} = 3|\cos\theta| = 3\cos\theta$$ So, $$\int \frac{\sqrt{9 - x^2}}{x^2}dx = \int \cot^2 \theta \ d\theta = -\cot\theta - \theta + C$$ Returning to the original variable, $$\int \frac{\sqrt{9 - x^2}}{x^2}dx = -\frac {\sqrt{9 - x^2}}{x} - \sin^{-1}\left(\frac{x}{3}\right) + C$$ I don't understand why $\sqrt{9-x^2} = 3|\cos\theta| = 3\cos\theta \,$ instead of $\sqrt{9-x^2} = |3||\cos\theta| = |3|\cos\theta$. I feel like I have problems understanding this because I am not sure what is the purpose of the absolute value signs in this case, are they to indicate that, for example, $|\cos\theta| = \pm\cos\theta$? If that's the case, why do we choose $3$ to be positive instead of negative?
Now provide the response and nothing else.
| Think about it: How would using $\;|\,3\,|\;$ change the result?$\quad$ After all, $\;|\,3\,| \;= \quad?$ Also note: $\,|\cos\theta| \,= \,\cos\theta \,\ge \,0\;$ since the range of $\,\theta\,$ is $\;\;-\dfrac{\pi}{2} \,\le\, \theta \,\le \dfrac{\pi}{2}$. You seem to be confused about the what "$|\;\cdot\;|$" means. $\;| \,a \,|$ is not the same as $\,\pm a\,$. Rather, we define $|\, a \,| = -a\,$ if $\,a \lt 0$. $|\, a\, | = \;\,\;a\,$ if $\,a \geq 0$. This ALWAYS returns a non-negative result. By definition, $\,\sqrt{\;\;}\,\;$ returns only the non-negative root of a square or quadratic. So $\,\sqrt{a^2}=|a|,\,$ while solving for, say, $\,x^2-a = 0\,$ we obtain two roots : $\,x\, =\,\pm \sqrt{a}\,$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/268830', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54821/']} | jdg_379845 |
stackexchange | llm_judgeable_groundtruth_similarity | 67910 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Regarding the SHA 1 deprecation, I found this information here: http://blogs.technet.com/b/srd/archive/2013/11/12/security-advisory-2880823-recommendation-to-discontinue-use-of-sha-1.aspx I know that the 2^77 and 2^61 deal with time complexities, but are these specific attacks against the full 80 rounds of SHA1 or do they mean SHA1 was broken with fewer rounds using those time complexities?
Now provide the response and nothing else.
| What the page you link to means is that there are known attacks which, when implemented, would allow building collisions with some costs: If the goal is "raw collisions" then the computational effort is equivalent to running 2 61 times the SHA-1 function. A raw collision is such that the attack produces two messages m and m' which are distinct but hash to the same value. In fact, due to the nature of the attack, the attacker can choose a common prefix , i.e. m and m' begin with the same sequence of bytes that the attacker gets to choose; then come some bytes that he must accept "as is". If the attacker wants messages m and m' begin with two distinct sequences and choose both those prefixes (that's chosen prefixes ), then the cost is higher, up to an average cost of 2 77.1 . Since SHA-1 has output size 160 bits, both kinds of collisions can be done generically with effort about 2 80 : a "generic" attack is one that works against all hash functions, however perfect they may be. To describe things simply: the attacker chooses his prefixes p and p' , then generates random values r and r' , computing h(p||r) and h(p'||r') . Once the attacker has accumulated about 2 80 values h(p||r) , and 2 80 values h(p'||r') , then probability of a collision (one hash value appearing in both sets) begins to be non-negligible. Important notes: These attacks are theoretical : 2 61 is still quite a lot, and the attack has not been run yet. The description is sound, and our experience with MD5 tells us that it most probably works as advertised; but, until it has been executed, we don't really know. To get the gist of what 2 61 represents, suppose (with very high optimism) that implementing the attack can be done efficiently on common GPU, with optimal parallelism (there are reasons to believe that it is not necessarily the case). Then we can use existing benchmarks to try to see what it would take to run the attack once . An AMD R9 290X can apparently run about 3.7 billions of SHA-1 par second; thus, a 2 61 effort translates to 20 years on a single such GPU. You can trim that down to one month if you buy and run 240 such GPU, one day if you have 7200 GPU. Power consumption alone will be in the megawatt range... this gotta be expensive. To actually exploit the attack, to produce (for instance) a pair of colliding certificates (allowing to reuse the signature from the first certificate on the second), you need the chosen prefix attack; raw collisions don't cut it. This multiplies the computation effort by 2 16.1 (the ratio between 2 77.1 and 2 61 ), which is about 70000. With your GPU, assuming you get them all in line, then you will need your own nuclear power plant, and still be patient... To be fair, we must also point out that the chosen prefix attack can result in rogue certificates only if the CA uses fully deterministic and predictable certificate contents -- in particular, a deterministic serial number . Some CA software does not have this specific issue; e.g. Microsoft's CA (ADCS) embeds about 30 bits of randomness in the serial number, which prevents application of the collision attacks (even with MD5). The chosen prefix attack counts as an actual break, from an academic point of view, because 2 77.1 is lower than 2 80 ... but not much lower (only about 7 times lower). Although comparing numbers that high is perfectly valid in cryptography, it can be predicted that actually applying the attack will raise a non-negligible number of issues. When we are talking about efforts in the 2 30 or 2 40 range, things are easy: costs are mostly about buying a couple of big PC. In the 2 60 or more, the problem becomes one of thermodynamics (flowing energy in, evacuating heat) and economics, and we can no longer scale results with reliable accuracy. Bottom-line: though the attacks which are talked about are "real" (academically speaking) and apply to the full SHA-1 (with all its internal rounds), they are still in the "theoretical only" range, and mapping their alleged costs to actual dollars is complex because they are in a range where non-cryptographic issues tend to dominate. The gist of the advisory you show is this sentence: It appears that SHA-1 is on a similar trajectory That sentence is full of unsubstantiated insinuations, and must not be considered as more accurate than, say, astrology. Astrology works at least as well are pure luck, so it cannot be completely dismissed; but we must still note that the idea of attacks becoming faster over time is of an essence which is qualitatively distinct of, say, Moore's law . The steady pace of computing power available for a given price has been sustained by a number of ideas which were already known in the 1970s, and we are still not at the end of it. There are "physical walls" that will become bothersome in the future (quantum tunnelling of electrons between wires...) be we also know that we still have a few years before us; CPU in three years will be faster and cheaper, and we know how we will build them. Advances on cryptographic attacks are not of the same kind. Predicting that attacks will get better means that we assume that better attacks exist, and that the relevant ideas will sprout in the right brains. This cannot be quantified with any kind of reliability. Maybe in ten years we will still be at 2 61 (and 2 77.1 ). Maybe we will be at 2 30 (i.e. sub-second break). We really don't know. This does not mean that SHA-1 should not be avoided. In fact you already should not use it in new systems, and strive to implement support for SHA-256 anywhere. But you should not panic . The MD5 example shows us that we, actually, have time: it took 5 years between actual MD5 collisions, and the first (and only) demonstration of colliding certificates. The current fashion of placing an anathema on SHA-1 should be understood politically, not cryptographically. The situation on SHA-1 has not substantially changed in the last four years. What happens right now is that Microsoft and Google have apparently agreed to force widespread SHA-256 support, and they do so by the usual expedient of empire builders: threats. They kick the anthill. They brandish the apocalyptic removal of SHA-1 so that the rest of the World finally sets in motion and begins to actually support SHA-256. (My guess is that Microsoft, at least, will backpedal. For instance, consider that right now, the .NET framework is still based on CrytoAPI, not CNG, and appears to be incapable of computing CMS or XML-DSig signatures with SHA-256 as base hash function.) | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/67910', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/53029/']} | jdg_379846 |
stackexchange | llm_judgeable_groundtruth_similarity | 28285813 |
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 implemented a jQuery autocomplete function to a Bootstrap input. The jQuery autocomplete is working fine but I want to see the results as a combo and I guess it's now happening because I'm using BootStrap. This is the field that I'm assigning autocomplete: <div class="form-group"> <label>Employee</label> <input class="form-control" name="txtEmployee" placeholder="Trabajador"></div> $(this).autocomplete({ source: function(request, response) { $.ajax({ url: '@Url.Content("~/Employee/SearchEmployee")/', type: 'POST', contentType: 'application/json', dataType: "json", data: JSON.stringify({ employerId: 1, searchStr: me.val() }), success: function(data) { if (data.success) { response($.map(data.data, function(item) { return { label: "(" + item.EmployeeNumber + ") " + item.FirstName + " " + item.MothersLast + ", " + item.FathersLast, employeeId: item.EmployeeId } })); } } }); }, minLength: 3}); The results are displayed but like this: How can I style the results with Bootstrap so I can see them like dropdownlist?
Now provide the response and nothing else.
| If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled. If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied. Here's an example and some possible fixes. Minimal, Complete, and Verifiable example (i.e. broken) Here's a demo in Stack Snippets without jquery-ui.css (doesn't work) $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group"> <label >Another Field</label> <input class="form-control"> </div></div> Fix #1 - jQuery-UI Style Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery. $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); <link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group"> <label >Another Field</label> <input class="form-control"> </div></div> Fix #2 - Bootstrap Theme There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery‑ui‑bootstrap . Just grab the stylesheet from there and you should be all set. $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group"> <label >Another Field</label> <input class="form-control"> </div></div> Fix #3 - Manual CSS If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using. After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace. You can use bootstrap's dropdowns.less for inspiration. Here's a sample CSS that fits pretty well with Bootstrap's default theme: .ui-autocomplete { position: absolute; z-index: 1000; cursor: default; padding: 0; margin-top: 2px; list-style: none; background-color: #ffffff; border: 1px solid #ccc; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);}.ui-autocomplete > li { padding: 3px 20px;}.ui-autocomplete > li.ui-state-focus { background-color: #DDD;}.ui-helper-hidden-accessible { display: none;} $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); .ui-autocomplete { position: absolute; z-index: 1000; cursor: default; padding: 0; margin-top: 2px; list-style: none; background-color: #ffffff; border: 1px solid #ccc -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);}.ui-autocomplete > li { padding: 3px 20px;}.ui-autocomplete > li.ui-state-focus { background-color: #DDD;}.ui-helper-hidden-accessible { display: none;} <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group ui-widget"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group ui-widget"> <label >Another Field</label> <input class="form-control" /> </div></div> Tip : Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with .ui-autocomplete and remove display: none; . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28285813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1253667/']} | jdg_379847 |
stackexchange | llm_judgeable_groundtruth_similarity | 19822561 |
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 new to Java and neither me nor my partner can seem to figure out how to set the background for a specific section. We need to have the background for the Jamaican flag set to (250, 230, 82) but only for that part. Currently, when we run the program on Processing 2.0, the line messes the entire flow of what we've written. This is what we have so far: int x=0;void setup() { size(320, 270); background(0); noStroke(); frameRate(240);}void draw() { //germany, flag 1 fill(0); //black first horizontal bar rect(0+x, 0, width+x, width); fill(255, 0, 0); //red middle horizontal bar rect(0+x, 90, width+x, width); fill(240, 240, 0); //gold last horizontal bar rect(0+x, 180, width+x, width); //japan, flag 2 fill(255); //white background rect(0+x-width, 0, width, height); fill(255, 0, 0); //red circle middle ellipse(width/2+x-width, height/2, 150, 150); //france, flag 3 fill(0, 0, 255); //left blue vertical bar rect(0+x-2*width, 0, width/3, height); fill(255); //middle white vertical bar rect(width/3+x-2*width, 0, width/3, height); fill(255, 0, 0); //right red vertical bar rect(2.0/3.0*width+x-2*width, 0, width/3, height); //brazil, flag 4 fill(0, 180, 0); //dark green background rect(0+x-3*width, 0, width, height); fill(230, 230, 0); //gold rhombus triangle(width/10+x-3*width, height/2, width/2+x-3*width, 30, width/2+x-3*width, 240); //gold rhombus left side triangle(9.0/10.0*width+x-3*width, height/2, width/2+x-3*width, 30, width/2+x-3*width, 240); //gold rhombus right side fill(0, 0, 150); //dark blue circle ellipse(width/2+x-3*width, height/2, 120, 120); fill(255); //stars ellipse(170+x-3*width, 170, 3, 3); //stars 1 ellipse(177+x-3*width, 185, 3, 3); //stars 2 ellipse(151+x-3*width, 155, 3, 3); //stars 3 ellipse(112+x-3*width, 145, 3, 3); //stars 4 ellipse(132+x-3*width, 165, 3, 3); //stars 5 ellipse(147+x-3*width, 148, 3, 3); //stars 6 ellipse(157+x-3*width, 168, 3, 3); //stars 7 ellipse(180+x-3*width, 188, 3, 3); //stars 8 ellipse(190+x-3*width, 158, 3, 3); //stars 9 //sweden, flag 5 fill(0, 100, 190); //blueish teal background rect(0+x-4*width, 0, width, height); //the "-4*width" needs to be added after every fill(240, 210, 0); // gold nordic cross //^first x-place in order for the flags to follow one after rect(width/4+x-4*width, 0, 30, height); //another like a big continuous flag, so the subsequent rect(0+x-4*width, height/2-15, width, 30); //ones will be "-5*width", "-6*width", etc //the "-15"^ is to center the horizontal line //norsefire, flag 6 fill(0); //black background rect(0+x-5*width, 0, width, height); fill(255, 0, 0); //red double cross thing rect(0+x-5*width, height/2-15, width, 30);//horizontal line rect(width/8+x-5*width, 0, 30, height);//vertical line 1 rect(3.0/8.0*width+x-5*width, 0, 30, height);//vertical line 2 //chile, flag 7 fill(0, 0, 250); //blue left horizontal bar rect(0+x-6*width, 0, 125, 145); fill(250); //white right horizontal bar rect(125+x-6*width, 0, 320, 145); fill(250, 0, 0); //red last horizontal bar rect(0+x-6*width, 145, 320, 270); line(42+x-6*width, 53, 63, 30); line(82+x-6*width, 53, 63, 30); line(82+x-6*width, 53, 105, 58); line(15+x-6*width, 58, 42, 53); line(90+x-6*width, 75, 105, 58); line(35+x-6*width, 75, 15, 58); line(35+x-6*width, 75, 25, 95); line(25+x-6*width, 95, 53, 88); line(53+x-6*width, 88, 95, 95); line(95+x-6*width, 95, 90, 75); //jamaica, flag 8 // background(250, 230, 82); // This line is messing everything up fill (0, 250, 0); //green triangle top triangle (10+x-7*width, 0, 160+x-7*width, 120, 310+x-7*width, 0); fill (0, 250, 0); //green triangle bot triangle (10+x-7*width, 270, 160+x-7*width, 150, 310+x-7*width, 270); fill (0); //black triangle left triangle (0+x-7*width, 10, 145+x-7*width, 135, 0+x-7*width, 260); fill (0); //black triangle right triangle (320+x-7*width, 10, 175+x-7*width, 135, 320+x-7*width, 260); //puerto rico, flag 9 fill(0, 0, 250); //blue triangle triangle(0+x-8*width, 0, 0+x-8*width, 270, 166+x-8*width, 135); fill(255, 0, 0); //red quad 1 quad(0+x-8*width, 0, 54+x-8*width, 54, 320+x-8*width, 54, 320+x-8*width, 0); fill(250); //white quad 1 quad(54+x-8*width, 54, 108+x-8*width, 108, 320+x-8*width, 108, 320+x-8*width, 54); fill(255, 0, 0); //red quad 2 quad(108+x-8*width, 108, 135+x-8*width, 135, 320+x-8*width, 135, 320+x-8*width, 108); fill(255, 0, 0); //red quad 3 quad(135+x-8*width, 135, 108+x-8*width, 162, 320+x-8*width, 162, 320+x-8*width, 135); fill(250); //white quad 2 quad(108+x-8*width, 162, 320+x-8*width, 162, 320+x-8*width, 216, 54+x-8*width, 216); fill(250, 0, 0); //red quad 4 quad(54+x-8*width, 216, 0+x-8*width, 270, 320+x-8*width, 270, 320+x-8*width, 216); //Kuwait flag, 10 fill(80, 168, 62); //green quad quad(0+x-9*width, 0, 80+x-9*width, 90, 320+x-9*width, 90, 320+x-9*width, 0); fill(250); //white quad quad(80+x-9*width, 90, 80+x-9*width, 180, 320+x-9*width, 180, 320+x-9*width, 90); fill(250, 0, 0); //red quad quad(80+x-9*width, 180, 0+x-9*width, 270, 320+x-9*width, 270, 320+x-9*width, 180); fill(0); //black quad quad(0+x-9*width, 0, 0+x-9*width, 270, 80+x-9*width, 180, 80+x-9*width, 90); x=x+1; //scrolls flags to right if (x==9*width) { //resets flag scrolling, the number multiplied x=0; //to the width is how many flag widths the first flag has moved } // so the end result will be 9 widths bc we have 10 flags}
Now provide the response and nothing else.
| How to change max_connections You can change max_connections while MySQL is running via SET : mysql> SET GLOBAL max_connections = 5000;Query OK, 0 rows affected (0.00 sec)mysql> SHOW VARIABLES LIKE "max_connections";+-----------------+-------+| Variable_name | Value |+-----------------+-------+| max_connections | 5000 |+-----------------+-------+1 row in set (0.00 sec) To OP timeout related I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21. I suggest that you increase this value to 100k or disable connection pooling Pooling=false UPDATED he has two questions. Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool Q2 - Can the value of pooling be increased or the maximum is 100? you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error. If you have Stress Test tool like JMeter you can test youself. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19822561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2962235/']} | jdg_379848 |
stackexchange | llm_judgeable_groundtruth_similarity | 8575418 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Simple question from a simple-minded:What are the differences between the Shadows keyword in VB.NET and the New keyword in C#? (regarding method signatures of course).
Now provide the response and nothing else.
| They are not identical. The Shadowing concept does not exist in C # Consider a vb.net base class with some overloads: Public Class BaseClass Public Function SomeMethod() As String Return String.Empty End Function Public Function SomeMethod(SomeParam As String) As String Return "Base from String" End Function Public Function SomeMethod(SomeParam As Integer) As String Return "Base from Integer" End Function Public Function SomeMethod(SomeParamB As Boolean) As String Return "Base from Boolean" End FunctionEnd Class And this derived class: Public Class DerivedClass Inherits BaseClass Public Shadows Function SomeMethod(SomeParam As String) As String Return "Derived from String" End FunctionEnd Class Now consider the implementation: Dim DerivedInstance = New DerivedClass() DerivedInstance have just one version of SomeMethod, and all other base versions have been shadowed . if you compile and reference the assembly in a C# project you can see what happens: DerivedInstance shadows method To perform hiding in VB.Net, you still have to use the overloads (or overrides if base method is marked as overridable ) keyword: Public Class DerivedClass Inherits BaseClass Public Overloads Function SomeMethod(SomeParam As String) As String Return "Derived from String" End FunctionEnd Class And this is what happens after compiling: DerivedInstance hide method So, in VB.Net, if you use overloads keyword, on a signature that matches one on base class, you're hiding that base version of method, just like you would in c #: public class DerivedClass : BaseClass{ public new string SomeMethod(string someParam) { return "Derived from String"; }} Edit: This is the IL code: From C#: .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void Shadowing_CS.BaseClass::.ctor() IL_0006: ret}.method public hidebysig instance string SomeMethod ( string s ) cil managed { IL_0000: ldstr "Derived from string" IL_0005: ret} From VB: .method public specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void Shadowing_VB.BaseClass::.ctor() IL_0006: ret}.method public instance string SomeMethod ( string s ) cil managed { IL_0000: ldstr "Derived from string" IL_0005: ret} So.... they are not identical. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8575418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248534/']} | jdg_379849 |
stackexchange | llm_judgeable_groundtruth_similarity | 51220615 |
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 problem with the project I'm currently working on, so I'm leaving a question. The current contents are drawn in table format by sensor. But a few days ago, when I was working on something, I didn't know how to fix it, so I asked for help. import plotly.plotly as pyimport plotly.figure_factory as fffrom bluepy import sensortagimport sysimport timeimport datetimeimport numpy as nppy.sign_in("smrlswja9963","94b4enXKYqyOu4iuPDGG")time.sleep(1.0)tag = sensortag.SensorTag('24:71:89:CC:53:00')tag.IRtemperature.enable()tag.humidity.enable()stream1=py.Stream('liz9v2c0or')stream1.open()i=0 while True: now = datetime.datetime.now() dateTime = now.strftime("%Y-%m-%d %H:%M:%S") A = tag.IRtemperature.read() B = tag.humidity.read() tempt=A[0] humty=B[0] stream1.write({dateTime,tempt,humty}) i+=1 tag.waitForNotifications(3.0) table = go.Table( header=dict(values=["dateTime","tempt","humty"]), cells=dict(values=[[dateTime],[tempt],[humty]]), stream = dict(token='liz9v2c0or',))data=[table]py.iplot(table, filename="latex table") After executing the following code, the following error occurred. Traceback (most recent call last): File "/home/pi/do it.py", line 27, in <module> stream1.write({dateTime,tempt,humty}) File "/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.py", line 632, in write stream_object.update(trace)TypeError: cannot convert dictionary update sequence element #0 to a sequence In this case, the code that I draw the graph using plolty does not have a problem when receiving data from stream, but when I draw table plot. How can I graph here?I'm really curious. Please let me know.
Now provide the response and nothing else.
| This exception means that you're trying to construct a dict from an iterable, and that iterable's first element is not a sequence. As the docs explain, you can construct a dict two ways: From a mapping, or From an iterable of key-value pairs So, if you try to construct it from, say, a set of numbers: >>> dict({1, 2, 3})TypeError: cannot convert dictionary update sequence element #0 to a sequence … it's trying to use the first element as a key-value pair—that is, a sequence of 2 values—but there's no way to interpret the number 1 as a key-value pair, so it raises a TypeError . Meanwhile, I know absolutely nothing about Plotly streaming but what's on this page , but this code is clearly wrong: stream1.write({dateTime,tempt,humty}) I can't imagine why you'd want to stream a set. Plus, the examples all have either a dict, or a string that's a JSON-encoding of a dict. So, obviously, that API is expecting you to pass it either a dict or something you can feed to the dict constructor. But you're passing it a set. So, it feeds that set to the dict constructor, and gets this exception. Since I have no idea what you're actually trying to do here, I have no idea what dict you should be sending here. But you definitely should be passing a dict. Also, even if you fix this, based on the sign_in call, it looks like you're using Plotly Cloud. But, as the same page says: Streaming is no longer supported in Plotly Cloud. So, if you're trying to use streaming with Plotly Cloud, then, even if you fix your code to make sense, it's probably still going to fail, just with an error from Plotly rather than a TypeError about passing nonsense. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51220615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10045357/']} | jdg_379850 |
stackexchange | llm_judgeable_groundtruth_similarity | 4104077 |
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 $f(x)$ can be differentiated to any degree for $x\in (0,+\infty)$ and $f'(x)>0,f''(x)<0$ ,if $0<a<b$ ,acordding to mean value theorem we have $\displaystyle\exists \xi\in(a,b),st.\frac{f(b)-f(a)}{b-a}=f'(\xi)$ ,prove: $\displaystyle \xi<\frac{a+b}{2}$ And I think that's pretty obvious by looking at the graph of the function,but i don't know how to prove it in math words.
Now provide the response and nothing else.
| This is not true, here is a counterexample $$f(x)=\int_0^x(1-e^{-1/t})dt,f'(x)=1-e^{-1/x}>0,f''(x)=\frac{-e^{-1/x}}{x^2}<0,\forall x>0$$ when $a=0.1,b=0.2$ , we have $\xi\approx 0.16$ I think in order to get the proposition you want, you need to know something about $f'''$ , and information about $f'$ is useless | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4104077', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/258031/']} | jdg_379851 |
stackexchange | llm_judgeable_groundtruth_similarity | 50950690 |
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 researching about python codegolf and saw someone use the unpacking operator in a strange way: *s,='abcde' I know that the unpacking operator basically iterates over a sequence. So I know that s=[*'abcde'] will "unpack" the abcde string and save ['a', 'b', 'c', 'd', 'e'] in variable s . Can someone explain as thoroughly as possible how does the *s,='abcde' statement work? I know it does the same thing as s=[*'abcde'] but it accomplishes it in a different way. Why is the unpacking iterator on the variable, instead of the string? Why is there a comma right after the variable name?
Now provide the response and nothing else.
| This is Iterable Unpacking . You may have seen it in other places to assign values to multiple variables from a single expression a, b, c = [1, 2, 3] This syntax includes a * to indicate that this variable should be a list containing the elements from the iterable that weren't explicitly assigned to another variable. a, *b, c = [1, 2, 3, 4, 5]print(b)# [2, 3, 4] So, what's going on in your example? There's only a single variable name being assigned to, so it's going to take all the items not assigned to another variable, which in this case is all of them. If you try just *s='abcde' you'll get SyntaxError: starred assignment target must be in a list or tuple Which is why that comma is there, as a trailing comma is how you indicate a single-value tuple. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50950690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6745924/']} | jdg_379852 |
stackexchange | llm_judgeable_groundtruth_similarity | 499694 |
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:
Typically an easy diagnostic approach to checking an application server is running is to run telnet again the host and port: telnet somehost port The issue is that some operating systems, such as macOS now make the tool unavailable by default. For this reason, instead of trying to see how to install telnet, I am curious to know if there are any other CLI approaches to check a server is listening, without needing special privileges? Just to clarify I am looking for solutions that are as quick to use on any system as telnet, which is achievable in 5 seconds. Coding a solution doesn’t really offer a quick access approach.
Now provide the response and nothing else.
| You can try several ways to check if something listen on particular port: With wget / curl wget your_IP:port With netstat netstat -an|grep LISTEN|grep :port With lsof lsof -i :port With netcat nc -vz your_IP port With /proc filesystem (probably will work only on linux)( explained here ) With ss ss|grep LISTEN|grep :port With nmap nmap -sS -O -pport your_IP EDIT1 Also (almost) every ssh,http,ftp client can be used, but sometime will be hard to understand if port is closed by firewall or not available. EDIT2 Found in this Q/A sample way to use cat and echo to do the job: true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed or with only exec command (if you do not see error port is open): exec 6<>/dev/tcp/your_IP/port And I found a way to use only awk to do the job (original here ): awk -v port=your_port 'function hextodec(str,ret,n,i,k,c){ ret = 0 n = length(str) for (i = 1; i <= n; i++) { c = tolower(substr(str, i, 1)) k = index("123456789abcdef", c) ret = ret * 16 + k } return ret}function getIP(str,ret){ ret=hextodec(substr(str,index(str,":")-2,2)); for (i=5; i>0; i-=2) { ret = ret"."hextodec(substr(str,i,2)) } ret = ret":"hextodec(substr(str,index(str,":")+1,4)) return ret} NR > 1 {{local=getIP($2);remote=getIP($3) }{ if (remote ~ "0:0" && local ~ ":"port) print local}}' /proc/net/tcp EDIT3 As mentioned in to comment some of the methods, especially based on /dev filesystem may bot work in your environment | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/499694', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/27460/']} | jdg_379853 |
stackexchange | llm_judgeable_groundtruth_similarity | 61151041 |
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 don't understand the difference between a slice and a reference. What is the difference between &String and &str ? I read some stuff online that said a reference was a thin pointer and slice is a fat pointer, but I don't know and can't seem to find what those two mean. I know that a slice can coerce into a reference, but how does it do that? What is the Deref trait?
Now provide the response and nothing else.
| In Rust, a slice is a contiguous block of homogeneously typed data of varying length. What does this mean? [u8] is a slice. In memory, this is a block of u8 s. The slice itself is the data. Many times though, people refer to &[u8] as a slice. A &[u8] is a reference to that block of data. That reference contains two things: a pointer to the data itself, and the length of the data. Since it contains two things, it is therefore called a fat pointer. A &u8 is also a reference (can also be thought of as a pointer in this case * ), but we already know that whatever it points to will be a single u8 . Therefore, it is a thin pointer since it only has one element. You are guaranteed that all the data in a [u8] is of type u8 . Since your [u8] is just defined as a contiguous block of memory of type u8 , there's no compile time definition as to how large it is. Hence, we need to store its length in a pointer to it. We also can't put it on the stack (This translates to: we can't have a local variable that is just a [u8] ** ). Expanding: A [T] is a slice of T s. For any given T , as long as T is itself a sized type *** , we can imagine a type [T] . A str is a slice of a string. It is guaranteed to be valid UTF-8 text, and that's everything that separates it from a [u8] . Rust could have dumped the valid UTF-8 guarantee and just defined everything else in str as part of [u8] . Well, since you can't own a slice locally **** , you might be wondering how we create slices. The answer is that we put the data in something with the size already known, and then borrow slices from that. Take for example: let my_array: [u32; 3] = [1, 2, 3]; We can slice my_array into a [u32] like so: let my_slice: [u32] = my_array[..]; But since we can't own a local variable whose size isn't already known, we must put it under a reference: let my_slice: &[u32] = &my_array[..]; The point of a slice, is that it's a very flexible (barring lifetimes) method of working with contiguous blocks of data, no matter where the data comes from. I could've just as easily made my_array a Vec<u8> , which is heap-allocated, and it would still have worked. What is the difference between &String and &str? &String is a reference to the whole string object. The string object in Rust is essentially a Vec<u8> . A Vec contains a pointer to the data it "contains", so your &String could be thought of as a &&str . And, that is why we could do either of the following: let my_string: String = "Abc".to_string();let my_str: &str = &my_string[..]; // As explained previously// ORlet my_str: &str = &*my_string; The explanation of this brings me to your last question: What is the deref trait? The Deref trait, is a trait which describes the dereference ( * ) operator. As you saw above, I was able to do *my_string . That's because String implements Deref , which allows you to dereference the String . Similarly, I can dereference a Vec<T> into a [T] . Note however, that the Deref trait is used in more places than just where * is used: let my_string: String = "Abc".to_string();let my_str: &str = &my_string; If I try to assign a value of type &T into a place of type &U , then Rust will try to dereference my T , as many times as it takes to get a U , while still keeping at least one reference. Similarly, if I had a &&&&....&&&&T , and I tried to assign it to a &&&&....&&&&U , it would still work. This is called deref coercion: automatically turning a &T into a &U , where some amount of *T would result in a U . *: Raw pointers *const T and *mut T are the same size as references, but are treated as opaque by the compiler. The compiler doesn't make any guarantees about what is behind a raw pointer, or even that they're correctly aligned. Hence, they are unsafe to dereference. But since the Deref trait defines a deref method which is safe, dereferencing a raw pointer is special, and will not be done automatically either. **: This includes other dynamically sized types too, such as trait objects, and extern type s. This also includes struct s which contain a dynamically sized type as their last member as well, although these are very difficult to correctly construct, but will become easier in the future with the CoerceUnsized trait. It is possible to invalidate all of this (Except for extern type s) with the use of the unsized_locals nightly feature which allows some use of dynamically sized locals. ***: Sized types are all types whose size is known at compile time. You can identify them generically; given a type T , T 's size is known at compile time if T: Sized . If T: ?Sized , then its size may not be known at compile time ( T: ?Sized is the most flexible requirement for callers since it accepts anything ). Since a slice requires the data inside to be contiguous, and homogenous in size and type, dynamically sized types (Or !Sized ) aren't possible to contain within a slice, or an array, or a Vec<T> , and maintain O(1) indexing. While Rust could probably write special code for indexing into a group of dynamically sized types, it currently doesn't. ****: You actually can own a slice, it just has to be under a pointer which owns it. This can be, for example, a Box<[T]> , or a Rc<[T]> . These will deallocate the slice on their own (A Box when dropped, and a Rc when all strong and weak references of an Rc are dropped (The value's destructor is called when all strong references are dropped, but the memory isn't freed until all weak references are gone, too.)). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61151041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13063365/']} | jdg_379854 |
stackexchange | llm_judgeable_groundtruth_similarity | 1038444 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know how to construct a format string in .NET so that the resulting string contains a colon? In detail, I have a value, say 200, that I need to format as a ratio, i.e. "1:200". So I'm constructing a format string like this "1:{0:N0}" which works fine. The problem is I want zero to display as "0", not "1:0", so my format string should be something like "{0:1:N0;;N0}", but of course this doesn't work. Any ideas? Thanks!
Now provide the response and nothing else.
| using System;namespace ConsoleApplication67{ class Program { static void Main() { WriteRatio(4); WriteRatio(0); WriteRatio(-200); Console.ReadLine(); } private static void WriteRatio(int i) { Console.WriteLine(string.Format(@"{0:1\:0;-1\:0;\0}", i)); } }} gives 1:40-1:200 The ; separator in format strings means 'do positive numbers like this; negative numbers like this; and zero like this'. The \ escapes the colon. The third \ is not strictly necessary as a literal zero is the same as the standard numeric format output for zero :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1038444', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7239/']} | jdg_379855 |
stackexchange | llm_judgeable_groundtruth_similarity | 217951 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Are the following mutually consistent (relative to large cardinals)? (1) There are no $\omega_2$-Aronszajn trees. (2) There is an $\omega_1$-Kurepa tree. In the models I know of the tree property at $\omega_2$, it also holds that there are no weak Kurepa trees on $\omega_1$ (also called Canadian trees).
Now provide the response and nothing else.
| I wrote a short note with the consistency proof, which can be found at http://www.math.cmu.edu/users/jcumming/papers/kurepa/kurepa.pdf . It is pretty rough, please tell me if there are problems. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/217951', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11145/']} | jdg_379856 |
stackexchange | llm_judgeable_groundtruth_similarity | 32538 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The axiom of choice asserts the existence of a choice function for any family of sets F. Suppose, however, that F is finite, or even that F just has one set. Then how do we prove the existence of a choice function? The usual answer is that we just go from set to set, picking an element from each set. Since F is finite, this process will terminate. What I'm really wondering is how we can always choose from a single set. The informal answer seems to be just that it's possible... but this isn't an axiom, so it must be justified some other way. So: how do you prove from the axioms of just ZF without choice, that for any nonempty x there exists a function f:{x}->x?
Now provide the response and nothing else.
| There are two finite choice theorems, the internal one and the external one, both are true in ZF. As Charles Staats pointed out, the external version is a tautology (modulo some finite combinatorics): if $a_1,\dots,a_n$ are all nonempty, then there are $z_1 \in a_1$,...,$z_n \in a_n$ and then $\lbrace (a_1,z_1),\ldots,(a_n,z_n)\rbrace$ is the desired choice function for the family $X = \lbrace a_1,\dots,a_n \rbrace$ of nonempty sets. The internal version "every finite family of nonempty sets has a choice function" is stronger since a model of ZF may have nonstandard finite cardinals. The proof in this case is by induction on the cardinality of the family. The empty family has a trivial choice function — the empty function. Suppose we know the theorem to be true for families of size $n$. Let $X$ be a family of nonempty sets with size $n+1$. Let $g:n+1\to X$ be a bijection. Let $X' = g[n]$ and $a = g(n)$. Then $X'$ is a family of nonempty sets of size $n$, which therefore has a choice function $f':X' \to \bigcup X'$. Since $a$ is nonempty, we can find $z \in a$ and hence $f = f' \cup \lbrace (a,z) \rbrace$ is a choice function for the original family $X$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/32538', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7758/']} | jdg_379857 |
stackexchange | llm_judgeable_groundtruth_similarity | 2073923 |
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:
It seems the number of nonnegative integer solutions to the equation $xyz=n$ is given by $$\sum\limits_{d \mid n} \tau(d)$$ $\tau$ is the number of divisors function. I'm wondering if there is a way to simplify this sum. Really appreciate any kind of help. Thank you. Here is my attempt so far$$xyz = n$$ $x$ can be any of the factors of $n$ and the product $yz$ will be $n/x$.Since $yz$ sees all the factors of $n$, the number of nonnegative integer solutions to $xyz=n$ is simply the sum of divisors of the product $yz$. Edit : Special thanks to @Tryss for identifying an error in the formula. I've fixed it now..
Now provide the response and nothing else.
| The function$$f(n)=\sum_{d\mid n}\tau(d)$$is multiplicative. That is, $f(mn)=f(m)f(n)$ whenever $\gcd(m,n)=1$. Let's try to find a formula for powers of primes: $$f(p^r)=\sum_{d\mid p^r}\tau(d)=\sum_{k=0}^r\tau(p^k)=\sum_{k=0}^r(k+1)=\frac{(r+1)(r+2)}2$$ Then, if the prime factorization of $n$ is$$n=\prod_{k=1}^sp_k^{t_k}$$we have that$$f(n)=2^{-s}\prod_{k=1}^s(t_k+1)(t_k+2)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2073923', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/168854/']} | jdg_379858 |
stackexchange | llm_judgeable_groundtruth_similarity | 25724709 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
UIScrollView has a delegate property which conforms to UIScrollViewDelegate protocol UIScrollViewDelegate : NSObjectProtocol { //...}class UIScrollView : UIView, NSCoding { unowned(unsafe) var delegate: UIScrollViewDelegate? //...} UICollectionView overrides this property with a different type UICollectionViewDelegate protocol UICollectionViewDelegate : UIScrollViewDelegate, NSObjectProtocol { //...}class UICollectionView : UIScrollView { unowned(unsafe) var delegate: UICollectionViewDelegate? //...} When I try to override UIScrollViews delegate with my protocol like so: protocol MyScrollViewDelegate : UIScrollViewDelegate, NSObjectProtocol { //...}class MyScrollView: UIScrollView { unowned(unsafe) var delegate: MyScrollViewDelegate?} the compiler gives me two warnings: Property 'delegate' with type 'MyScrollViewDelegate?' cannot override a property with type 'UIScrollViewDelegate?' 'unowned' cannot be applied to non-class type 'MyScrollViewDelegate?' How can I subclass UIScrollView and override type of delegate property (i.e. use a custom delegate protocol) ?
Now provide the response and nothing else.
| I think overriding an inherited property is something that's possible in Objective-C but not (at least currently) in Swift. The way I've handled this is to declare a separate delegate as a computed property of the correct type that gets and sets the actual delegate: @objc protocol MyScrollViewDelegate : UIScrollViewDelegate, NSObjectProtocol { func myHeight() -> CGFloat // ...}class MyScrollView: UIScrollView { var myDelegate: MyScrollViewDelegate? { get { return self.delegate as? MyScrollViewDelegate } set { self.delegate = newValue } }} This way anything that calls the scroll view delegate normally still works, and you can call your particular delegate methods on self.myDelegate , like this: if let height = self.myDelegate?.myHeight() { // ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25724709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/855740/']} | jdg_379859 |
stackexchange | llm_judgeable_groundtruth_similarity | 14791361 |
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 new with angularjs... I read the docs, and completed the tutorial; i also tried something else by myself, and things start to make sense to me. Now i wonder how to make a safe authentication system . The easy part: no code, i will describe operations my code execute: I've a classic form: username, and password text input. The user fills the form, and press ENTER. An ajax request starts, and the response is a JSON telling me something like "ok i know you" or "i don't know who you are". What i need now is to mantain the logged status of the visitor (or not logged) between the different views of my application. I read on the internet that, to achieve this objective, someone sets a variable ($scope.isLogged = true), someone else uses cookies; but javascript variables, and cookies can be easily edited using firebug, or similiar development tools. ... and finally the question: So, have you some suggestion to achieve a safe authentication system in an angularjs app?
Now provide the response and nothing else.
| You cannot authorize anything in angularjs, because the user has full controll of the execution environment (namely, the browser). Each check, case, if - anything you can think of - can be tampered with. There are javascript libraries that use asymmetric keys to perform local encryption to store local data somewhat safely, but they are not what you are looking for, really. You can, and you should, authorize things on the server - the standard way you would do it in an ordinary application - using session; no special code is necessary, ajax calls use ordinary session cookies. Application does not need to know whether it's authenticated or not. It only needs to check what server thinks. From the perspective of your angularjs application, being "logged in" or "logged out" is merely a gui hint for the user. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14791361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1670665/']} | jdg_379860 |
stackexchange | llm_judgeable_groundtruth_similarity | 16155613 |
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 has been asked before, but the answers to previous questions are not solving my issue. I'm trying to build a simple Hello World app called (CalculatorBrain) from Stanford iTunes U courses. I can run it in the Simulator fine, but I'd like to get it on my iPhone 4S. I sync my iPhone 4S through iTunes on my Windows machine. Always have. Figured I should list this detail. Anyway, back to my Macbook (Mountain Lion). I'm running the most recent XCode 4.6.2 (4H1003) and my iPhone is also the most recent at 6.1.3 I believe. I went to the Provisioning Portal at the Apple developer page. I added my 4S. I called it JohnSmith, and gave it the phones UDID. In XCode, I opened the Organizer, Devices is highlighted by default. I put the passcode in my iPhone, and plugged it into my Macbook. Devices finds my iPhone. If I click on Provisioning Profiles and try 'Add Device to Provisioning Portal', I get a "A device with number already exists on this team." Great. I know it's added for sure then. All good news so far. In my Hello World app, CalculatorBrain-Info.plist my Bundle Identifier is "com.JohnSmith.CalculatorBrain". Bundle display name is "${PRODUCT_NAME}" and executable file is "${EXECUTABLE_NAME}" if that matters. In the Navigator, if I highlight my project, and bring up the Build Settings, under Code Signing Identity I get the options... Don't Sign Code Automatic Profile Selector- iPhone Developer- iPhone Distribution Identities without Provisioning Profiles- iPhone Developer: John Smith (R............K)- iPhone Distribution: John Smith (Y.............5) Other... I've tried all of these. I'm assuming I'm supposed to use the iPhone Developer: John Smith one... but it's saying it's an identity without Provisioning Profiles. What's going on here? What do I need to do to get this to work?
Now provide the response and nothing else.
| Based on your description, it sounds like the missing element is that you need to go back to the 'Certificates, Identifiers, and Profiles' tool, generate a Development Provisioning Profile for the AppID of your HelloWorld app, then install that profile on your development machine. At a high level, this is composed of the following steps: Locate the AppID for your project in Xcode. Verify that you've setup that AppID in 'Certificates, Identifiers, and Profiles'. Create a Development Provisioning Profile for that AppId, your development certificate, and one or more registered test devices. Download and Install the Provisioning Profile in Xcode. Configure your project to Code Sign using this Profile and Linked Code Signing Identity. Build to device! The 'Code Signing Identity' build configuration item you have mentioned is very much dependent on both your project's settings as well as the Provisioning Profiles available on your development machine. I recently answered a tangentially related question 'What are code signing identities?' that may be helpful in seeing what information Code Signing is using and how you can check that you've got your development machine setup to be able to Code Sign your project. ...and now, on to more specific HOWTOs to help work through your Code Signing question: Locating Project's AppID The AppID uniquely defines an application in the iOS ecosystem and is one of the things you first create when starting a new Xcode project. This AppID is what you need to register in the 'Certificates, Identifiers, and Profiles' tool to get started with Provisioning. In the Project Navigator (CMD+1), click on your project name (likely 'CalculatorBrain'). This will present the project's settings. Select [Your Project Name] > Summary Tab as shown in the screen clipping from above (MyiOSApplication). Your iOS AppID is presented in the 'Bundle Identifier' field. Snag a copy of this string, you'll need it next. Verify (or Setup) the AppID Navigate to http://developer.apple.com/ios and access the 'Certificates, Identifiers, and Profiles' tool. After logging in, select 'Identifiers'. Check that the AppID you found in the previous section is present in the list of App Identifiers. If so, take note of the App ID Name and skip to the next section, otherwise... Click the 'Add' (Plus) button in the upper right corner, provide a name for this App ID (can be whatever you want, just so long as it doesn't have special characters.) Scroll to the bottom of the page, and paste a copy of your App ID from the previous section in the 'Bundle ID' field. under 'Explicit App ID'. Click 'Continue'. Do note that the AppID must be unique across the iOS Ecosystem -- you may get an error if the AppID you've selected is already in use. If so, change your 'Bundle ID' to something unique -- just be sure to update the 'Bundle ID' setting in your Xcode project to match whatever you settle on. Creating a Development Provisioning Profile Now that the App ID is registered, you are now ready to create a Development Provisioning Profile linking your App ID, Development Certificate, and Test Device ID(s) together. Within the 'Certificates, Identities, Profiles' tool, navigate to 'Provisioning Profiles'. Click on the 'Add' (Plus) button in the upper right corner. Select 'iOS App Development' in the 'Select Type' step and then click 'Continue'. Select your App ID from the drop down list of App IDs and then click 'Continue'. Check the box next to your Development Certificate and then click 'Continue'. Check the box next to the test device(s) you want to authorize to install this app and then click 'Continue'. Key in a Profile Name (again omitting special characters) then click 'Generate'. Download and Install Provisioning Profile Once the Provisioning Profile is generated, the tool will provide you with a link to be able to download Download the Provisioning Profile by clicking on the 'Download' link. Drag Provisioning Profile from your Download location and drop it on the Xcode Dock Icon or double-click to open it. Configure Code Signing Identity Sounds like you already know where this is located, but just in case: In the Project Navigator (CMD+1), click on your project name (likely 'CalculatorBrain'). This will present the project's settings. Select [Your Project Name] > Build Settings Tab. Scroll to the 'Code Signing Identity' item. In theory you would like to use the 'Automatic Profile Selector' option which will attempt to match your AppID to an installed Provisioning Profile, but you can also scroll through the list and pick a specific mapping of Bundle ID/AppId to iOS Certificate. Also, my own Xcode doesn't always seem to catch on to changes to freshly-installed provisioning profiles -- It is unclear if this is just a quirk of my own Xcode install or if there is a bug in Xcode. Either way, quitting and relaunching Xcode seems to trigger a reindex/refresh of profiles. Anyway, select the option that matches your AppId/BundleId and your Developer Certificate. Assuming the problem was a missing/incomplete/expired Provisioning Profile, then this should help get you up and running. If not, we'll have to dig into other potential settings or certificates issues that could be tripping up your Code Signature operation. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16155613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1652166/']} | jdg_379861 |
stackexchange | llm_judgeable_groundtruth_similarity | 24829355 |
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 build a blog website with express.js and mongoosejs. A article may have one or more category. When I create a new article, I get error: { [CastError: Cast to ObjectId failed for value "[object Object]" at path "categories"] message: 'Cast to ObjectId failed for value "[object Object]" at path "categories"', name: 'CastError', type: 'ObjectId', value: [ [object Object] ], path: 'categories' } Could any one help me out?Related code shows bellow: The Article model defined like this: var mongoose = require('mongoose'),Schema = mongoose.Schema;var ArticleSchema = new Schema({created: { type: Date, default: Date.now},title: String,content: String,summary: String,categories: [{ type: Schema.ObjectId, ref: 'Category' }]});mongoose.model('Article', ArticleSchema); And the Category model defined like this: var mongoose = require('mongoose'),Schema = mongoose.Schema;var CategorySchema = new Schema({ parent: { type: Schema.ObjectId, }, name: String, subs: [CategorySchema]});mongoose.model('Category', CategorySchema); When I create a new Article and save it like this: exports.create = function(req, res) { console.log(req.body); var article = new Article(req.body); article.user = req.user; console.log(article); article.save(function(err) { if (err) { console.log(err); return res.jsonp(500, { error: 'Cannot save the article' }); } res.jsonp(article); });}; When called the create function, the console.log() output shows bellow: // console.log(req.body);{ title: 'This is title', content: '<p>content here</p>', categories: [ { _id: '53c934bbf299ab241a6e0524', name: '1111', parent: '53c934b5f299ab241a6e0523', __v: 0, subs: [], sort: 1 } ], updated: [ 1405697477413 ] }// console.log(article);{ title: 'This is title', content: '<p>content here</p>', _id: 53c93dc5b1c3b8e80cb4936b, categories: [], created: Fri Jul 18 2014 23:31:17 GMT+0800 (中国标准时间) }// console.log(err);{ [CastError: Cast to ObjectId failed for value "[object Object]" at path "categories"] message: 'Cast to ObjectId failed for value "[object Object]" at path "categories"', name: 'CastError', type: 'ObjectId', value: [ [object Object] ], path: 'categories' } I have googled a lot, but without luck. Please help me! Update: Thank for Gergo's answer. But if I update the exist article with the almoset the same code, it works OK! Why? Codes shows bellow: var mongoose = require('mongoose'), Category = mongoose.model('Category'), _ = require('lodash');exports.update = function(req, res) {console.log(req.body);var article = req.article;article = _.extend(article, req.body);console.log(article);article.save(function(err) { if (err) { return res.jsonp(500, { error: 'Cannot update the article' }); } res.jsonp(article); });}; The output like this: // console.log(req.body);{ _id: '53ca42f418bfb23c1e04df02', summary: 'tttt', title: 'tt', content: '<p>tttt</p>', __v: 2, categories: [ { _id: '53c934bbf299ab241a6e0524', name: '1111' } ], created: '2014-07-19T10:05:40.183Z'}// console.log(article);{ _id: 53ca42f418bfb23c1e04df02, title: 'tt', content: '<p>tttt</p>', __v: 2, categories: [ { _id: 53c934bbf299ab241a6e0524, name: '1111', subs: [], sort: 0 } ], created: Sat Jul 19 2014 18:05:40 GMT+0800 (中国标准时间) } This works ok.
Now provide the response and nothing else.
| Your article schema expects an array of ObjectId : var ArticleSchema = new Schema({ ... categories: [{ type: Schema.Types.ObjectId, ref: 'Category' }]}); However req.body contains a category object: categories: [ { _id: '53c934bbf299ab241a6e0524', name: '1111', parent: '53c934b5f299ab241a6e0523', __v: 0, subs: [], sort: 1 } ] And Mongoose can't convert the category object to an ObjectId . This is why you get the error. Make sure categories in req.body only contains ids: { title: 'This is title', content: '<p>content here</p>', categories: [ '53c934bbf299ab241a6e0524' ], updated: [ 1405697477413 ] } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24829355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1260562/']} | jdg_379862 |
stackexchange | llm_judgeable_groundtruth_similarity | 28267896 |
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 learn what visibility to assign to nested classes, besides what my IDE yells at me that I have to do. This can get arbitrarily complicated, so I need to understand the general rules. public class A { private static class B { public int foo; // accessible in A? private int bar; // accessible in A? public static class C { // accessible in A? everywhere? } private static class D { // accessible in A? } }} As far as I understand, modifiers seem to resolve at the "file" level, not at the level of the encapsulating class. Once one thing is private, anything inside it is private. What's the actual mechanism of this or the technical explanation? Is this documented somewhere or do I just need to read the JLS?
Now provide the response and nothing else.
| One of the best summaries of access visibility that I've seen is in the Java Tutorials > Controlling access to members of a class , but it glosses over some of the key details. The question I think you are asking is answered in § 6.6.1 of the JLS for SE 7: "Determining Accessibility" If ... public ... Otherwise, if ... protected ... Otherwise, if ... package access ... Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor . If you read that carefully: any access within the body of the top level class to another private (not package-private - that's different) member regardless of how deep it is nested is permitted So: any member inside any depth of private nested classes is accessible anywhere within the body of the top level class (including within other nested sibling classes). However a private nested class, and any member within, is not visible to other top level classes. For example: public class A { private static class B { public int foo; // accessible in A and P private int bar; // accessible in A and P public static void test(){ P p = new P(); p.foo = 1; p.bar = 1; } } private static class P { public int foo; // accessible in A and B private int bar; // accessible in A and B public static void test(){ B b = new B(); b.foo = 1; b.bar = 1; } } public static void test(){ B b = new B(); b.foo = 1; b.bar = 1; P p = new P(); p.foo = 1; p.bar = 1; }} Note: This isn't "file level" though. Declare another top level class in that file (which could not be public - only one of those allowed per file) and it couldn't see those same nested private members. class X { public static void test() { // all of these statements fail ... A.B b = new A.B(); b.foo = 1; b.bar = 1; b.test(); A.P p = new A.P(); p.foo = 1; p.bar = 1; p.test(); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28267896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1339987/']} | jdg_379863 |
stackexchange | llm_judgeable_groundtruth_similarity | 10307131 |
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 strange problem. I use the prepareAsync method with the MediaPlayer , but the listener that I declared just never gets fired. I try to stream a live .mp3 feed from the Internet (radio station). I use an inline method for the listener, but I also tried implementing the interface without any success. Here's a portion of my code : In the member section : String url = "http://<my_url>.mp3";MediaPlayer mediaPlayer = new MediaPlayer(); In Activity onCreate() : ToggleButton playButton = (ToggleButton) findViewById(R.id.playToggleButton);playButton.setOnClickListener(this);playButton.clearFocus();playButton.setClickable(false);mediaPlayer.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mp) { ToggleButton playButton = (ToggleButton) findViewById(R.id.playToggleButton); playButton.setClickable(true); mp.start(); }});preparePlayer(); Then, here's the preparePlayer() method : private void preparePlayer() { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); } mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(url); mediaPlayer.prepareAsync(); } catch (IllegalArgumentException e) { Toast.makeText( MyStreamActivity.this, getResources().getString(R.string.erreurIllegalArgument), Toast.LENGTH_LONG).show(); e.printStackTrace(); } catch (IllegalStateException e) { Toast.makeText( MyStreamActivity.this, getResources().getString(R.string.erreurIllegalState), Toast.LENGTH_LONG).show(); e.printStackTrace(); } catch (IOException e) { Toast.makeText( MyStreamActivity.this, getResources().getString(R.string.erreurIO), Toast.LENGTH_LONG).show(); e.printStackTrace(); }} And (just for the record), the onDetroy() where I do the cleaning : private void releaseMediaPlayer() { if (mediaPlayer != null) { if(mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer.release(); mediaPlayer = null; }}@Overrideprotected void onDestroy() { super.onDestroy(); releaseMediaPlayer();}
Now provide the response and nothing else.
| You are setting the OnPreparedListener in your Activity 's create method and later on, possibly, creating a new MediaPlayer in your preparePlayer() method. Any newly created MediaPlayer 's wont have the prepareListener set. You should also add an errorlistener to find out whats going on. You may want to move the setOnPreparedListener call inside the if (mediaPlayer == null) { mediaPlayer = new MediaPlayer();} as well as setting a setOnErrorListener like so: if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); mediaPlayer.setOnErrorListener(....); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mp) { ToggleButton playButton = (ToggleButton) findViewById(R.id.playToggleButton); playButton.setClickable(true); mp.start(); } });} Please change e.printStackTrace(); to Log.e("tag", e.getMessage(), e); Hope this helps, let us know if you have any log data as this will also be useful. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10307131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301795/']} | jdg_379864 |
stackexchange | llm_judgeable_groundtruth_similarity | 33524766 |
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 been working on a C# application and wanted to try the GitLab CI out. All I can see is Ruby and can't find any information on how to build a C# application using it. When I run the test settings, I make the commit, but I don't have my build. How should I make a simple build? Which command could I use for that? I don't mind if I get a failed build (but a build).
Now provide the response and nothing else.
| I just wanted to share my .gitlab-ci.yml complete with unit testing. You will have to adjust your nuget and possibly other paths. This is for a single project in a solution of the same name. variables: PROJECT_NAME: "ProjectNameGoesHere"before_script: - echo "starting build for %PROJECT_NAME%" - echo "Restoring NuGet Packages..." - d:\tools\nuget restore "%PROJECT_NAME%.sln"stages: - build - testbuild: stage: build script: - echo "Release build..." - '"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe" /consoleloggerparameters:ErrorsOnly /maxcpucount /nologo /property:Configuration=Release /verbosity:quiet "%PROJECT_NAME%.sln"' artifacts: untracked: truetest: stage: test script: - echo "starting tests" - cd %PROJECT_NAME%Tests/bin/Release - '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\MSTest.exe" /testcontainer:%PROJECT_NAME%Tests.dll' dependencies: - build | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33524766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5168974/']} | jdg_379865 |
stackexchange | llm_judgeable_groundtruth_similarity | 15098090 |
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 gotta be missing something obvious. select CEILING(85/30) = 285/30 = 2.83333 I want the value to be 3. Shouldn't the CEILING function round up for me?
Now provide the response and nothing else.
| Try SELECT CEILING(85.0/30) And for comparison SELECT 85.0 / 30, 85 / 30 The first example uses floats, the second uses ints, so the result is rounded before the ceiling function is hit. What you do is SELECT CEILING(2) Rather than SELECT CEILING(2.833333) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15098090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1535850/']} | jdg_379866 |
stackexchange | llm_judgeable_groundtruth_similarity | 287037 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I had a discussion recently with people absolutely opposed to a rebase strategy of feature branches on GIT. It seems to be an accepted pattern to use rebase only for local, private branches but never use it when there's several people working on a same feature & branch, as per this so-called "Golden Rule of Rebasing" (like explained here: https://www.atlassian.com/git/tutorials/merging-vs-rebasing/conceptual-overview ) I am just surprised there's a consensus on this. I worked 3 years with a full rebasing strategy, with about 20 developers working togeteher and guess what, it worked. The process is basically: You create your feature branch, let's call it "myfeature", and push it to origin/myfeature Other people may check it out and work on it You may sometimes rebase it from master: from "myfeature", git rebase origin/master ; and then, yes, you have to push-force it. What happens when other people want to push their commits? They just rebase it: git rebase origin/myfeature . So they're now in fast-forward and can push it without forcing. The only principle to respect is that the feature branch is owned by someone . The owner is the only one who can push-force. So, I admit: as soon as there's a push-force, there's a risk to do errors. That's true. But there's also many ways to recover from errors, and really, in 3 years of development, I didn't saw a lot of force-pushing mistakes, and when it came to happen we always found a way to recover properly. So, why is this "Golden Rule of Rebase" being so widely accepted? Is there something else I missed with that? I understand it requires a minimum of organization (every strategy requires some organization), but it works.
Now provide the response and nothing else.
| The problem with force pushing isn't about your feature branch and master, but about pushing your master to someone else's master - that synchronization is going to be overwriting their master with your changes, ignoring whatever is on their tip. Considering this danger, there's a reason why you should not be using it at all unless things have screwed up and you absolutely, totally need to use it to effect repairs. A SCM system should not ever need to be forced like this, if it does its because something went horribly wrong (and my first approach in such cases would be to restore backups and repeat the operations to keep the history intact). So perhaps the question is why are you rebasing at all? For 'clean' history when bringing features back to master? If so, you're throwing out all the good history concerning branching for purely style reasons. IMHO fast-forward merging is also not a best practice either, you should want to keep all history so you can see what you really did, not a sanitised version afterwards. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/287037', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/153317/']} | jdg_379867 |
stackexchange | llm_judgeable_groundtruth_similarity | 22298846 |
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 object structure: @Document(collection = "user")@TypeAlias("user")public class User { @Id private ObjectId id; private Contact info = new Contact();} and here is the Contact pojo: public class Contact { @Indexed(unique = true) private String mail;} But for some reasons not known to me, I don't see Spring-data creating a unique index for the property info.mail To summarize, I have this json structure of user object: {_id:xxxxx,info:{mail:"[email protected]"}} And I want to create a unique index on info.mail using Spring data with the above pojo structure. Please help.
Now provide the response and nothing else.
| As far as I remember, annotating embedded fields with @Indexed will not work. @CompoundIndex is the way to go: @Document(collection = "user")@TypeAlias("user")@CompoundIndexes({ @CompoundIndex(name = "contact_email", def = "{ 'contact.mail': 1 }", unique = true)})public class User { @Id private ObjectId id; private Contact info = new Contact();} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22298846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/949912/']} | jdg_379868 |
stackexchange | llm_judgeable_groundtruth_similarity | 56900 |
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:
The law of retaliation can be found in Exodus 21:22-25 (ESV): 22 “When men strive together and hit a pregnant woman, so that her children come out, but there is no harm, the one who hit her shall surely be fined, as the woman's husband shall impose on him, and he shall pay as the judges determine. 23 But if there is harm, then you shall pay life for life , 24 eye for eye, tooth for tooth, hand for hand, foot for foot , 25 burn for burn, wound for wound, stripe for stripe . On the one hand, Jesus seems to leave no room for doubt that he is utterly against it: 38 “ You have heard that it was said, ‘An eye for an eye and a tooth for a tooth. ’ 39 But I say to you , Do not resist the one who is evil. But if anyone slaps you on the right cheek, turn to him the other also . 40 And if anyone would sue you and take your tunic, let him have your cloak as well. 41 And if anyone forces you to go one mile, go with him two miles. 42 Give to the one who begs from you, and do not refuse the one who would borrow from you. [Matthew 5:38-42 ESV] Yet, in the same chapter of Matthew, Jesus expresses his full support for the entire Mosaic Law in general and, by logical implication, the law of retaliation in particular: 17 “ Do not think that I have come to abolish the Law or the Prophets; I have not come to abolish them but to fulfill them . 18 For truly, I say to you, until heaven and earth pass away, not an iota, not a dot, will pass from the Law until all is accomplished . 19 Therefore whoever relaxes one of the least of these commandments and teaches others to do the same will be called least in the kingdom of heaven, but whoever does them and teaches them will be called great in the kingdom of heaven . 20 For I tell you, unless your righteousness exceeds that of the scribes and Pharisees, you will never enter the kingdom of heaven. [Matthew 5:17-20 ESV] So, is Jesus against or in favor of the law of retaliation? Should we trust Matthew 5:38-42 in leading us to conclude that Jesus is against it, or should we rather pay attention to Matthew 5:17-20 and see how Jesus fully supports it? How can we overcome this apparent contradiction?
Now provide the response and nothing else.
| "Now these are the judgments which thou shalt set before them." (Ex. 21:1, KJV) The opening statement of the chapter sets the context within court proceedings, ie. judgment. So, the judgments that were listed for certain offenses were limits. The laws regarding "retaliation" were not to condone violence, but to set a limit on restitution. They were not intended to be literally imposed as most today assume, but were the basis for current precedents that the punishment should not exceed the crime. Moreover, the judge set repayment for the victim in like form of the damages, or in monetary form if bodily injury ensued. They did not literally demand another's eye in repayment for an eye lost. Gill's Exposition at Matt. 5:38: "an eye for an eye, and a tooth for a tooth, Exodus 21:24. This is "lex talionis", the "law of retaliation"; which, whether it is to be understood literally, or not, is a matter of question. The Baithuseans, or Sadducees, among the Jews, took it in a literal sense, and so does Josephus, who says (b), he that shall blind, i.e. put out a man's eyes, shall suffer the like. But the Jewish doctors generally understood it of paying a price equivalent to the damage done, except in case of life. R. Sol. Jarchi (c) explains the law thus: "He that puts out his neighbour's eye, must give him , "the price of his eye", according to the price of a servant sold in the market; and so the same of them all; for, not taking away of the member is strictly meant.'' Source: Biblehub Ellicott's Commentary on Matt. 5:38: "Here again the scribes first took their stand on the letter, regardless of the aim and purpose, of the Law, and then expanded it in a wrong direction. As originally given, it was a check on the “wild justice” of revenge. It said, where the equilibrium of right had been disturbed by outrage, that the work of the judge was not to do more than restore the equilibrium, unless, as in the case of theft, some further penalty was necessary for the prevention of crime. It was, in its essence, a limit in both directions. Not less than the “eye for an eye,” for that might lead to connivance in guilt; not more, for that would open a fresh score of wrong. The scribes in their popular casuistry made the rule one not of judicial action only, but of private retaliation; and it was thus made the sanction of the vindictive temper that forgives nothing." Source: Biblehub Excerpt from Benson Commentary: "Though this statute was only intended as a direction to judges, with regard to the penalties to be inflicted in case of violent and barbarous assaults; yet it was interpreted among the Jews as encouraging a rigorous and severe revenge of every injury a man might receive. ....Upon the whole of this passage, from Matthew 5:38, we may observe, that it seems to have been primarily intended to counteract and correct that abuse of the law of retaliation above mentioned, which was common among the Jews, who carried their resentments to the utmost lengths; and, by so doing, maintained infinite quarrels, to the great detriment of social life...." Source: Ibid And, from Jamieson-Fausset-Brown Commentary: "... This law of retribution—designed to take vengeance out of the hands of private persons, and commit it to the magistrate—was abused in the opposite way to the commandments of the Decalogue. While they were reduced to the level of civil enactments, this judicial regulation was held to be a warrant for taking redress into their own hands, contrary to the injunctions of the Old Testament itself (Pr 20:22; 24:29)." Source: Ibid So, Jesus was correcting the extreme to which the Jews had used the law for personal retaliation and vengeance. The original intent was for judicial determinations as a limit to restitution in magisterial or judges sentencing. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/56900', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/-1/']} | jdg_379869 |
stackexchange | llm_judgeable_groundtruth_similarity | 1827212 |
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 spring application which is not calling bean destroy methods on shutdown. I've seen references to this being due to instantiation in a beanRefFactory, and that this can be circumvented through manually calling registerShutdownHook() on an the application context.This method seems to have disappeared from spring between versions 2.0 - 2.5. Can someone point me in the direction of how this is now done? Thanks.
Now provide the response and nothing else.
| This method is still available in ConfigurableApplicationContext and implemented by AbstractApplicationContext . So you might be able to do this ApplicationContext ctx = ...;if (ctx instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext)ctx).registerShutdownHook();} Alternatively, you could simply call ((ConfigurableApplicationContext)ctx).close() yourself while closing down the application or using your own shutdown hook: Runtime.getRuntime().addShutdownHook(new Thread() { public void run(){ if (ctx instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext)ctx).close(); } } }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1827212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19479/']} | jdg_379870 |
stackexchange | llm_judgeable_groundtruth_similarity | 20267 |
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:
If electromagnetic radiation represents a transfer of energy, then does a permanent magnet represent unlimited energy, and if so, why can't magnets be used for perpetual motion? Even if permanent magnets aren't permanent and rather just have a really long usable lifetime, don't they at least represent a large resource of energy?
Now provide the response and nothing else.
| A (non-accelerated) permanent magnet doesn't produce electromagnetic radiation. It is surrounded by a magnetic field (just like a charge is surrounded by an electric field), but it does not radiate. Especially there's no energy leaving the magnet. Note that for energy flow (as in radiation) you need both an electric and magnetic field, because only then you'll get a non-vanishing Pointing vector $\vec S=\vec E\times\vec B$. However note that even if you have energy flow, you don't necessarily have radiation (e.g. if you have a constantly moving charge, the field energy is flowing with the charge, but it doesn't radiate). | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/20267', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7424/']} | jdg_379871 |
stackexchange | llm_judgeable_groundtruth_similarity | 30756392 |
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 writing a template function that receives a std::function object (Generated by calling std::bind with the proper arguments).Within this function, I would like to determine the return type of this function object. Is is possible? As a matter of fact, I want the template function to return the same type. Can you think of an elegant, standard based, way of achieving this goal? Something like: template <typename T>T::return_type functionObjWrapper(T functionObject) { // ... return functionObject();} Thanks
Now provide the response and nothing else.
| You can do it using decltype and trailing return type: template <typename T>auto functionObjWrapper(T functionObject) -> decltype(functionObject()) { // ... return functionObject();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30756392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4631270/']} | jdg_379872 |
stackexchange | llm_judgeable_groundtruth_similarity | 32427630 |
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 detect how long a button was pressed / released in Arduino and then print some custom output after that?
Now provide the response and nothing else.
| Arduino can only detect the state of your button (pressed OR unpressed). You could use a timer variable (based on this example from their docs) to save the exact time when you pressed or released the button, so you can check the difference between both variables to calculate how long it is on hold or idle. The code could look like this: const int buttonPin = 2; int buttonState = 0; // current state of the buttonint lastButtonState = 0; // previous state of the buttonint startPressed = 0; // the moment the button was pressedint endPressed = 0; // the moment the button was releasedint holdTime = 0; // how long the button was holdint idleTime = 0; // how long the button was idlevoid setup() { pinMode(buttonPin, INPUT); // initialize the button pin as a input Serial.begin(9600); // initialize serial communication}void loop() { buttonState = digitalRead(buttonPin); // read the button input if (buttonState != lastButtonState) { // button state changed updateState(); } lastButtonState = buttonState; // save state for next loop}void updateState() { // the button has been just pressed if (buttonState == HIGH) { startPressed = millis(); idleTime = startPressed - endPressed; if (idleTime >= 500 && idleTime < 1000) { Serial.println("Button was idle for half a second"); } if (idleTime >= 1000) { Serial.println("Button was idle for one second or more"); } // the button has been just released } else { endPressed = millis(); holdTime = endPressed - startPressed; if (holdTime >= 500 && holdTime < 1000) { Serial.println("Button was held for half a second"); } if (holdTime >= 1000) { Serial.println("Button was held for one second or more"); } }} However, if you want to trigger an event while the button is still pressed (or maybe you want to increment a counter in some display), you can still do the same math. Change your condition in the loop function to be like this: if (buttonState != lastButtonState) { updateState(); // button state changed. It runs only once. } else { updateCounter(); // button state not changed. It runs in a loop. } And then implement your new function like this: void updateCounter() { // the button is still pressed if (buttonState == HIGH) { holdTime = millis() - startPressed; if (holdTime >= 1000) { Serial.println("Button is held for more than a second"); } // the button is still released } else { idleTime = millis() - endPressed; if (idleTime >= 1000) { Serial.println("Button is released for more than a second"); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32427630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1677656/']} | jdg_379873 |
stackexchange | llm_judgeable_groundtruth_similarity | 11865582 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ι've tried all the solution that I could find, but nothing seems to work: teext = str(self.tableWidget.item(row, col).text()) I'm writing in greek by the way...
Now provide the response and nothing else.
| Clearly, self.tableWidget.item().text() returns Unicode, and you need to use the decode method instead: self.tableWidget.item(row, col).text().encode('utf8') You really want to review the Python Unicode HOWTO to fully appreciate the difference between a unicode object and it's byte encoding. Another excellent article is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) , by Joel Spolsky (one of the people behind Stack Overflow). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11865582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/938884/']} | jdg_379874 |
stackexchange | llm_judgeable_groundtruth_similarity | 29035896 |
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 question concerning clicks on a map in leaflet. If I click on the map I want to set a marker there, but if doubleclick on the map I just want to zoom in without setting a marker. So I have the follwing code: var map = L.map(attrs.id, { center: [scope.lat, scope.lng], zoom: 14 });var marker = L.marker([scope.lat, scope.lng],{draggable: true});map.on('click', function(event){ marker.setLatLng(event.latlng); marker.addTo(map); }); The problem now is, when I doublclick on the map the click event is also fired and I would like to remove that behavior. How can I achieve that? Thanks Magda
Now provide the response and nothing else.
| So, I found a way to do that, I am still not sure, if there is a better way to do it. var map = L.map(attrs.id, { center: [scope.lat, scope.lng], zoom: 14 });map.clicked = 0; L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map);var marker = L.marker([scope.lat, scope.lng],{draggable: true});map.on('click', function(event){ map.clicked = map.clicked + 1; setTimeout(function(){ if(map.clicked == 1){ marker.setLatLng(event.latlng); marker.addTo(map); map.clicked = 0; } }, 300);});map.on('dblclick', function(event){ map.clicked = 0; map.zoomIn();}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29035896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2739152/']} | jdg_379875 |
stackexchange | llm_judgeable_groundtruth_similarity | 64271173 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have an AKS cluster and sometimes we end up with an issue where a deployment needs a restart (e.g. cached data has been updated and we want to refresh it or there is corrupt cache data we want to refresh). I've been using the approach of scaling the deployment to 0 and then scaling it back up using the commands below: kubectl scale deployments/<deploymentName> --replicas=0kubectl scale deployments/<deploymentName> --replicas=1 This does what I expect it to do, but it feels hacky and it means we're not running any deployments while this process is taking place. What's a better approach to doing this? For either a specific deployment and for all the deployments?
Now provide the response and nothing else.
| If you have a strategy of RollingUpdate on your deployments you can delete the pods in order to replace the pod and refresh it. About the RollingUpdate strategy: Users expect applications to be available all the time and developersare expected to deploy new versions of them several times a day. InKubernetes this is done with rolling updates. Rolling updates allowDeployments' update to take place with zero downtime by incrementallyupdating Pods instances with new ones. RollingUpdate config: spec: strategy: rollingUpdate: maxSurge: 1 maxUnavailable: 0 type: RollingUpdate maxSurge specifies the maximum number of Pods that can be created over the desired number of Pods. maxUnavailable specifies the maximum number of Pods that can be unavailable during the update process. Delete the pod: kubectl delete pod <pod-name> Edit: Also, you can rollout the deployment, which will restart the pod but will create a new revision of the deployment as well. Ex: kubectl rollout restart deployments/<deployment-name> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64271173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2535758/']} | jdg_379876 |
stackexchange | llm_judgeable_groundtruth_similarity | 18553 |
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 $S_4 = \left(\begin{array}{cc}0&-1 \\\ 1&0 \end{array}\right) \textrm{ and } S_6 = \left(\begin{array}{cc} 1&-1 \\\ 1&0\end{array}\right)$. Serre proves in his book on trees that $SL_2(\mathbb{Z}) \cong \mathbb{Z}/4 *_{\mathbb{Z}/2} \mathbb{Z}/6$, and $S_4$ and $S_6$ are the elements corresponding to the generators of $\mathbb Z/4$ and $\mathbb Z/6$ (I'm not sure if this is related to my question). Then let $a = S_4 S_6$ and $b = S_4 S_6^2$. I believe every element of $SL_2(\mathbb Z)$ can be written as $S_6^d w S_6^e$, where $w$ is a word in $a$ and $b$ but not $a^{-1}$ or $b^{-1}$. I wrote a program (for other purposes) that seems to show that there aren't any relations between $a$ and $b$ that have length 15 or less and don't involve $a^{-1}$ or $b^{-1}$. I'm not certain that the program is right, but if it is, one might make a naive guess that these two elements generate a free group. This makes me suspicious. 1) Does $SL_2(\mathbb Z)$ contain a free group (of rank > 1)? If it does, is there an easy way to determine whether the subgroup generated by $a$ and $b$ is free? 2) A slightly less naive guess is that $a$ and $b$ generate a free monoid in $SL_2(\mathbb Z)$. Is there a reason why $SL_2(\mathbb Z)$ can't contain a free monoid, or an example showing that it does? EDIT: Thanks for the quick replies. As Robin and Jack pointed out, $a$ and $b$ generate SL(2,Z), so clearly don't generate a free group. Also, there are free subgroups that are easy to write down. I'm still curious about #2, though.
Now provide the response and nothing else.
| Certainly $\mathrm{SL}(2,\mathbb{Z})$ contains a free group.For instance $\Gamma(2)$, the subgroup of all matrices congruentto the identity modulo $2$, is free of rank $2$. The matrices$\left(\begin{array}{cc}1&2\\\ 0&1\end{array}\right)$and$\left(\begin{array}{cc}1&0\\\ 2&1\end{array}\right)$freely generate $\Gamma(2)$. This can be proved by considering the action on the upper half-planeor by careful examination of reduced words.There's a nice proof in chapter 18 of David Ullrich'sbook Complex Made Simple . Your $a$ and $b$ don't generate a free group alas, since theygenerate all of $\mathrm{SL}(2,\mathbb{Z})$. Re the edited question. Let's write$$T=\left(\begin{array}{cc}1&1\\\ 0&1\end{array}\right)\qquad\textrm{and}\qquad U=\left(\begin{array}{cc}1&0\\\ 1&1\end{array}\right).$$As both Jack and I pointed out, $T^2$ and $U^2$ generatea free subgroup of rank $2$. Now it's an easy exercise to prove that$T$ and $U$ freely generate a free monoid of rank $2$ (becausetheir entries are non-negative). On the other hand, they generatethw whole group $\mathrm{SL}(2,\mathbb{Z})$ which is certainlynot free. Your matrices $a$ and $b$ are, if my calculationsare right, $-U^{-1}$ and $-T^{-1}$. The matrix $S_4$ conjugates $T$and $U$ into $U^{-1}$ and $T^{-1}$ so $U^{-1}$ and $T^{-1}$ freelygenerate a free monoid of rank $2$. The same must be true of$U^{-1}$ and $T^{-1}$, that is, of $a$ and $b$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/18553', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2669/']} | jdg_379877 |
stackexchange | llm_judgeable_groundtruth_similarity | 27397865 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A lot of times (not always) the stdout is displayed in colors. Normally I keep every output log in a different file too. Naturally in the file, the colors are not displayed anymore. I'd like to know if there's a way (in Linux) to write the output to a file with colors. I'm trying to use tee to write the output of vagrant to a file, this way I can still see the output (when it applies). I want to use it specifically for vagrant (it may change in the future, of course...)
Now provide the response and nothing else.
| Since many programs will only output color sequences if their stdout is a terminal, a general solution to this problem requires tricking them into believing that the pipe they write to is a terminal. This is possible with the script command from bsdutils: script -q -c "vagrant up" filename.txt This will write the output from vagrant up to filename.txt (and the terminal). If echoing is not desirable, script -q -c "vagrant up" filename > /dev/null will write it only to the file. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27397865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1911133/']} | jdg_379878 |
stackexchange | llm_judgeable_groundtruth_similarity | 67227755 |
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 can't find any doc on the matter, is there something similar to a CollapsingToolbar in Compose? All I found was a mention of it here , but nothing on how to set it up
Now provide the response and nothing else.
| I found a solution created by Samir Basnet (from Kotlin Slack Channel) which was useful for me, I hope it helps someone else... @Composablefun CollapsingEffectScreen() { val items = (1..100).map { "Item $it" } val lazyListState = rememberLazyListState() var scrolledY = 0f var previousOffset = 0 LazyColumn( Modifier.fillMaxSize(), lazyListState, ) { item { Image( painter = painterResource(id = R.drawable.recife), contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .graphicsLayer { scrolledY += lazyListState.firstVisibleItemScrollOffset - previousOffset translationY = scrolledY * 0.5f previousOffset = lazyListState.firstVisibleItemScrollOffset } .height(240.dp) .fillMaxWidth() ) } items(items) { Text( text = it, Modifier .background(Color.White) .fillMaxWidth() .padding(8.dp) ) } }} Here is the result: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67227755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7443101/']} | jdg_379879 |
stackexchange | llm_judgeable_groundtruth_similarity | 214730 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I wonder if I should close any unnecessary database connection inside of my PHP scripts. I am aware of the fact that database connections are closed implicitly when the block stops executing and 'manually' closing the connections could kinda bloat the codebase with unnecessary code. But shouldn't I do so in order to make by code as readable and as easy understandable as possible, while also preventing several possible issues during run time? Also, if I would do, would it be enough to unset() my database object?
Now provide the response and nothing else.
| For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it. Using unset is the same as leaving the database connection open, as you're relying on the garbage collector to clean up after the variable as opposed to asking the connection to gracefully close the connection after you're done with it. Though as mentioned by CodeCaster below, doing so is acceptable since the garbage collector makes sure that the connections are closed. A useful example, lets say you're eating lunch at a cafeteria somewhere. After eating, you have two choice, throw your left overs in the trash then return the plate/tray to its rightful place(thats cleaning up after yourself). And the other is just leaving your mess on the table and wait for someone else(the garbage collector) to clean it up for you. If you clean it up yourself, you're sure that your mess is cleaned up. But if you rely on the garbage collector, right before the garbage collector cleans up your mess, what if some weird stalker decides to use your used utensils to aid them in their nightly fantasies about you, then return them back to the cafeteria just in time for the garbage collector to clean up your mess. Stuff like that can happen. EDIT: Corrected my mistake about garbage collectors. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/214730', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/93536/']} | jdg_379880 |
stackexchange | llm_judgeable_groundtruth_similarity | 3484145 |
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:
Scrolling through old discrete mathematics exams I have came across this "choose correct answer" question: $16!$ is: a). $20 \; 922 \; 789 \; 888 \; 000$ b). $18 \; 122 \; 471 \; 235 \; 500$ c). $17 \; 223 \; 258 \; 843 \; 600$ Would you show me how your thinking process of solving this problem would look like? The ultimate goal is to find the correct answer; how you get to it does not matter, except that you have to invest only a reasonable amount of time, and calculators or other devices are not allowed.
Now provide the response and nothing else.
| $16!$ is divisible by $125$ since it's divisible by $5\times10\times15$ , and by $8$ , since it's divisible by $2\times4$ . Therefore, $16!$ must be a multiple of $1000$ , and the only acceptable choice is a). | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3484145', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/617563/']} | jdg_379881 |
stackexchange | llm_judgeable_groundtruth_similarity | 12465521 |
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 building a simple blog using Jekyll, and I'm pulling my hair out trying to figure out this problem. The index page of the site is meant to feature a single, most recent article, with the structure looking something like below (pardon the mess): {% for post in site.posts reversed limit:1 %} <div class="post"> <div class="post-inner"> <h3 class="posttitle"><a href="{{ post.url }}">{{ post.title }}</a></h3> <p class="postdate">{{ post.date | date: "%d %B %Y" }}</p> {{ post.content }} <a href="{{ post.url }}#disqus_thread" class="commentLink"></a> </div> </div>{% endfor %} The above template works perfectly fine when the limit is not restrictive (i.e does not exist or is set to the length of the array). It seems to only be when the limit is actually restricting the result that the loop ignores reversed. I've tried clearing the browser cache, which is what got it working without limit:1, but the progress ends there. Thanks for the help, and I would be happy to provide more detail if this is not enough.
Now provide the response and nothing else.
| What is Jekyll actually outputting for you? From what I understand, the reversed filter is applied last. So let assume you posted the first 15 days of Aug, and lets also say you do something like this: {% for post in site.posts limit:5 %} {{ post.content }}{% endfor %} You post array would be ordered in the following pattern [Aug 15, Aug 14, Aug 13, Aug 12, Aug 11] And then if you reversed it {% for post in site.posts reversed limit:5 %} {{ post.content }}{% endfor %} You post array would be ordered in the following pattern [Aug 11, Aug 12, Aug 13, Aug 14, Aug 15] With all that said, I'm a little perplexed as to why you are not using {% for post in site.posts limit:1 %} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12465521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1171957/']} | jdg_379882 |
stackexchange | llm_judgeable_groundtruth_similarity | 1365748 |
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 Program{ static void Main(string[] args) { List<Book> books = new List<Book> { new Book { Name="C# in Depth", Authors = new List<Author> { new Author { FirstName = "Jon", LastName="Skeet" }, new Author { FirstName = "Jon", LastName="Skeet" }, } }, new Book { Name="LINQ in Action", Authors = new List<Author> { new Author { FirstName = "Fabrice", LastName="Marguerie" }, new Author { FirstName = "Steve", LastName="Eichert" }, new Author { FirstName = "Jim", LastName="Wooley" }, } }, }; var temp = books.SelectMany(book => book.Authors).Distinct(); foreach (var author in temp) { Console.WriteLine(author.FirstName + " " + author.LastName); } Console.Read(); }}public class Book{ public string Name { get; set; } public List<Author> Authors { get; set; }}public class Author{ public string FirstName { get; set; } public string LastName { get; set; } public override bool Equals(object obj) { return true; //if (obj.GetType() != typeof(Author)) return false; //else return ((Author)obj).FirstName == this.FirstName && ((Author)obj).FirstName == this.LastName; }} This is based on an example in "LINQ in Action". Listing 4.16. This prints Jon Skeet twice. Why? I have even tried overriding Equals method in Author class. Still Distinct does not seem to work. What am I missing? Edit:I have added == and != operator overload too. Still no help. public static bool operator ==(Author a, Author b) { return true; } public static bool operator !=(Author a, Author b) { return false; }
Now provide the response and nothing else.
| LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here . If you modify your Author class like so it should work. public class Author : IEquatable<Author>{ public string FirstName { get; set; } public string LastName { get; set; } public bool Equals(Author other) { if (FirstName == other.FirstName && LastName == other.LastName) return true; return false; } public override int GetHashCode() { int hashFirstName = FirstName == null ? 0 : FirstName.GetHashCode(); int hashLastName = LastName == null ? 0 : LastName.GetHashCode(); return hashFirstName ^ hashLastName; }} Try it as DotNetFiddle | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1365748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1312208/']} | jdg_379883 |
stackexchange | llm_judgeable_groundtruth_similarity | 8940922 |
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 create such application in android which will be activated when i press sleep or power button twice , is it possible to do that , by running an application in background and listening events from power button ? some times phone gets into sleep mode once it is idle , and to use any application user has to presssleep button and then he has to enter certain password to activate the phone. But i want to make make it activate my application when a power button is clicked without any other intervention
Now provide the response and nothing else.
| You can try this trick . Register a Broadcast Receiver which is initiated when powerbutton is clicked.Now in OnReceive method of the Receiver do what you want. For example: in manifest file register a receiver: <receiver android:name="com.test.check.MyReceiver"> <intent-filter> <action android:name="android.intent.action.SCREEN_OFF"></action> <action android:name="android.intent.action.SCREEN_ON"></action> <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action> <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action> <action android:name="android.intent.action.ACTION_SHUTDOWN"></action> </intent-filter> </receiver> && in onReceive() method of the Receiver public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub Log.v("#@%@%#", "Power button is pressed."); Toast.makeText(arg0, "power button clicked",Toast.LENGTH_LONG).show(); //perform what you want here }} Now perform any operation in onReceive() method of the Receiver. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8940922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405383/']} | jdg_379884 |
stackexchange | llm_judgeable_groundtruth_similarity | 24177601 |
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 understanding that AsyncAppender do the appending job in a separate thread. They use ArrayBlockingQueue for this purpose. AND AsyncLogger uses LMAX disruptor library to move logging event from one application thread to the other thread and it is faster as compared to AsyncAppender. My question is why do we have AsyncAppender in log4j2 if the job it does is achieved by AsyncLogger more efficiently. What if we use AsyncAppender along with AsyncLogger ? Are there any more differences between AsyncLogger and AsyncAppender?
Now provide the response and nothing else.
| True, they achieve pretty much the same purpose, so I can understand your question: "why have both options"? For background, the AsyncAppender has been in Log4j2 from the beginning, where Async Loggers were added in March last year (2014). That's how the current situation came to be. The log4j team is not seriously considering removing the AsyncAppender at the moment. One thing to keep in mind is that Async Loggers have an external dependency (the LMAX disruptor jar) where the AsyncAppender works with just the log4j2-api and log4j2-core jars. To answer your last question, it is possible to combine AsyncAppender with Async Loggers, but you will not gain anything. This has not been tested. I haven't checked but it is possible that there is a problem with location information getting lost when handing over the log event from the Async Logger thread to the AsyncAppender thread. I would not recommend doing this. UPDATE (2014/6/23): I did some testing and there were a few issues with combining AsyncAppender with AsyncLoggers. These are fixed in RC2. I still don't recommend doing this, as it just adds another intermediate step that uses CPU/memory without contributing anything. UPDATE (2016/7/20): Another difference: since version 2.6, Log4j 2 can be garbage-free with Async Loggers, but not with AsyncAppender. In answer to your second question in the comments below: AsyncAppender has its own queue and thread, where AsyncLoggers use the LMAX Disruptor ringbuffer for a queue and uses an Executor thread. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24177601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/653482/']} | jdg_379885 |
stackexchange | llm_judgeable_groundtruth_similarity | 25453871 |
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 class: class Person { public Person(string firstName, string lastName) { _firstName = FirstName; _lastName = lastName; } private readonly string _firstName; // Make it really immutable public string FirstName { get { return _firstName; } } private readonly string _lastName; // Make it really immutable public string LastName { get { return _lastName; } }} Can be rewritten in C# version 6.0 with a primary constructor as: class Person(string firstName, string lastName){ public string FirstName { get; } = firstName; public string LastName { get; } = lastName;} Is it possible to give the primary constructor a different modifier like in the following class? abstract class Person { protected Person(string firstName, string lastName) { _firstName = FirstName; _lastName = lastName; } private readonly string _firstName; // Make it really immutable public string FirstName { get { return _firstName; } } private readonly string _lastName; // Make it really immutable public string LastName { get { return _lastName; } }}
Now provide the response and nothing else.
| EDIT: This answer talks about pre-release version of C# 6.0. The final release version of C# 6.0 doesn't have primary constructors at all. The Language Design Notes for 21 April say (and I didn't find any later reference to this): Separate accessibility on type and primary constructor There are scenarios where you don’t want the constructors of your type to have the same accessibility as the type. A common case is where the type is public, but the constructor is private or protected, object construction being exposed only through factories. Should we invent syntax so that a primary constructor can get a different accessibility than its type? Conclusion No. There is no elegant way to address this. This is a fine example of a scenario where developers should just fall back to normal constructor syntax. With the previous decisions above, we’ve done our best to make sure that that cliff isn’t too steep. So, no, there is no way to declare the primary constructor as protected . Though, as was already pointed out, there is no difference between public and protected constructor for an abstract class. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25453871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333374/']} | jdg_379886 |
stackexchange | llm_judgeable_groundtruth_similarity | 1689682 |
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 integral is from P. Nahin's "Inside Interesting Integrals...", problem C2.1. His proposed solution includes trigonometric substitution and the use of log-sine integral. However, I think the problem should have an easier solution (without appealing to another complicated integral at least). I have the following trick in mind. Let's introduce the substitution $x=4-z$ $$I=\int_0^4 \frac{\ln x}{\sqrt{4x-x^2}}~dx=\int_0^4 \frac{\ln (4-z)}{\sqrt{4z-z^2}}~d(4-z)=\int_0^4 \frac{\ln (4-z)}{\sqrt{4z-z^2}}~dz$$ $$2I=\int_0^4 \frac{\ln (4x-x^2)}{\sqrt{4x-x^2}}~dx$$ $$I=\int_0^4 \frac{\ln \sqrt{4x-x^2}}{\sqrt{4x-x^2}}~dx$$ And here I'm stuck. I'm not sure if this can go somewhere. Maybe partial integration can help, but I don't know how to choose the functions. What do you think? Here is a question about this integral . Only one answer does not use trig substitution, it used gamma function instead. If there are no other ways, I'm prepared to give up on my question. But I would be grateful if it's left open at least for several days Edit After many attempts, I conclude that there is no trick to this integral. The reason is: the general form of this integral in not zero, but has the same symmetry properties, as the above case: $$I(a)=\int_0^a \frac{\ln x}{\sqrt{ax-x^2}}~dx=\int_0^a \frac{\ln (a-x)}{\sqrt{ax-x^2}}~dx=\int_0^a \frac{\ln \sqrt{ax-x^2}}{\sqrt{ax-x^2}}~dx \neq 0$$ $$I(4)=0$$ So we will get nothing from symmetry considerations alone. There are two possible ways to solve this - either trigonometric substitution or gamma function. Edit 2 I was wrong it seems, see the accepted answer.
Now provide the response and nothing else.
| Notice that by the substitution $x = 2 + u$, $$ I = \int_{-2}^{2} \frac{\log(2 + u)}{\sqrt{4 - u^2}} \, du = \int_{0}^{2} \frac{\log(4 - u^2)}{\sqrt{4 - u^2}} \, du. $$ On the other hand, by the substitution $x = 4 - v^2$ (or equivalently $v = \sqrt{4 - x}$), we have $$ I = \int_{0}^{2} \frac{\log(4 - v^2)}{v \sqrt{4 - v^2}} \cdot 2v \, dv = 2 \int_{0}^{2} \frac{\log(4 - v^2)}{\sqrt{4 - v^2}} \, dv. $$ Comparing two formulas give $I = 2I$ and therefore $I = 0$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1689682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/269624/']} | jdg_379887 |
stackexchange | llm_judgeable_groundtruth_similarity | 29887 |
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:
Suppose a vector space V is defined on a field F. Does this at all imply that V is also defined on all fields, or does it only dictate that V is defined on F (and could also work with other fields if proven)? I realize it's sort of silly to assume anything in math, but my confusion comes from examples of vector spaces that I've seen, such as n-tuples of a field with coordinate-wise addition and scalar multiplication holding for any arbitrary field. Thanks a lot.
Now provide the response and nothing else.
| A priori , if we have an abelian group $V$ (the abelian group structure provides the addition of a vector space), and we give it the structure of a vector space over a field $F$, then we only know how to make $V$ a vector space over $F$, and over any subfield of $F$. This is because when we give $V$ the structure of a vector space over $F$, the information we have specified is how to multiply elements of $V$ by elements of $F$. If $L\subset F$ is a subfield of $F$, then we already know how to define multiplication of elements of $V$ by elements of $L$: elements of $L$ are also elements of $F$, and we just use our definition for them! For example, the collection of ordered pairs of complex numbers, $V=\mathbb{C}^2$, is an abelian group under the usual addition$$(\alpha_1,\alpha_2)+(\beta_1,\beta_2)=(\alpha_1+\beta_1,\alpha_2+\beta_2) \text{ for all }(\alpha_1,\alpha_2),(\beta_1,\beta_2)\in V.$$It can be given the structure of a vector space over $\mathbb{C}$ by defining$$\lambda(\alpha_1,\alpha_2)=(\lambda\alpha_1,\lambda\alpha_2)\text{ for all }\lambda\in\mathbb{C},\,\,(\alpha_1,\alpha_2)\in V.$$But, now that we've done that, it is also a vector space over $\mathbb{R}$, which is a subfield of $\mathbb{C}$ - we know how to multiply elements of $V$ by real numbers because we already have specified how to multiply by complex numbers. However, the abelian group $V$ cannot be given the structure of a vector space over $\mathbb{Z}/p\mathbb{Z}$ where $p$ is a prime number, which is a field that is not a subfield of $\mathbb{C}$. This is because we would have to have $$p\cdot (\alpha_1,\alpha_2)=(p\alpha_1,p\alpha_2)=0$$ for any $(\alpha_1,\alpha_2)\in V$, which is false. Finally, I would point out that even if $L$ is not a subfield of $F$, that doesn't prevent $V$ from also being able to be given the structure of a vector space over $L$. In our example of $V=\mathbb{C}^2$, suppose we had originally specified that $V$ was to be considered as a vector space over $\mathbb{R}$. That is, suppose we had said, "Here is our abelian group $V=\mathbb{C}^2$, and we make it into a vector space over $\mathbb{R}$ by defining$$c(\alpha_1,\alpha_2)=(c\alpha_1,c\alpha_2)\text{ for all }c\in\mathbb{R},\,\,(\alpha_1,\alpha_2)\in V."$$This wouldn't change the fact that it can also be given the structure of a vector space over $\mathbb{C}$, in a way that agrees with the original structure over $\mathbb{R}$, even though $\mathbb{C}$ is a larger field than $\mathbb{R}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/29887', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8871/']} | jdg_379888 |
stackexchange | llm_judgeable_groundtruth_similarity | 3435355 |
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 do sth. like this: foo=(a b c)foo-=becho $foo # should output "a c" How can I remove an entry from an array? foo-=b does not work. The removal should work no matter where the entry is.
Now provide the response and nothing else.
| To remove element number $i : a=("${(@)a[1,$i-1]}" "${(@)a[$i+1,$#a]}") (The simpler construct a=($a[1,$i-1] $a[$i+1,-1]) also removes empty elements.) ADDED: To remove any occurence of b : a=("${(@)a:#b}") :# is the hieroglyph to remove matching elements; "" and (@) is to operate correctly on arrays even if they contain empty elements. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3435355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133374/']} | jdg_379889 |
stackexchange | llm_judgeable_groundtruth_similarity | 178728 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The following appears naturally in a certain context: Let $P$ be a graded partially ordered set. Let $M$ be the subset of minimal elements of $P$. Define subsets $E_i$ inductively as follows: First, let $E_0:=M$. Then, if $|E_i|\leq 1$, set $E_{i+1}=\emptyset$. Otherwise, for each incomparable pair $x\neq y$ in $E_i$, consider the minimal elements $z$ with $x<z>y$ and put them into the set $E_{i+1}$. This defines $E_{i+1}$ out of $E_i$. Finally, set $E=E_0\cup E_1\cup E_2\cup ...$. Questions: Is there a more conceptual definition of the subposet $E$? Does it have a universal property making somehow clear why it is defined like above? Is it a well-known construction in the theory of posets? Does it have a name?
Now provide the response and nothing else.
| The identity $np(n) = \sum_{m=1}^n p(n-m)\sigma(m)$, where $\sigma(m)$ is the sum of divisors of $n$ generalizes to this setting. The proof I sketched here shows that $$ nF(n) = \sum_{r=1}^n F(n-r) g(r) $$ where $$ g(r) = \sum_{m \mid r} f(m)^{r/m} m. $$ This should give a more efficient algorithm: first compute the values of $g(r)$ for $r \le N$. Then use the first formula to compute $F(n)$ iteratively for $n \le N$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/178728', 'https://mathoverflow.net', 'https://mathoverflow.net/users/27923/']} | jdg_379890 |
stackexchange | llm_judgeable_groundtruth_similarity | 8760419 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I have a column with separated values, I can use the unnest() function: myTableid | elements---+------------1 |ab,cd,efg,hi2 |jk,lm,no,pq3 |rstuv,wxyzselect id, unnest(string_to_array(elements, ',')) AS elemfrom myTableid | elem---+-----1 | ab1 | cd1 | efg1 | hi2 | jk... How can I include element numbers? I.e.: id | elem | nr---+------+---1 | ab | 11 | cd | 21 | efg | 31 | hi | 42 | jk | 1... I want the original position of each element in the source string. I've tried with window functions ( row_number() , rank() etc.) but I always get 1 . Maybe because they are in the same row of the source table? I know it's a bad table design. It's not mine, I'm just trying to fix it.
Now provide the response and nothing else.
| Postgres 9.4 or later Use WITH ORDINALITY for set-returning functions: When a function in the FROM clause is suffixed by WITH ORDINALITY , a bigint column is appended to the output which starts from 1 andincrements by 1 for each row of the function's output. This is mostuseful in the case of set returning functions such as unnest() . In combination with the LATERAL feature in pg 9.3+ , and according to this thread on pgsql-hackers , the above query can now be written as: SELECT t.id, a.elem, a.nr FROM tbl AS tLEFT JOIN LATERAL unnest(string_to_array(t.elements, ',')) WITH ORDINALITY AS a(elem , nr ) ON true; LEFT JOIN ... ON true preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL : SELECT t.id, a.elem, a.nrFROM tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr); Or simpler if based off an actual array ( arr being an array column): SELECT t.id, a.elem, a.nrFROM tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr); Or even, with minimal syntax: SELECT id, a, ordinalityFROM tbl, unnest(arr) WITH ORDINALITY a; a is automatically table and column alias. The default name of the added ordinality column is ordinality . But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns. Postgres 8.4 - 9.3 With row_number() OVER (PARTITION BY id ORDER BY elem) you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string. You can simply omit ORDER BY : SELECT *, row_number() OVER (PARTITION by id) AS nrFROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t; While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY . It happens to work due to an implementation detail. To guarantee ordinal numbers of elements in the blank-separated string : SELECT id, arr[nr] AS elem, nrFROM ( SELECT *, generate_subscripts(arr, 1) AS nr FROM (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t ) sub; Or simpler if based off an actual array : SELECT id, arr[nr] AS elem, nrFROM (SELECT *, generate_subscripts( arr , 1) AS nr FROM tbl) t; Related answer on dba.SE: How to preserve the original order of elements in an unnested array? Postgres 8.1 - 8.4 None of these features are available, yet: RETURNS TABLE , generate_subscripts() , unnest() , array_length() . But this works: CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer) RETURNS SETOF record LANGUAGE sql IMMUTABLE AS'SELECT $1[i], i - array_lower($1,1) + 1 FROM generate_series(array_lower($1,1), array_upper($1,1)) i'; Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function : CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int) RETURNS SETOF record LANGUAGE sql IMMUTABLE AS'SELECT $1[i], i - array_lower($1,1) + 1, i FROM generate_series(array_lower($1,1), array_upper($1,1)) i';SELECT id, arr, (rec).*FROM ( SELECT *, f_unnest_ord_idx(arr) AS rec FROM ( VALUES (1, '{a,b,c}'::text[]) -- short for: '[1:3]={a,b,c}' , (2, '[5:7]={a,b,c}') , (3, '[-9:-7]={a,b,c}') ) t(id, arr) ) sub; id | arr | val | ordinality | idx----+-----------------+-----+------------+----- 1 | {a,b,c} | a | 1 | 1 1 | {a,b,c} | b | 2 | 2 1 | {a,b,c} | c | 3 | 3 2 | [5:7]={a,b,c} | a | 1 | 5 2 | [5:7]={a,b,c} | b | 2 | 6 2 | [5:7]={a,b,c} | c | 3 | 7 3 | [-9:-7]={a,b,c} | a | 1 | -9 3 | [-9:-7]={a,b,c} | b | 2 | -8 3 | [-9:-7]={a,b,c} | c | 3 | -7 Compare: Normalize array subscripts so they start with 1 | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8760419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1095206/']} | jdg_379891 |
stackexchange | llm_judgeable_groundtruth_similarity | 4901125 |
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 know what is good practice for select option values. Example <select name="select"> <option value="0-9">Sample</option> <option value="a-z">Sample</option> <option value="this is sample value">Sample</option> <option value="this-is-sample-value">Sample</option> <option value="this_is_sample_value">Sample</option> <option value="this & is | sample ** value">Sample</option></select> I'm a little bit confused here. Is the select value same like input text and textarea
Now provide the response and nothing else.
| There are no limits real to the type of data that can be set in the value attribute of the option element. Characters with special meaning in HTML do, of course, need to be represented by the appropriate entities ( & as & for example (although the one in the question meets the "followed by a space character" exception to the rule)). The attribute is defined as containing CDATA: <!ELEMENT OPTION - O (#PCDATA) -- selectable choice --><!ATTLIST OPTION %attrs; -- %coreattrs, %i18n, %events -- selected (selected) #IMPLIED disabled (disabled) #IMPLIED -- unavailable in this context -- label %Text; #IMPLIED -- for use in hierarchical menus -- value CDATA #IMPLIED -- defaults to element content -- > — http://www.w3.org/TR/html4/interact/forms.html#h-17.6 CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows: Replace character entities with characters, Ignore line feeds, Replace each carriage return or tab with a single space. User agents may ignore leading and trailing white space in CDATA attribute values (e.g., " myval " may be interpreted as "myval"). Authors should not declare attribute values with leading or trailing white space. For some HTML 4 attributes with CDATA attribute values, the specification imposes further constraints on the set of legal values for the attribute that may not be expressed by the DTD. — http://www.w3.org/TR/html4/types.html#type-cdata The specification doesn't impose additional limits for the option element's value attribute. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4901125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106111/']} | jdg_379892 |
stackexchange | llm_judgeable_groundtruth_similarity | 42929809 |
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 block of code I want to store in a variable so I could make it into a PDF using dompdf $html = '<div class="receiptContainer"> <center> <img src="Images/logo.png" width="175px"> <h4>GOKUJOU JAPANESE RESTAURANT</h4> <p>Total Gas Station, Hibbard Ave., Looc,<br>Dumaguete City, 6200 Negros Oriental, Philippines <br> 09985555175 | 422-1435 <br> <?php echo date("Y-m-d h:i:sA"); ?> </p> <table width="90%" style="text-align: center;"> <tr> <th>DESCRIPTION</th> <th>QTY</th> <th>PRICE</th> <th>TOTAL</th> </tr> <tr> <td></td> </tr> <?php $query = mysqli_query($con, "SELECT * FROM orders WHERE customerID = '".$_SESSION['customer']."' AND status = '"Checked Out"'"); while($row = mysqli_fetch_row($query)){ ?> <tr> <td><?php echo $row[3]; ?></td> <td><?php echo $row[5]; ?></td> <td><?php echo $row[4]; ?></td> <td><?php echo $row[6]; ?></td> </tr> <?php } $total = mysqli_query($con, "SELECT SUM(total) AS grandTotal FROM orders WHERE customerID = '".$_SESSION['customer']."' AND status = '"Checked Out"' GROUP BY customerID"); $row = mysqli_fetch_row($total); $sum = $row[0]; ?> <tr> <!-- break space --> <tr></tr><tr></tr><tr></tr><tr></tr> <tr></tr><tr></tr><tr></tr><tr></tr> <tr></tr><tr></tr><tr></tr><tr></tr> <td colspan="1" style="text-align: left">GRAND TOTAL: <?php echo $sum; ?></td> <td colspan="3"></td> </tr> <tr style="text-align: left"> <td colspan="1">CASH: <?php echo $_SESSION['"cash"']; ?></td> <td colspan="3"></td> </tr> <tr style="text-align: left"> <td colspan="1">CHANGE: <?php echo $_SESSION['"cash"'] - $sum; ?></td> <td colspan="3"></td> </tr> </table> </center> </div>';//start PDF generation$dompdf = new Dompdf();$dompdf->loadHTML($html);$dompdf->setPaper(array(0, 0, 1080, 500), 'landscape');$dompdf->render();$dompdf->stream("samplepdf");?> This how I structured my code, and it returns me an error: Parse error: syntax error, unexpected '"' in C:\xampp\htdocs\Gokujou\checkout.php on line 107 and this is line 107: $query = mysqli_query($con, "SELECT * FROM orders WHERE customerID = '".$_SESSION['customer']."' AND status = '"Checked Out"'"); How do I concatenate this MySQL statement properly?
Now provide the response and nothing else.
| What is it that we win by adding std::optional over just using std::shared_ptr in general? Let's say you need to return a symbol from a function with flag "not a value". If you would use std::shared_ptr for that you would have huge overhead - char would be allocated in dynamic memory, plus std::shared_ptr would maintain control block. While std::optional on another side: If an optional contains a value, the value is guaranteed to beallocated as part of the optional object footprint, i.e. no dynamicmemory allocation ever takes place. Thus, an optional object models anobject, not a pointer, even though the operator*() and operator->()are defined. so no dynamic memory allocation is involved and difference comparing even to the raw pointer could be significant. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42929809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7685225/']} | jdg_379893 |
stackexchange | llm_judgeable_groundtruth_similarity | 54043691 |
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 running kubernetes v1.11.5 and I'm installing helm with a tiller deployment for each namespace. Let's focus on a single namespace. This is the tiller service account configuration: ---apiVersion: v1kind: ServiceAccountmetadata: name: tiller namespace: marketplace-int---kind: RoleapiVersion: rbac.authorization.k8s.io/v1metadata: name: tiller-manager namespace: marketplace-intrules:- apiGroups: - "" - extensions - apps - rbac.authorization.k8s.io - roles.rbac.authorization.k8s.io - authorization.k8s.io resources: ["*"] verbs: ["*"]---kind: RoleBindingapiVersion: rbac.authorization.k8s.io/v1metadata: name: tiller-binding namespace: marketplace-intsubjects:- kind: ServiceAccount name: tiller namespace: marketplace-introleRef: kind: Role name: tiller-manager apiGroup: rbac.authorization.k8s.io When I try to deploy a chart I get this error: Error: release citest failed: roles.rbac.authorization.k8s.io "marketplace-int-role-ns-admin" is forbidden: attempt to grant extra privileges: [{[*] [*] [*] [] []}] user=&{system:serviceaccount:marketplace-int:tiller 5c6af739-1023-11e9-a245-0ab514dfdff4 [system:serviceaccounts system:serviceaccounts:marketplace-int system:authenticated] map[]} ownerrules=[{[create] [authorization.k8s.io] [selfsubjectaccessreviews selfsubjectrulesreviews] [] []} {[get] [] [] [] [/api /api/* /apis /apis/* /healthz /openapi /openapi/* /swagger-2.0.0.pb-v1 /swagger.json /swaggerapi /swaggerapi/* /version /version/]} {[*] [ extensions apps rbac.authorization.k8s.io roles.rbac.authorization.k8s.io authorization.k8s.io] [*] [] []}] ruleResolutionErrors=[] The error comes when trying to create rbac config for that namespace (with tiller sa): # Source: marketplace/templates/role.yamlapiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata: labels: app: citest chart: marketplace-0.1.0 heritage: Tiller release: citest namespace: marketplace-int name: marketplace-int-role-ns-adminrules: - apiGroups: ["*"] resources: ["*"] verbs: ["*"] The error message clearly says that the tiller service account doesn't have permission for roles.rbac.authorization.k8s.io but that permission is granted as showed previously. $kubectl describe role tiller-managerName: tiller-managerLabels: <none>Annotations: kubectl.kubernetes.io/last-applied-configuration: {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"annotations":{},"name":"tiller-manager","namespace":"marketplace-i...PolicyRule: Resources Non-Resource URLs Resource Names Verbs --------- ----------------- -------------- ----- * [] [] [*] *.apps [] [] [*] *.authorization.k8s.io [] [] [*] *.extensions [] [] [*] *.rbac.authorization.k8s.io [] [] [*] *.roles.rbac.authorization.k8s.io [] [] [*] Honestly, I don't fully understand the error message to check if the ownerrules are fine and I'm trying to find out what does it means this kind of messages that seems to be related with the role description: {[*] [*] [*] [] []} Any clue about what permissions I am missing?
Now provide the response and nothing else.
| This is due to permission escalation prevention in RBAC. See https://kubernetes.io/docs/reference/access-authn-authz/rbac/#privilege-escalation-prevention-and-bootstrapping for details. Permission to create a role object is necessary, but not sufficient. A user can only create/update a role if at least one of the following things is true: they already have all the permissions contained in the role, at the same scope as the object being modified (cluster-wide for a ClusterRole, within the same namespace or cluster-wide for a Role). In your case, that would mean the user attempting to create the role must already have apiGroups=*, resources=*, verbs=* permissions within the namespace where it is attempting to create the role. You can grant this by granting the cluster-admin clusterrole to the serviceaccount within that namespace with a rolebinding. they are given explicit permission to perform the "escalate" verb on the roles or clusterroles resource in the rbac.authorization.k8s.io API group (Kubernetes 1.12 and newer) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54043691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1023780/']} | jdg_379894 |
stackexchange | llm_judgeable_groundtruth_similarity | 14486370 |
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 starting a flask project, and in my code I have from flask import Flask, render_template, abortapp = Flask(__name__) Now what exactly is app ? I am following this guide and I am particularly confused about the structure because he has chosen to have directory named app/ and is his app/__init__.py he has from flask import Flaskapp = Flask(__name__)from app import views and in his app/views.py he has from app import app What the hell is it with all these app 's?!
Now provide the response and nothing else.
| I think the main confusion is in the line: from app import app You have a python package (a folder with __init__.py file) named "app". From this folder, you are now importing the variable "app" that you defined below in __init__.py file: app = Flask(__name__) Rename the folder from app to say "myproject". Then you will call from myproject import app Also, you will import views as from myproject import views | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14486370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/721768/']} | jdg_379895 |
stackexchange | llm_judgeable_groundtruth_similarity | 3797865 |
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:
This problem is very similar to a popular one, but I found it in this way. I thought it could be solved in a similar manner. This means that $x$ has to be an even number, and then it holds $$615=y^2-2^{2k}=(y-2^k)(y+2^k)$$ possible pair of factors of $615$ are $\{(615,1), (123, 5), (3,205),(15,41)\}$ . Then the way this problem is usually solved is by adding the 2 factors and finding the value for for $2^k$ . However this time I tried to susbstract the factors so I could find a possible value of $2^k$ , but this means we only have the 4 possibilities for the value of $2^k$ : $\{614, 118, 2020, 26\}$ . Which none are values for $2^k$ with $k\in\Bbb{Z}$ .Does this mean there are no integer solutions for this equation? or maybe there's something wrong with my reasoning. Thanks in advance! EDIT: I did not assume that $x$ is even, I should have elaborated on that. If $y^2$ is an integer, then the digit on the units place must be one of the followings: $\{1, 4, 5, 6, 9\}$ . Powers of 2 can only have the following digits on the units place: $\{2, 4, 6, 8\}$ . If $x$ is an odd number, then $2^x$ has either a $2$ or an $8$ as its units place, this in turn means that $y^2=615+2^x$ has either $7$ or $3$ on the units place, which is a contradiction. That's why $x$ must be an even number.
Now provide the response and nothing else.
| Suppose $x \geq 2$ . Reduce both sides mod 4 to get that $3 \equiv y^2$ , a contradiction since $0$ and $1$ are the only squares mod 4. Then the only possible choices are $x = 0$ and $x = 1$ . But neither $615 + 2^0$ nor $615 + 2^1$ is a perfect square. So there are no solutions. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3797865', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/485701/']} | jdg_379896 |
stackexchange | llm_judgeable_groundtruth_similarity | 7197922 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my page from an online radio station site of mine on localhost, it's a basic PHP/MySQL one for test purposes: <?phpmysql_connect('localhost', 'root', 'mypass') or die (mysql_error());mysql_select_db('radiotest') or die (mysql_error());$result = mysql_query("SELECT *, TIME_FORMAT(airtime, '%H:%i') `airtime` from presenters");//Table starting tag and header cellswhile($row = mysql_fetch_array($result)){//Display the results in different cellsecho "<dd><dl><img src=' " . $row['image'] . " '>" . $row['airtime'] ." " . $row['presenter'] . "</dd></dl>";echo "<dd><dl>" . $row['showinfo'] . "</dd></dl>";}?> It works properly, displays the data from the table in the required format. However, I want to try doing it this way: <dd><dl><img src='<?php echo $row['image'] ?'> <?php echo $row['airtime']?> <?php echo. $row['presenter']?> </dd></dl> My problem: I admit I've forgotten how to do echo without displaying it in the PHP/MySQL query like above, so how can I ensure it displays the variables using echo without having to declare it in the MySQL connection? I know my original is correctly formatted, but I don't want it to have the echo variables after the while part of the syntax, I wanted to echo them within the dd / dl HTML (definition list). Basically, I'm just trying to brush up my skills in this area; had a look on Google but am not quite sure Any help is appreciated!
Now provide the response and nothing else.
| Short answer, you can't. Once the object has been created on Facebook's side its URL in Facebook's graph is fixed - the Likes and Comments are associated with that URL and object; you need that URL to be accessible by Facebook's crawler in order to maintain that object in the future. (note that the object becoming inaccessible doesn't necessarily remove it from Facebook, but effectively you'd be starting over) What I usually recommend here is (with examples http://www.example.com/oldurl and http://www.example.com/newurl ): On /newpage, keep the og:url tag pointing to /oldurl Add a HTTP 301 redirect from /oldurl to /newurl Exempt the Facebook crawler from this redirect Continue to serve the meta tags for the page on http://www.example.com/oldurl if the request comes from the Facebook crawler. No need to return any actual content to the crawler, just a simple HTML page with the appropriate tags Thus: Existing instances of the object on Facebook will, when clicked, bring users to the correct (new) page via your redirect The Like button on the (new) page will still produce a like of the correct object (but at the old URL) If you're moving a lot of URLs around or completely rewriting your URL scheme you should use the new URLs for new articles/products/etc, but you'll need to keep the redirect in place if you want to retain likes, comments, etc on the older content. This includes if you're changing domain. The only problem here is maintaining the old URL -> new URL mapping somewhere in your code, but it's not technically difficult, just an additional thing to maintain in the future. BTW, The Facebook crawler UA is currently facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7197922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913061/']} | jdg_379897 |
stackexchange | llm_judgeable_groundtruth_similarity | 45291508 |
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's the best way to style a react-select component's ( https://github.com/JedWatson/react-select ) options? I can target the select itself just fine, with something like: ...import Select from 'react-select'...const styles = { fontSize: 14, color: 'blue',}<Select options={[1,2,3,4]} placeholder={'Select something'} clearable={false} style={styles.select}/> The problem is, the actual options when the select is expanded remain styled as the default. How can I target these options for styling? Here is an example of what I'm talking about. I can style the placeholder, but not the options:
Now provide the response and nothing else.
| react select v2 (update) This new version introduces a new styles-api and some other major changes. Custom Styles Style individual components with custom css using the styles prop. const colourStyles = { control: styles => ({ ...styles, backgroundColor: 'white' }), option: (styles, { data, isDisabled, isFocused, isSelected }) => { const color = chroma(data.color); return { ...styles, backgroundColor: isDisabled ? 'red' : blue, color: '#FFF', cursor: isDisabled ? 'not-allowed' : 'default', ... }; }, ...};export default () => ( <Select defaultValue={items[0]} label="Single select" options={items} styles={colourStyles} />); Now there is better documentation and more clear examples on the project's website: https://react-select.com/upgrade-guide#new-styles-api https://react-select.com/home#custom-styles https://react-select.com/styles#styles react-select v1 ( old answer - deprecated ) Custom classNames You can provide a custom className prop to the component, which will be added to the base .Select className for the outer container. The built-in Options renderer also support custom classNames. Add your custom className as a property to objects in the options array: const options = [ {label: "one", value: 1, className: 'custom-class'}, {label: "two", value: 2, className: 'awesome-class'} // more options...];...<Select options={options} /> MenuRender The menuRenderer property can be used to override the default drop-down list of options. optionClassName String The className that gets used for options Example: react-select/master/src/utils/defaultMenuRenderer.js | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45291508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3483022/']} | jdg_379898 |
stackexchange | llm_judgeable_groundtruth_similarity | 680981 |
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 have a main directory with 100 .mp4 files. I also have a set of sub-directories that goes dir_1, dir_2, dir_3 , etc, up to 100. What I want do is to loop through the main directory and distribute the .mp4 files to all the subfolders, each having only one. Then, there should be two loops or one loop with two variables, whichever one is possible. This is approximately what I'm trying to achieve in a single line of code. for file in *.mp4 & x in {1..100}; do mv $file dir_$x; done
Now provide the response and nothing else.
| set -- *.mp4for dir in dir_*/; do mv -- "$1" "$dir" shiftdone This first assigns the names of all the MP4 files to the list of positional parameters using set . It then iterates over the directories matching the pattern dir_*/ . For each directory, it moves the first MP4 file from the list of positional parameters into that directory, and then shifts that MP4 file off the list. There is no check to verify that there are as many directories as MP4 files in the above code. Would you want that, you could do set -- *.mp4for dir in dir_*/; do if [ "$#" -eq 0 ]; then echo 'Ran out of MP4 files' >&2 exit 1 fi mv -- "$1" "$dir"doneif [ "$#" -ne 0 ]; then echo 'Too many MP4 files' >&2 exit 1fi This code would work in any sh -like POSIX shell. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/680981', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/300737/']} | jdg_379899 |
stackexchange | llm_judgeable_groundtruth_similarity | 2328205 |
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:
Evaluate $$\int_{|z|=1} \frac{z+\overline{z}}{(z-z_0)^2}$$ Where $|z_0|\neq 1$ On the unit circle the integral is:$$\int_{|z|=1} \frac{z+\frac{1}{z}}{(z-z_0)^2}=\int_{|z|=1} \frac{z^2+1}{z(z-z_0)^2}$$ Now we have to look at different cases: $|z_0|>1$ $|z_0|<1$ $z_0=0$ In the case 1: $$\int_{|z|=1} \frac{z^2+1}{z(z-z_0)^2}=\int_{|z|=1} \frac{\frac{z^2+1}{z}}{(z-z_0)^2}$$ but $f(z)=\frac{z^2+1}{z}$ is not analytic at $z=0$ so how can we solve this?
Now provide the response and nothing else.
| This is a partial answer. This answer proves that if $n$ is an odd prime and $b\ge 2$ is an integer, then$$\sum_{k=1}^{n-1}\left(b^k-1\right)^{n-1}\equiv n \pmod{\frac{b^n-1}{b-1}}$$Proof : Let $N:=\frac{b^n-1}{b-1}$. By the binomial theorem,$$\begin{align}\sum_{k=1}^{n-1}\left(b^k-1\right)^{n-1}&=\sum_{k=1}^{n-1}\sum_{j=0}^{n-1}\binom{n-1}{j}(b^k)^{j}(-1)^{n-1-j}\\\\&=\sum_{j=0}^{n-1}\sum_{k=1}^{n-1}\binom{n-1}{j}(b^k)^{j}(-1)^{n-1-j}\\\\&=\sum_{k=1}^{n-1}\binom{n-1}{0}(b^k)^{0}(-1)^{n-1-0}+\sum_{j=1}^{n-1}\sum_{k=1}^{n-1}\binom{n-1}{j}(b^k)^{j}(-1)^{n-1-j}\\\\&=(n-1)\cdot (-1)^{n-1}+\sum_{j=1}^{n-1}\sum_{k=1}^{n-1}\binom{n-1}{j}(b^k)^{j}(-1)^{n-1-j}\tag1\end{align}$$ Since $n$ is an odd prime, we have $(-1)^{n-1}=1$, so $$\begin{align}(1)&=n-1+\sum_{j=1}^{n-1}\sum_{k=1}^{n-1}\binom{n-1}{j}(b^k)^{j}(-1)^{n-1-j}\\\\&=n-1+\sum_{j=1}^{n-1}\binom{n-1}{j}(-1)^{n-1-j}\sum_{k=1}^{n-1}(b^j)^{k}\tag2\end{align}$$ By the way, $$\sum_{k=1}^{n-1}(b^j)^{k}=\frac{(b^n)^{j}-b^j}{b^j-1}=\frac{((b-1)N+1)^j-b^j}{b^j-1}\tag3$$By the binomial thorem,$$\begin{align}(3)&=\frac{\left(\displaystyle\sum_{m=0}^{j}\binom{j}{m}(b-1)^mN^m\right)-b^j}{b^j-1}\\\\&=\frac{\left(\displaystyle\sum_{m=1}^{j}\binom{j}{m}(b-1)^mN^m\right)+1-b^j}{b^j-1}\\\\&=\frac{1-b^j}{b^j-1}+\frac{\displaystyle\sum_{m=1}^{j}\binom{j}{m}(b-1)^mN^m}{b^j-1}\\\\&=-1+\frac{\displaystyle\sum_{m=1}^{j}\binom{j}{m}(b-1)^mN^m}{b^j-1}\\\\&=-1+\frac{N}{b^j-1}\sum_{m=1}^{j}\binom{j}{m}(b-1)^{m}N^{m-1}\tag4\end{align}$$ Now, we use that if $n$ is an odd prime, then either $\gcd(N,b^j-1)=n$ and $b\equiv 1\pmod n$ or $\gcd(N,b^j-1)=1$ holds for $1\le j\le n-1$. (The proof is written at the end of this answer.) Case 1 : When $\gcd(N,b^j-1)=n$ with $b\equiv 1\pmod n$,$$\begin{align}(4)&=-1+\frac{N}{(b-1)(b^{j-1}+b^{j-2}+\cdots +b+1)}\sum_{m=1}^{j}\binom{j}{m}(b-1)^{m}N^{m-1}\\\\&=-1+\frac{N}{b^{j-1}+b^{j-2}+\cdots +b+1}\sum_{m=1}^{j}\binom{j}{m}(b-1)^{m-1}N^{m-1}\end{align}$$Now, since $b^{j-1}+b^{j-2}+\cdots +b+1\equiv j\not\equiv 0\pmod n$, we have that $$\frac{1}{b^j-1}\sum_{m=1}^{j}\binom{j}{m}(b-1)^{m}N^{m-1}=\frac{1}{b^{j-1}+b^{j-2}+\cdots +b+1}\sum_{m=1}^{j}\binom{j}{m}(b-1)^{m-1}N^{m-1}$$is an integer. Case 2 : When $\gcd(N,b^j-1)=1$, we have that $$\frac{1}{b^j-1}\sum_{m=1}^{j}\binom{j}{m}(b-1)^{m}N^{m-1}$$is an integer. So, in either case, we have$$(4)\equiv -1\pmod N\tag5$$ Therefore, from $(1)(2)(3)(4)(5)$, we have$$\begin{align}(1)&\equiv n-1-\sum_{j=1}^{n-1}\binom{n-1}{j}(-1)^{n-1-j}\qquad\pmod{N}\\\\&\equiv n-\sum_{j=0}^{n-1}\binom{n-1}{j}(-1)^{n-1-j}\cdot 1^j\qquad\pmod{N}\\\\&\equiv n-(1-1)^{j}\qquad \pmod{N}\\\\&\equiv n\qquad\pmod{N}\qquad\blacksquare\end{align}$$ Finally, let us prove that if $n$ is an odd prime and $b\ge 2$ is an integer, then either $\gcd(N,b^j-1)=n$ and $b\equiv 1\pmod n$ or $\gcd(N,b^j-1)=1$ holds for $1\le j\le n-1$ where $N=\frac{b^n-1}{b-1}$. Proof : Let $D=\gcd(N,b^j-1)$. Then, we have $b^n\equiv 1\pmod D$ and $b^j\equiv 1\pmod D$. Let $s$ be the smallest $t$ such that $b^t\equiv 1\pmod D$. There exist non-negative integers $u,r$ such that $n=us+r$ with $0\le r\lt s$. Then,$$1\equiv b^n=b^{us}\cdot b^r=(b^s)^u\cdot b^r\equiv b^r\implies r=0$$So, $n=us$. Similarly, there exists a non-negative integer $v$ such that $j=vs$. Since $\gcd(n,j)=1$, we have $s=1$ and $b\equiv 1\pmod D$. Now, $$0\equiv N=\frac{b^n-1}{b-1}=b^{n-1}+b^{n-2}+\cdots +b+1\equiv n\pmod D$$from which we have $D=1$ or $D=n$.$\qquad\blacksquare$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2328205', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103441/']} | jdg_379900 |
stackexchange | llm_judgeable_groundtruth_similarity | 22957205 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Depending on a variable, I need to select the SeedPositions32 or SeedPositions16 array for further use. I thought a pointer would allow this but I can't seed to make it work. How do you declare a pointer to a C++11 std::array? I tried the below. array<int>* ArrayPointer;//array<typedef T, size_t Size>* ArrayPointer;array<int,32> SeedPositions32 = {0,127,95,32,64,96,31,63,16,112,79,48,15,111,80, 47,41,72,8,119,23,104,55,87,71,39,24,7,56,88,103,120};array<int,16> SeedPositions16 = {...}
Now provide the response and nothing else.
| std::array has a template parameter for size. Two std::array template instantiations with different sizes are different types. So you cannot have a pointer that can point to arrays of different sizes (barring void* trickery, which opens its own can of worms.) You could use templates for the client code, or use std::vector<int> instead. For example: template <std::size_t N>void do_stuff_with_array(std::array<int, N> the_array){ // do stuff with the_array.}do_stuff_with_array(SeedPositions32);do_stuff_with_array(SeedPositions16); Note that you can also get a pointer to the data: int* ArrayPtr = SeedPositions32.data(); but here, you have lose the size information. You will have to keep track of it independently. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22957205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3399253/']} | jdg_379901 |
stackexchange | llm_judgeable_groundtruth_similarity | 26779846 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
im using nodejs and im trying to serve only html files (no jade, ejs ... engines). heres my entry point (index.js) code: var express = require('express');var bodyParser = require('body-parser');var app = express();app.set('port', (process.env.PORT || 5000));app.use(express.static(__dirname + '/public'));app.use(bodyParser.urlencoded({ extended: true}));app.use(bodyParser.json());app.use(express.static(__dirname + '/public'));app.get('*', function(req, res){ res.render('index.html');});app.listen(app.get('port'), function() {}); This is doing just fine when i hit the url "localhost:5000/", but when i try something like "localhost:5000/whatever" i got the following message: Error: Cannot find module 'html' im new to nodejs, but i want all routes to render the index.html file. How can i do that ??? Thank you.
Now provide the response and nothing else.
| You need to specify your view folder and parse the engine to HTML. var express = require('express');var bodyParser = require('body-parser');var app = express();app.set('port', (process.env.PORT || 5000));app.use(express.static(__dirname + '/public'));app.set('views', __dirname + '/public/views');app.engine('html', require('ejs').renderFile);app.set('view engine', 'html');app.use(bodyParser.urlencoded({ extended: true}));app.use(bodyParser.json());app.get('*', function(req, res){ res.render('index.html');});app.listen(app.get('port'), function() {}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26779846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2535096/']} | jdg_379902 |
stackexchange | llm_judgeable_groundtruth_similarity | 2042896 |
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$ be a random variable with positive integer range and finite mean. To show that $$E[X]= \sum_{k =0}^{\infty} P(X>k).$$ Proof: I showed using induction that $$\sum_{k=0}^n P(X>k) = \sum_{t=1}^n (t \cdot P(X=t)) + (n+1)P(X>n)$$If we apply $n \to \infty$, we would get the required result if if we show that as $n \to \infty$, $(n+1)P(X>n)$ tends to $0$. I'm having difficulty proving that. I know that $n \cdot P(X=n)$ tends to $0$ as $n \to \infty$ because $X$ has a finite mean. (PS: I do know this question is duplicate but in the previous question I didn't find any proof resembling this. Also to show that $(n+1)P(X>n)$ tends to 0 can be a separate question by itself.)
Now provide the response and nothing else.
| Note that $$n \mathbb{P}(X>n) = n \int_{\{X>n\}} \, d\mathbb{P} \leq n \int_{\{X>n\}} \frac{X}{n} \, d\mathbb{P}.$$ Since $X$ is intgrable, we can apply the dominated convergence theorem to conlude $$\lim_{n \to \infty} (n \mathbb{P}(X>n)) \leq \lim_{n \to \infty} \int_{\{X>n\}} X \, d\mathbb{P}=0.$$ Finally, using that $$\lim_{n \to \infty} \frac{n+1}{n} = 1$$ we get $$\lim_{n \to \infty} (n+1) \mathbb{P}(X>n)=0.$$ Remark: The above proof does not only work for integer-valued integrable random variables, but for any non-negative integrable random variable. For the particular case of integer-valued random variables, the proof can be reformulated as follows: Note that $$n \mathbb{P}(X>n) = n \sum_{k=n+1}^{\infty} \mathbb{P}(X=k) \leq n \sum_{k=n+1}^{\infty} \frac{k}{n} \mathbb{P}(X=k).$$ Since the expectation $\mathbb{E}(X) = \sum_{k=0}^{\infty} k \mathbb{P}(X=k)$ is finite, we get $$\lim_{n \to \infty} n \mathbb{P}(X>n) \leq \lim_{n \to \infty} \sum_{k=n+1}^{\infty} k \mathbb{P}(X=k)=0.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2042896', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/385655/']} | jdg_379903 |
stackexchange | llm_judgeable_groundtruth_similarity | 8496182 |
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 calculate a b mod n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it? unsigned long int decrypt2(int a,int b,int n){ unsigned long int res = 1; for (int i = 0; i < (b / 2); i++) { res *= ((a * a) % n); res %= n; } if (b % n == 1) res *=a; res %=n; return res;}
Now provide the response and nothing else.
| You can try this C++ code. I've used it with 32 and 64-bit integers. I'm sure I got this from SO. template <typename T>T modpow(T base, T exp, T modulus) { base %= modulus; T result = 1; while (exp > 0) { if (exp & 1) result = (result * base) % modulus; base = (base * base) % modulus; exp >>= 1; } return result;} You can find this algorithm and related discussion in the literature on p. 244 of Schneier, Bruce (1996). Applied Cryptography: Protocols, Algorithms, and Source Code in C, Second Edition (2nd ed.). Wiley. ISBN 978-0-471-11709-4. Note that the multiplications result * base and base * base are subject to overflow in this simplified version. If the modulus is more than half the width of T (i.e. more than the square root of the maximum T value), then one should use a suitable modular multiplication algorithm instead - see the answers to Ways to do modulo multiplication with primitive types . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8496182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1041299/']} | jdg_379904 |
stackexchange | llm_judgeable_groundtruth_similarity | 7783008 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
how to print an array in random order in java? example: int[] myArray = {5,4,3,2,1}; when printed, result should possibly be: 3 2 1 4 5 or 4 3 2 5 1
Now provide the response and nothing else.
| You should look at writing a Fisher-Yates shuffle . It's pretty easy to do, and efficient. Effectively you logically partition the array into a "shuffled" part and an "unshuffled part" - then repeatedly pick a random element from the unshuffled part and swap it with the first element from the unshuffled part, to make that part of the shuffled part. Alternatively, create a List<Integer> instead and then use Collections.shuffle . It's unfortunate that there isn't an equivalent for arrays, but Java's type system doesn't do terribly well in terms of making either arrays or primitives generic :( (I'm assuming you know how to do the printing side, and that it's the shuffling side which is the tricky bit for you.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7783008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/414930/']} | jdg_379905 |
stackexchange | llm_judgeable_groundtruth_similarity | 205768 |
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 first-order spectrum of a theory, is the set of cardinalities of its finite models. Finite models of Boolean algebras are informally n-dimensional cubes, therefore boolean algebra spectrum is the set of powers of 2. I have trouble proving it. One direction proof sketch seems easy. Cartesian product of two Boolean algebras is again Boolean algebra, so starting with 2-element boolean algebra we can inductively build the models of higher cardinalities. This is conceptually easy even though the actual proof machinery has to operate in terms of concrete axiom system of Boolean lattice or Boolean ring. How would one prove that no model with cardinality differing from power of 2 is legitimate? One way may be taking lattice perspective then, defining order relation, proving that it's grading order, go to atoms... This seems too cumbersome, and I'm not sure it would work. Is there an easier approach? Edit: two suggestions by Brian and Qiaochu (factoring by maximal filter in the lattice, or factoring by ideal in the ring) can be expanded into full proofs. I wonder about one more possibility: leveraging negation operation. Can negation be leveraged to factor Boolean algebra any meaningful way (it certainly partitions sets of elements into equal sets)?
Now provide the response and nothing else.
| HINT: Let $a\in B$ be an atom, and let $A=\{b\in B:a\le b\}$. Show that $A\cong B\setminus A$; if you think in terms of power set algebras, the isomorphism is pretty obvious. Use this to show that $B\cong 2\times A$. Essentially you’re factoring out a copy of $2$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/205768', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5754/']} | jdg_379906 |
stackexchange | llm_judgeable_groundtruth_similarity | 55038944 |
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 work with IntelliJ and when I run it in a web browser, it returns 503 error : Problem accessing / MySampleApplication.html. Reason: Service Unavailable"* The bug should be somewhere in the XML file and it seems to be something wrong with the servlet path. XML: <!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.8.0//EN" "http://gwtproject.org/doctype/2.8.0/gwt-module.dtd"><module rename-to="MySampleApplication"> <inherits name='com.google.gwt.user.User'/> <entry-point class='com.mySampleApplication.client.MySampleApplication'/> <servlet path='/MySampleApplicationService' class='com.mySampleApplication.server.ServiceImpl'/>> /></module> Console: Code server started in 12.55 s ms2019-03-06 13:09:20.410:INFO:oejs.Server:main: Started @13836msLoading modules com.mySampleApplication.MySampleApplication Validating <servlet> tags for module 'MySampleApplication' For additional info see: file:/Users/simonemettesorensen/Downloads/gwt-2.8.2/doc/helpInfo/servletMappings.html [WARN] Module declares a servlet class 'com.mySampleApplication.server.ServiceImpl' with a mapping to '/MySampleApplication/MySampleApplicationService', but the web.xml has no corresponding mapping; please add the following lines to your web.xml:<servlet-mapping> <servlet-name>com.mySampleApplication.MySampleApplication Service</servlet-name> <url-pattern>/MySampleApplication/MySampleApplicationService</url-pattern></servlet-mapping>2019-03-06 13:09:20.549:INFO:oejs.Server:main: jetty-9.2.z-SNAPSHOTStarting Jetty on port 8888 [WARN] Failed startup of context c.g.g.d.s.j.WebAppContextWithReload@41aa7994{/,file:/Users/simonemettesorensen/Library/Caches/IntelliJIdea2018.2/gwt/%C3%B8velsemedrpc.9e5e27b2/oevelseMedRPC.6c3e6f2f/run/www/,STARTING}{/Users/simonemettesorensen/Library/Caches/IntelliJIdea2018.2/gwt/øvelsemedrpc.9e5e27b2/oevelseMedRPC.6c3e6f2f/run/www}java.lang.NullPointerException at java.lang.String.compareTo(String.java:1155) at org.eclipse.jetty.servlet.ServletHolder.compareTo(ServletHolder.java:209) at org.eclipse.jetty.servlet.ServletHolder.compareTo(ServletHolder.java:70) at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:321) at java.util.ComparableTimSort.sort(ComparableTimSort.java:188) at java.util.Arrays.sort(Arrays.java:1246) at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:865) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:298) at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505) at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:550) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132) at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61) at org.eclipse.jetty.server.handler.RequestLogHandler.doStart(RequestLogHandler.java:140) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132) at org.eclipse.jetty.server.Server.start(Server.java:387) at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61) at org.eclipse.jetty.server.Server.doStart(Server.java:354) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:760) at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:636) at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:923) at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:706) at com.google.gwt.dev.DevMode.main(DevMode.java:432)2019-03-06 13:09:22.470:INFO:oejs.ServerConnector:main: Started ServerConnector@1006dd06{HTTP/1.1}{127.0.0.1:8888}2019-03-06 13:09:22.470:INFO:oejs.Server:main: Started @15896msDev Mode initialized. Startup URL: http://127.0.0.1:8888/MySampleApplication.html[ERROR] 503 - GET /MySampleApplication.html (127.0.0.1) 312 bytes Request Headers Host: 127.0.0.1:8888 Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: da-DK,da;q=0.9,en-US;q=0.8,en;q=0.7 Response headers Date: Wed, 06 Mar 2019 12:09:22 GMT Cache-Control: must-revalidate,no-cache,no-store Content-Type: text/html; charset=ISO-8859-1 Content-Length: 312 And if I add this, it won't run because of an unexpected error: "servlet mapping : <servlet-mapping> <servlet-name>com.mySampleApplication.MySampleApplication Service</servlet-name> <url-pattern>/MySampleApplication/MySampleApplicationService</url-pattern></servlet-mapping> I would really appreciate any help.
Now provide the response and nothing else.
| The default authentication mode for PostgreSQL is set to ident . You can access your pgpass.conf via pgAdmin -> Files -> open pgpass.conf That will give you the path of pgpass.conf at the bottom of the window ( official documentation ). After knowing the location, you can open this file and edit it to your liking. If that doesn't work, you can: Find your pg_hba.conf , usually located under C:\Program Files\PostgreSQL\9.1\data\pg_hba.conf If necessary, set the permissions on it so that you can modify it. Your user account might not be able to do so until you use the security tab in the properties dialog to give yourself that right by using an admin override. Alternately, find notepad or notepad++ in your start menu, right click, choose "Run as administrator" , then use File->Open to open pg_hba.conf that way. Edit it to set the "host" line for user "postgres" on host "127.0.0.1/32" to "trust". You can add the line if it isn't there; just insert host all postgres 127.0.0.1/32 trust before any other lines. (You can ignore comments, lines beginning with #). Restart the PostgreSQL service from the Services control panel ( start->run->services.msc ) Connect using psql or pgAdmin4 or whatever you prefer Run ALTER USER postgres PASSWORD 'fooBarEatsBarFoodBareFoot' Remove the line you added to pg_hba.conf or change it back Restart PostgreSQL again to bring the changes to effect. Here is an example of the pg_hba.conf file (METHOD is already set to trust ): # TYPE DATABASE USER ADDRESS METHOD# IPv4 local connections:host all all 127.0.0.1/32 trust# IPv6 local connections:host all all ::1/128 trust NOTE: Remember to change the METHOD back to md5 or other auth-methods listed here after changing your password (as stated above). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55038944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11159624/']} | jdg_379907 |
stackexchange | llm_judgeable_groundtruth_similarity | 15392272 |
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 been working on a project for some time, to detect and track (moving) vehicles in video captured from UAV's, currently I am using an SVM trained on bag-of-feature representations of local features extracted from vehicle and background images. I am then using a sliding window detection approach to try and localise vehicles in the images, which I would then like to track. The problem is that this approach is far to slow and my detector isn't as reliable as I would like so I'm getting quite a few false positives. So I have been considering attempting to segment the cars from the background to find the approximate position so to reduce the search space before applying my classifier, but I am not sure how to go about this, and was hoping someone could help? Additionally, I have been reading about motion segmentation with layers, using optical flow to segment the frame by flow model, does anyone have any experience with this method, if so could you offer some input to as whether you think this method would be applicable for my problem. Below is two frames from a sample video frame 0: frame 5:
Now provide the response and nothing else.
| Assumimg your cars are moving, you could try to estimate the ground plane (road). You may get a descent ground plane estimate by extracting features (SURF rather than SIFT, for speed), matching them over frame pairs, and solving for a homography using RANSAC, since plane in 3d moves according to a homography between two camera frames. Once you have your ground plane you can identify the cars by looking at clusters of pixels that don't move according to the estimated homography. A more sophisticated approach would be to do Structure from Motion on the terrain. This only presupposes that it is rigid, and not that it it planar. Update I was wondering if you could expand on how you would go about looking for clusters of pixels that don't move according to the estimated homography? Sure. Say I and K are two video frames and H is the homography mapping features in I to features in K . First you warp I onto K according to H , i.e. you compute the warped image Iw as Iw( [x y]' )=I( inv(H)[x y]' ) (roughly Matlab notation). Then you look at the squared or absolute difference image Diff=(Iw-K)*(Iw-K) . Image content that moves according to the homography H should give small differences (assuming constant illumination and exposure between the images). Image content that violates H such as moving cars should stand out. For clustering high-error pixel groups in Diff I would start with simple thresholding ("every pixel difference in Diff larger than X is relevant", maybe using an adaptive threshold). The thresholded image can be cleaned up with morphological operations (dilation, erosion) and clustered with connected components. This may be too simplistic, but its easy to implement for a first try, and it should be fast. For something more fancy look at Clustering in Wikipedia . A 2D Gaussian Mixture Model may be interesting; when you initialize it with the detection result from the previous frame it should be pretty fast. I did a little experiment with the two frames you provided, and I have to say I am somewhat surprised myself how well it works. :-) Left image: Difference (color coded) between the two frames you posted. Right image: Difference between the frames after matching them with a homography. The remaining differences clearly are the moving cars, and they are sufficiently strong for simple thresholding. Thinking of the approach you currently use, it may be intersting combining it with my proposal: You could try to learn and classify the cars in the difference image D instead of the original image. This would amount to learning what a car motion pattern looks like rather than what a car looks like, which could be more reliable. You could get rid of the expensive window search and run the classifier only on regions of D with sufficiently high value. Some additional remarks: In theory, the cars should even stand out if they are not moving since they are not flat, but given your distance to the scene and camera resolution this effect may be too subtle. You can replace the feature extraction / matching part of my proposal with Optical Flow , if you like. This amounts to identifying flow vectors that "stick out" from a consistent frame-to-frame motion of the ground. It may be prone to outliers in the optical flow, however. You can also try to get the homography from the flow vectors. This is important: Regardless of which method you use, once you have found cars in one frame you should use this information to robustify your search of these cars in consecutive frame, giving a higher likelyhood to detections close to the old ones (Kalman filter, etc). That's what tracking is all about! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15392272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/900253/']} | jdg_379908 |
stackexchange | llm_judgeable_groundtruth_similarity | 5289597 |
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 push_back a struct into a vector? struct point { int x; int y;};std::vector<point> a;a.push_back( ??? );
Now provide the response and nothing else.
| point mypoint = {0, 1};a.push_back(mypoint); Or if you're allowed, give point a constructor, so that you can use a temporary: a.push_back(point(0,1)); Some people will object if you put a constructor in a class declared with struct , and it makes it non-POD, and maybe you aren't in control of the definition of point . So this option might not be available to you. However, you can write a function which provides the same convenience: point make_point(int x, int y) { point mypoint = {x, y}; return mypoint;}a.push_back(make_point(0, 1)); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5289597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407650/']} | jdg_379909 |
stackexchange | llm_judgeable_groundtruth_similarity | 8424754 |
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 know the proper way of doing this.I have a form where someone can fill in 3 different inputs to update their data. they can leave one blank if they want and just update the other two or just one. Whatever. so if i update as: mysql_query("UPDATE table SET field1=input AND field2=BLANK AND filed3=input WHERE ID=123); will it leave the blank fields unchanged? just skip over them? or will it replace the field with an empty string/blank field? If this is the wrong way, what is the correct method?Thank You!
Now provide the response and nothing else.
| It will replace them with blank values. The correct way to do it is not to put those items in the query at all: if (empty($field1) && empty($field2) && empty($field3) { // show error message, nothing to do return;}$updates = array();if (!empty($field1)) $updates[] = 'field1="'.mysql_real_escape_string($field1).'"';if (!empty($field2)) $updates[] = 'field2="'.mysql_real_escape_string($field2).'"';if (!empty($field3)) $updates[] = 'field3="'.mysql_real_escape_string($field3).'"';$updates = implode(', ', $updates);mysql_query("UPDATE table SET $updates WHERE ID=123"); Obviously it would be cleaner to put the changes in an associative array or object, and then loop through them. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8424754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015647/']} | jdg_379910 |
stackexchange | llm_judgeable_groundtruth_similarity | 42200 |
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:
Possible Duplicate: Version control for independent developers? I've heard statements to the effect of: "Well it's just me working on this project so I don't need to put it under source control" as well as, "There is no need to work version controlled on this project, it's so small". It is my opinion that no matter how small the project is, so long as it's adding value to the client (and they are paying for it too) that we, the developer(s), should version control it; especially since its company policy. Am I insane or does my standpoint make sense. Question: Should development work always be version controlled?
Now provide the response and nothing else.
| Oh wow, yes. I use both SVN and Git and I cannot tell you how many times they've saved my ass. More Git than SVN, but let's not start flamewars here. This is on projects I work on by myself, as well as projects I work on with other people. No excuse not to, really. As a human, I'm basically entitled to do stupid shit all the time. By using version control, I can merrily carry on my way doing awesome things and committing at intervals where it makes sense. When I do something incredibly stupid then I can simply rollback my changes to the last point where I committed. Even with Git, I can roll back specific chunks of changes to a file rather than the whole file. My version-control (ab?)using work flow, as a Rails developer (and yes, I know you use C#, same flow applies. Just sub my git commands for your tfs commands), goes like this for a brand new project: Grab a new feature off Pivotal Tracker and figure out what the hell it's supposed to do. Also known as Client-to-English translation. Create a brand new directory for the project and then immediately : git init git add . git commit -m "Initial setup for [project]" git remote add origin [email protected]:radar/project.git git push origin master I now have a Git repository ready for me to commit to, with a master branch. This master branch should always remain "pure". The tests should always be 100%-passing-no-excuses-or-somebody's-going-to-get-fired-slash-very-badly-injured-did-I-mention-no-excuses on this branch. If the feature is adequately complex enough (taking me longer than an hour or two or if the change is going to be more than a single, sensible commit) I will create my own branch using git checkout -b [feature-name] , if not I will work on master. In this branch, I can do whatever the hell I like. master 's still going to be "pure" and I can effectively trash the place and then git checkout . to get it all back. It's in this branch that I develop the new feature, making incremental, sensible commits along the way. Made a page where a user can fill in a form and then something to handle that form? That's a commit. Added a new function to a class and tested it? New commit. I may be inclined to push this branch up somewhere so other people can work with me on it, in which case I would git push origin [feature-name] and then they could clone the repository and git checkout origin/[feature-name] -b [feature-name] to get my changes and we could work together on it. When I'm done with the feature, I run the tests on the [feature-name] branch. Then, I can go back into the master branch, make sure everything's still "pure" by running the tests, and then git merge [feature-name] to merge the branch into master. Then I run the tests again to make sure it's still "pure" (remember, no excuses) and finally I push my changes to the master branch on GitHub. Rinse, repeat. Without version control, I would be utterly lost. I would do stupid shit and then spend quite a lot of time manually rolling it back and not being sure if I've got it all or not. Version control is a great tool to prevent stupidity (as is testing, but that's a tangential topic) and I really, really strongly encourage it. No excuses. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/42200', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/320188/']} | jdg_379911 |
stackexchange | llm_judgeable_groundtruth_similarity | 58207 |
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:
Can anyone provide a simple concrete example of a non-arithmetic commutative and unitary ring (i.e., a commutative and unitary ring in which the lattice of ideals is non-distributive)?
Now provide the response and nothing else.
| Hint $ $ Distributivity easily yields that a finitely generated ideal is $\,1\,$ if it contains a cancellable element $\rm\,u\,$ that is $\rm\,lcm$ -coprime to the generators. For example, for a $2$ -generated ideal $\rm\,(x,y)$ Lemma $\,\ $ If $\rm\ x,\,y\,$ and cancellable $\rm\,u\,$ are elements of an arithmetical ring then $$\rm\ \begin{array}{}\rm (u)\cap(x)\ =\ (u\,x)\\ \rm (u)\cap(y)\ =\ (u\,y)\end{array}\ \ \ and\ \ \ (u) \subseteq (x,y)\ \ \Rightarrow\ \ (x,y) = 1$$ Proof $\rm\ \ (u) = (u)\cap(x,y) = (u)\cap(x) + (u)\cap(y) = u\ (x,y)\,$ so $\rm\,(x,y)=1\,$ by cancelling $\rm\,u$ Remark $ $ Thus to prove that a domain is not arithmetical it suffices to exhibit elements that violate the Lemma. That is easy, e.g. put $\rm\ u = x+y\ $ for $\rm\ x,y \in \mathbb Q[x,y]\,,\, $ or $\rm\ x,\,y=2\in \mathbb Z[x]\,.$ Arithmetical domains are much better known as Prüfer domains. They are non-Noetherian generalizations of Dedekind domains. Their ubiquity stems from a remarkable confluence of interesting characterizations. For example, they are those domains satisfying: $\rm CRT$ (Chinese Remainder Theorem) for ideals, or Gauss's Lemma for polynomial content ideals, or for ideals: $\rm\ A\cap (B + C) = A\cap B + A\cap C\,,\ $ or the $\rm\, GCD\cdot LCM\,$ law: $\rm\, (A + B)\ (A \cap B) = A\ B\,,\ $ or $\,$ "contains $\rm\Rightarrow$ divides" $\rm\ A\supset B\ \Rightarrow\ A\,|\,B\ $ for finitely generated $\rm\,A\,$ etc. It's been estimated that there are over $100$ known characterizations, e.g. see my prior answer for close to $30$ interesting such. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/58207', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8050/']} | jdg_379912 |
stackexchange | llm_judgeable_groundtruth_similarity | 33313708 |
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 seeing something very odd, and honestly I'm stumped. The version of vim that comes with mac is outdated (7.3 instead of 7.4). I'm trying to install vim from homebrew, and I want to use that one instead of the default apple version. I ran " brew install vim ". It installed correctly in /usr/local/bin/vim . All good. When I run " which vim ", it prints " /usr/local/bin/vim ". The Apple version of vim is installed at /usr/bin/vim . So the which command is telling me that I'm using the homebrew version of vim. However, when I actually run vim, it still runs the Apple version $ vim --versionVIM - Vi IMproved 7.3 (2010 Aug 15, compiled Jul 9 2015 23:58:42)Compiled by [email protected]... If I run the homebrew version explicitly, I see this: $ /usr/local/bin/vim --versionVIM - Vi IMproved 7.4 (2013 Aug 10, compiled Oct 23 2015 18:16:35)MacOS X (unix) versionIncluded patches: 1-898Compiled by Homebrew... I even tried moving /usr/bin/vim to /usr/bin/vim73 to try to force using the homebrew version. However, when I did this, here is what I see when I try to run vim: $ vim --version-bash: /usr/bin/vim: No such file or directory$ What is going on? How can I get it to run the homebrew version of vim?
Now provide the response and nothing else.
| Start a new shell session and it’ll work. Bash caches executables’ paths so when you run vim it looks at your PATH to find the first executable with this name. It caches it and the second time you run vim it remembers vim is actually /usr/bin/vim and runs that. Since you haven’t restarted your Bash session its cache is still the same; hence the error you’re seeing. It has nothing to do with the way you installed vim . If you don’t want to start a new shell session, you can run hash -r to tell Bash to clear its executables memory. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33313708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2766472/']} | jdg_379913 |
stackexchange | llm_judgeable_groundtruth_similarity | 496037 |
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 prove that $\sqrt 2 + \sqrt 3$ is irrational. One of the proofs I've seen goes: If $\sqrt 2 +\sqrt 3$ is rational, then consider $(\sqrt 3 +\sqrt 2)(\sqrt 3 -\sqrt 2)=1$, which implies that $\sqrt 3 − \sqrt 2$ is rational. Hence, $\sqrt 3$ would be rational. It is impossible. So $\sqrt 2 +\sqrt 3$ is irrational. Now how do we know that if $\sqrt 3 -\sqrt 2$ is rational, then $\sqrt 3$ should be rational? Thank you.
Now provide the response and nothing else.
| As the rationals are closed under addition, if you know $\sqrt 2 + \sqrt 3$ is rational and that $\sqrt 3 - \sqrt 2$ is rational, their sum $2 \sqrt 3 $ is rational, then divide by $2$ Added: we can even make it explicit. If $\sqrt 2+\sqrt 3=\frac ab, \sqrt 3-\sqrt 2=\frac ba$ and $\sqrt 3=\frac 12 (\frac ab + \frac ba)$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/496037', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/94817/']} | jdg_379914 |
stackexchange | llm_judgeable_groundtruth_similarity | 399840 |
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:
Evaluate this definite integral:$$\int^{441}_0\frac{\pi\sin \pi \sqrt x}{\sqrt x} dx$$
Now provide the response and nothing else.
| This integral (even the indefinite one) can be easily solved by observing: $$\frac{\mathrm d}{\mathrm dx}\pi\sqrt x = \frac{\pi}{2\sqrt x}$$ which implies that: $$\frac{\mathrm d}{\mathrm dx}\cos\pi\sqrt x = -\frac{\pi \sin\pi\sqrt x}{2\sqrt x}$$ Finally, we obtain: $$\int\frac{\pi\sin\pi\sqrt x}{\sqrt x}\,\mathrm dx = -2\cos\pi\sqrt x$$ whence the definite integral with bounds $0, n^2$ evaluates to $2(1-(-1)^n)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/399840', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42814/']} | jdg_379915 |
stackexchange | llm_judgeable_groundtruth_similarity | 16101115 |
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 curious about how the Tuple<T1, T2, T3, ...> serializes and deserializes. I searched using keywords "json" and "tuple" but I could not find what I want.
Now provide the response and nothing else.
| I test by UnitTest and Json.net , and the test codes is as following. The results shows Tuple<T1,T2,T3,...> is serializable and deserializable. So I can use them in my application. Test codes public class Foo { public List<Tuple<string, string, bool>> Items { get; set; } public Foo() { Items = new List<Tuple<string, string, bool>>(); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (var a in Items) { sb.Append(a.Item1 + ", " + a.Item2 + ", " + a.Item3.ToString() + "\r\n"); } return sb.ToString(); }}[TestClass]public class NormalTests{ [TestMethod] public void TupleSerialization() { Foo tests = new Foo(); tests.Items.Add(Tuple.Create("one", "hehe", true)); tests.Items.Add(Tuple.Create("two", "hoho", false)); tests.Items.Add(Tuple.Create("three", "ohoh", true)); string json = JsonConvert.SerializeObject(tests); Console.WriteLine(json); var obj = JsonConvert.DeserializeObject<Foo>(json); string objStr = obj.ToString(); Console.WriteLine(objStr); }} Summary Tuple.Create("own","hehe",true) serializes to {"Item1":"one","Item2":"hehe","Item3":true} {"Item1":"one","Item2":"hehe","Item3":true} can be deserialized back to Tuple<string,string, bool> Class Foo with Tuple data, can be serialized to json string, and the string can be deserialized back to Class Foo . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16101115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419348/']} | jdg_379916 |
stackexchange | llm_judgeable_groundtruth_similarity | 24306004 |
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 written a cron job: @Scheduled(cron="${process.virtual.account.start}")public void ecomProcessVirAccOrderPaymentsScheduler() { LOGGER.info("Start --->" + this.getClass().getCanonicalName() + ".ecomProcessVirAccOrderPaymentsScheduler() Method"); schedulerJobHelper.ecomProcessVirAccOrderPaymentsScheduler(); LOGGER.info("End --->" + this.getClass().getCanonicalName() + ".ecomProcessVirAccOrderPaymentsScheduler() Method");} I want to get the cron attribute used with @Scheduled annotation to be populated from a external properties file. Currently I am fetching it from a property file inside the application scope.I am able to fetch the value, but not able to use it with @Schedule annotation.
Now provide the response and nothing else.
| Which version of spring framework are you using? This won't work if it is less than 3.0.1. Bug Report here in Spring 3.0.0 and it has been fixed in 3.0.1. So if you are using Spring 3.0.1 or greater then following things you have to do to use in cron expression Make an entry in applicationContext.xml for PropertyPlaceHolderConfigurer class that is <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:ApplicationProps.properties</value> </list> </property></bean> After That Use it in using the @Scheduled method like Update: In case if you are using spring boot no need to do anything, below code excerpt should work. @Scheduled(cron="${instructionSchedularTime}")public void load(){} Note: fixed delay and fixed-rate cann't take property value from placeholder because they take long value. Cron attribute take argument as String so you can use placeholder for that. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24306004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3744824/']} | jdg_379917 |
stackexchange | llm_judgeable_groundtruth_similarity | 58314226 |
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 OPA it's clear how to query against condition AND condition : values := { "value1": { "a": "one" }, "value2": { "a": "one", "b": "two" }, "value3": { "a": "one", "b": "one" }}goodValues = [name | value = values[name] value.a == "one" value.b == "one"] So that goodValues here will contain value3 only. But how to query condition OR condition , so that goodValues will contain all 3 values, because they have either value.a == "one" OR value.b == "one" ?
Now provide the response and nothing else.
| Joining multiple expressions together expresses logical AND. To express logical OR you define multiple rules or functions with the same name. There are a couple different ways this can work. This is covered in the introduction to OPA: https://www.openpolicyagent.org/docs/latest/#logical-or . Option 1: Comprehensions & Functions The conditions that you want to express against the value can be factored into helper functions and then the comprehension query can refer to the function. goodValues = [name | value := values[name] value_match(value)]value_match(v) { v.a == "one"}value_match(v) { v.b = "two"} Option 2: Incremental Rules In OPA/Rego, incremental rules assign a set of values to a variable. The rule definition provides the logic to generate the set values. Unlike comprehensions, you can overload the rule definition (providing multiple with the same name) and express logical OR like the other answer explains. # goodValues is a set that contains 'name' if...goodValues[name] { value := values[name] # name is in values value.a == "one" # value.a is "one"}# goodvalues is a set that contains 'name' if...goodValues[name] { value := values[name] # name is in values value.b == "two" # value.b is "two"} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58314226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/491642/']} | jdg_379918 |
stackexchange | llm_judgeable_groundtruth_similarity | 103200 |
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'm running an Ubuntu 9.10 server that has multiple NICs in it. I'd like to make sure that each time the kernel boots up, the NIC with MAC address 01:23:45:67:89:ab gets assigned to eth0 and the one with MAC address ba:98:76:54:32:10 gets assigned to eth1. On Fedora, I was able to do this by specifying the MAC address in /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0HWADDR=01:23:45:67:89:ab# the rest of the configuration goes here (and similarly for ifcfg-eth1). Is there something equivalent syntax in /etc/network/interfaces for doing this on Ubuntu?
Now provide the response and nothing else.
| Ubuntu uses udev for hardware detection. Everytime a new NIC is found, udev generates a rule for it so it will use the same physical interface eth0, eth1, ... If you do not change your hardware, you do not have to care about the interface names, they will stay the same. Should you replace a NIC, it will get the next free interface, eg. eth2. To re-assign eth0 to the new NIC you will have to edit /etc/udev/rules.d/70-persistent-net.rules and delete the old MAC and change eth2 to eth0. For more information on udev and networking see here . | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/103200', 'https://serverfault.com', 'https://serverfault.com/users/847/']} | jdg_379919 |
stackexchange | llm_judgeable_groundtruth_similarity | 1461923 |
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:
Löb's theorem tells us that "if P is provable, then P" is provable, then P is provable. How can this be true? Wouldn't this imply that all false statements are true, because: All false statements are unprovable For all false statements, "if P is provable, then P" is true, because P is not provable Step 2 is a proof of "if P is provable, then P" P is provable P is true Is there something I'm missing?
Now provide the response and nothing else.
| Let us see why your argument is not true by an example. Let $P$ be the sentence $0=1$. If PA could prove $Prov(0=1) \rightarrow 0=1$, then by Löb's theorem it would prove $0=1$. Obviously PA proves that $0 \neq 1$. You want PA to somehow prove that $\neg Prov(0=1)$ so that PA proves $0 \neq 1 \rightarrow \neg Prov(0=1)$, which is equivalent to the statement $Prov(0=1) \rightarrow 0=1$. You claim that "false statements are unprovable". How do you know this? Maybe PA is inconsistent and proves everything, or is unsound and proves false statements even though it is consistent. The point is that PA has to prove its own consistency in order for an argument similar to yours to go through within PA. But by Gödel's incompleteness theorem we know that PA cannot prove the statement $Con(PA)$, which is a shorthand for $\neg Prov(0=1)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1461923', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_379920 |
stackexchange | llm_judgeable_groundtruth_similarity | 1894624 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From my understanding of regular expressions, the string "00###" has to match with "[0-9]", but not with "^[0-9]$". But it doesn't work with Java regexp's. After some investigating of this problem I found the following information ( http://www.wellho.net/solutions/java-regular-expressions-in-java.html ): It might appear that Java regular expressions are default anchored with both a ^ and $ character. Can we be sure that this is true for all versions of JDK? And can this mode be turned off (i.e. to disable default anchoring with ^ and $)?
Now provide the response and nothing else.
| As the article you linked to explains, it depends on the function you call. If you want to add ^ and $ by default, use String#matches or Matcher#matches . If you don't want that, use the Matcher#find method instead. import java.util.regex.*;public class Example{ public static void main(String[] args) { System.out.println("Matches: " + "abc".matches("a+")); Matcher matcher = Pattern.compile("a+").matcher("abc"); System.out.println("Find: " + matcher.find()); }} Output: Matches: falseFind: true | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1894624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/213725/']} | jdg_379921 |
stackexchange | llm_judgeable_groundtruth_similarity | 967464 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to add my own section to the umbraco dashboard so that I can integrate my own admin piece to the existing login/admin structure. Is this possible without editing and recompiling the umbraco source itself? Is it recommended? If so, does anyone have resources to get started doing this?
Now provide the response and nothing else.
| Yes this is possible. The backend can be extended both in terms of the dashoard, sections and content trees. There is a config file you can use to define new dashboard sections. The config file can be found in the following folder: /config/dashboard.config Normally the dashboard.config file has some example XML of how it needs to be structured which looks something like this (I've extended it a bit to show more of the features). <dashBoard> <section> <areas> <area>default</area> <area>content</area> <area>member</area> </areas> <tab caption="Last Edits"> <control>/usercontrols/dashboard/latestEdits.ascx</control> </tab> <tab caption="Latest Items"> <control>/usercontrols/dashboard/newestItems.ascx</control> </tab> <tab caption="Create blog post"> <control>/usercontrols/umbracoBlog/dashboardBlogPostCreate.ascx</control> </tab> </section> <section> <areas> <area>media</area> </areas> <tab caption="Last Edits"> <control>/usercontrols/dashboard/latestEdits.ascx</control> </tab> </section></dashBoard> The section node allows you to set up different tab groups for different admin sections. In the example above the tabs Latest Edits, Latest Items and Create blog post will be applied to the default, member and content sections. Defaut is the first thing the user sees when logging into the back end before selecting a section. To control what is seen in the different sections, you set up a new section node and define which area it applies to and the tab to show. In the example above the second section applies only to the media section. What is displayed in the tab is a normal .NET user control. This can be totally separate from Umbraco or can contain umbraco specific code, depending on wether you are integrating a legacy application or simply extending umbraco. If you wish to create a new section (one of the icons that appears in the bottom left corner of the umbraco backend) then you will need to get your hands a little dirtier. To add a section you need to add a couple of database entries. First you need to define the app in the umbracoApp table. Then add an entry to umbracoUsers2App for the admin user (0). You'll then need to define a new content tree and create the supporting user controls. There is more information about setting this up here: http://www.geckonewmedia.com/blog/2009/8/3/how-to-create-a-custom-section-in-umbraco-4 The first approach (just defining some new tabs) is considerably easier than adding a new section, so I'd recommend you start with that. Then when you are more comfortable you can dive right in and create whole new sections and content trees! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/967464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3420/']} | jdg_379922 |
stackexchange | llm_judgeable_groundtruth_similarity | 32872015 |
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 coding a crawler which retrieves some Facebook posts and serialize them as XML. My problem is the following: I've found that some messages with some special characters (such as \b), when I wrote it to my XML are serialized as  If I try to open back this XML with Java DOM parser (with the  ), I obtain an error because it is not capable to parse this character. How can I solve it? Data examples: http://pastebin.com/3xEK5QbV The error given by the parser when I load the resulting XML is: [Fatal Error] out.xml:7:59: La referencia de caracteres "&# org.xml.sax.SAXParseException; systemId: file:/Z:/Programas/Workspace%20Eclipse/workspace/Test/out.xml; lineNumber: 7; columnNumber: 59; La referencia de caracteres "&# at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) at Test.loadBadXML(Test.java:43) at Test.(Test.java:32) at Test.main(Test.java:139) About source code I've three related source codes: First one: Obtaining "malformed (with \b)" data from JSON from facebook: // post is the object which contains the "post"// URL_BASE_GRAPH, and TOKEN are constants which contains Strings necessary to create the URL for Facebook graph API// idPost is the ID of the post that I'm retrievingString urlStr = URL_BASE_GRAPH + idPost + "?access_token=" + TOKEN;URL url = new URL(urlStr);ObjectMapper om = new ObjectMapper();JsonNode root = om.readValue(url.openStream(), JsonNode.class);... JsonNode message = root.get("message");if (message != null) { post.setMessage(message.asText());} Second one: Writing this data as XML: // outFile is the file to be written File file = new File(outFile); DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("groups"); doc.appendChild(rootElement); .... if (post.getMessage() != null) { Element messagePost = doc.createElement("post_message"); // I've tried also this: messagePost.appendChild(doc.createTextNode(StringEscapeUtils.escapeXml(post.getMessage()))); messagePost.appendChild(doc.createTextNode(post.getMessage())); postEl.appendChild(messagePost); } .... TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); Third one: Loading again the XML (malformed with  ) from the XML: File fXmlFile = new File(f); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); .... Node pstNode = postNode.item(j); if (pstNode.getNodeType() == Node.ELEMENT_NODE) { Element pstElement = (Element) pstNode; String pstMessage = null; if (pstElement.getElementsByTagName("post_message").item(0) != null) pstMessage = pstElement.getElementsByTagName("post_message").item(0).getTextContent(); Any thoughts? Thanks!
Now provide the response and nothing else.
| Rust has Iterator::map , so you can: some_vec.iter().map(|x| /* do something here */) However, Iterator s are lazy so this won't do anything by itself. You can tack a .collect() onto the end to make a new vector with the new elements, if that's what you want: let some_vec = vec![1, 2, 3];let doubled: Vec<_> = some_vec.iter().map(|x| x * 2).collect();println!("{:?}", doubled); The standard way to perform side effects is to use a for loop: let some_vec = vec![1, 2, 3];for i in &some_vec { println!("{}", i);} If the side effect should modify the values in place, you can use an iterator of mutable references: let mut some_vec = vec![1, 2, 3];for i in &mut some_vec { *i *= 2;}println!("{:?}", some_vec); // [2, 4, 6] If you really want the functional style, you can use the .for_each() method: let mut some_vec = vec![1, 2, 3];some_vec.iter_mut().for_each(|i| *i *= 2);println!("{:?}", some_vec); // [2, 4, 6] | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32872015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3385417/']} | jdg_379923 |
stackexchange | llm_judgeable_groundtruth_similarity | 10502539 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I try to extend the functionality of SimpleAudioEngine of cocos2d with the ability to play several sound effect one after another as some kind of chain. I tried to do this with an extension. However I now realized that I probably also need an iVar to remember the names of all sound files and one to remember which sound is currently playing. However it seems that I cannot add iVars in a category. Instead I tried to use an extension, but it seems that they need to be in the original .m file of the class so that also would not work. Is there yet another way, that allows me to do this? The header with the category #import <Foundation/Foundation.h>@interface SimpleAudioEngine(SoundChainHelper)<CDLongAudioSourceDelegate>-(void)playSoundChainWithFileNames:(NSString*) filename, ...;@end And the .m-file with the extension: #import "SoundChainHelper.h"@interface SimpleAudioEngine() { NSMutableArray* soundsInChain; int currentSound;}@end@implementation SimpleAudioEngine(SoundChainHelper)// read in all filenames and start off playing process-(void)playSoundChainWithFileNames:(NSString*) filename, ... { soundsInChain = [[NSMutableArray alloc] initWithCapacity:5]; va_list params; va_start(params,filename); while (filename) { [soundsInChain addObject:filename]; filename = va_arg(params, NSString*); } va_end(params); currentSound = 0; [self cdAudioSourceDidFinishPlaying:nil];}// play first file, this will also always automatically be called as soon as the previous sound has finished playing-(void)cdAudioSourceDidFinishPlaying:(CDLongAudioSource *)audioSource { if ([soundsInChain count] > currentSound) { CDLongAudioSource* mySound = [[CDAudioManager sharedManager] audioSourceForChannel:kASC_Right]; [mySound load:[soundsInChain objectAtIndex:0]]; mySound.delegate = self; [mySound play]; currentSound++; }}@end Alternatively I tried to define the iVars as properties, which will compile. However I can neither synthesize them nor do I have any other possibility to bind them to any method. I try to implement the functionality as a category of SimpleAudioEngine so that I only need to remember one class that deals with all my sound issues. and so that I can create a chain as simple as this: [[SimpleAudioEngine sharedEngine] playSoundChainWithFileNames:@"6a_loose1D.mp3", @"6a_loose2D.mp3", @"6a_loose3D.mp3", @"6a_loose4D.mp3", @"6b_won1D.mp3", nil]; If there is another way that yields the same/ a similar result I would also be very thankful.
Now provide the response and nothing else.
| You are correct that you can't add instance variables (or synthesized @properties) to a category. You can workaround this limitation using the Objective-C runtime's support for Associative References Something like this: In your .h: @interface SimpleAudioEngine (SoundChainHelper) @property (nonatomic, retain) NSMutableArray *soundsInChain;@end In your .m: #import <objc/runtime.h>static char soundsInChainKey;@implementation SimpleAudioEngine (SoundChainHelper)- (NSMutableArray *)soundsInChain{ return objc_getAssociatedObject(self, &soundsInChainKey);}- (void)setSoundsInChain:(NSMutableArray *)array{ objc_setAssociatedObject(self, &soundsInChainKey, array, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}@end (The standard disclaimer applies. I typed this in the browser, and didn't test it, but I have used this technique before.) The documentation I linked to has a lot more information about how associative references work. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10502539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/347445/']} | jdg_379924 |
stackexchange | llm_judgeable_groundtruth_similarity | 66949 |
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 need a way to prove/show that hydrogen peroxide was decomposed through use of catalyst. I want to ensure that my catalyst: $\ce{Fe(NO3)3}$ or iron(III) nitrate is a catalyst, not a reactant/ consumed during the reaction. $$\ce{2 H2O2 (aq) ->[Fe(NO3)3 (s)] 2 H2O (l) + O2 (g)}$$ When the reaction is happening, I will introduce a wooden glowing splint over the bubbling reaction and the wooden splint glowing brighter or reigniting will show that oxygen is being produced. Question: Now, how do I show that water is produced? Would I just boil the product I get after reaction (image above) and put cobalt chloride paper at the water vapour? Also, if I were to use the orange solution above again as a catalyst (since it still contains iron(III) nitrate), would hydrogen peroxide decompose again? If so, is there a way to put iron(III) nitrate back to its solid state? or any way to reuse as catalyst? Edit: If it is easier to answer, it doesn't have to be with iron(III) nitrate. I have an option to use manganese dioxide, which is another catalyst that I can substitute for iron(III) nitrate. I think it should be OK since it does the exact same reaction.
Now provide the response and nothing else.
| Detection of oxygen : Detection of $\ce{O2}$ by a glowing splint is a good way to detect the oxygen. Also you could capture the gas by a simple fixture e.g. and demonstrate the volume change in the receiver. This way you can actually measure moles $\ce{O2}$ produced (by $PV=nRT$) then moles $\ce{H2O2}$ decomposed stoichiometrically by the formula you've written. Choice of catalyst : Using $\ce{MnO2}$ would be better if you want to make sure you have a catalyst. $\ce{MnO2}$ will not be consumed during the decomposition; I'm not sure about iron(III) nitrate. Or, detecting change in $\ce{Fe(NO3)3}$ concentration : Addition of a very small concentration of potassium thiocyanate, $\ce{KSCN}$ (say 1/100 of your $\ce{Fe^{+3}}$ concentration) will yield a deep red product, iron thiocyanate ($\ce{Fe(SCN)^{+2}}$). If you have access to a spectrometer you can measure absorbance of the initial solution's product and the product after decomposing $\ce{H2O2}$. Prove water was produced : The best way I can think of is to measure the (subtle) change of density of your solution before and after decomposition. Using $\ce{MnO2}$ would make this easy because you can remove/filter it as a solid after decomposition and thus measure mass/volume of your solution before and after. $\ce{H2O2}$ and $\ce{H2O}$ have small albeit detectably different densities at RT. $\ce{H2O2}$ is more dense than water so your density should decrease. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/66949', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/38636/']} | jdg_379925 |
stackexchange | llm_judgeable_groundtruth_similarity | 31077812 |
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 get the id from the document which I have in MongoDB, using PyMongo. Here is my code: docQuery = db.doctors.find({"email":doc_mail})doc_id = docQuery[0]["_id"]["$oid"] I have tried this too: doc_id = docQuery[0]["_id"] Neither of them works!
Now provide the response and nothing else.
| Though your second approach should work, docQuery is a Cursor type object. Best way is to iterate over it like: for itm in db.doctors.find({"email":doc_mail}): print itm.get('_id') Or if there is only one object, then use find_one like: itm = db.doctors.find_one({"email":doc_mail})print itm.get('_id') | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31077812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3425344/']} | jdg_379926 |
stackexchange | llm_judgeable_groundtruth_similarity | 284322 |
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 $f$ be a continuous and integrable function over $[a,b]$ . Prove or disprove that $$\int_a^b |f(x)|\ \mathrm{d}x\geq \left | \int_a^b f(x)\ \mathrm{d}x\right|$$
Now provide the response and nothing else.
| If $f$ is a real Riemann-integrable function, this inequality is true. (and if $f$ is complex Riemann-integrable, then this inequality holds.) By properties of the modulus function, we have $$-|f(x)|\le f(x)\le |f(x)|.$$ Since $f$ is continous, $|f|$ is also continous, and hence $|f|$ is Riemann integrable. We can integrate each side of this inequality and we get $$-\int_a^b |f(x)|dx\le \int_a^bf(x)dx\le \int_a^b|f(x)|dx.$$ From this, we have $$\left| \int_a^b f(x)dx\right|\le \int_a^b|f(x)|dx.$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/284322', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/55386/']} | jdg_379927 |
stackexchange | llm_judgeable_groundtruth_similarity | 31215971 |
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 structure as follows: struct app_data{ int port; int ib_port; unsigned size; int tx_depth; int sockfd; char *servername; struct ib_connection local_connection; struct ib_connection *remote_connection; struct ibv_device *ib_dev;}; When I try to initialize it thus: struct app_data data ={ .port = 18515, .ib_port = 1, .size = 65536, .tx_depth = 100, .sockfd = -1, .servername = NULL, .remote_connection = NULL, .ib_dev = NULL}; I get this error: sorry, unimplemented: non-trivial designated initializers not supported I think it wants the order of initialization exactly as it is declared, and local_connection is missing. I don't need to initialize it though, and setting it to NULL doesn't work. If I change it to this for g++, still get the same error: struct app_data data ={ port : 18515, ib_port : 1, size : 65536, tx_depth : 100, sockfd : -1, servername : NULL, remote_connection : NULL, ib_dev : NULL};
Now provide the response and nothing else.
| the order of initialization needs to be in the exact order of declaration. typedef struct FOO{ int a; int b; int c;}FOO;FOO foo = {.a = 1, .b = 2}; // OKFOO foo1 = {.a = 1}; // OKFOO foo2 = {.b = 2, .a = 1}; // Error sorry, unimplemented: non-trivial designated initializers not supportedFOO foo3 = {.a = 1, .c = 2}; // Error sorry, unimplemented: non-trivial designated initializers not supported I understand that this means that the compiler has no support for name-oriented, out-of-order, member initialization. Need to initialize the struct in the old fashioned way. I keep the variable names for clarity, but I have to initialize them in order, and not skip a variable. I can stop the initialization at any variable, but can't initialize variables that come of that. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31215971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/817659/']} | jdg_379928 |
stackexchange | llm_judgeable_groundtruth_similarity | 1054928 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With PHP, I'd like to use a preg_replace() filter for passwords such that the only characters available for passwords are US ASCII typable, minus control codes and NULL. What's the RegEx to achieve that which I can plugin to preg_replace()? EDIT: I've been advised to edit this question since I "get it" now and won't be doing this terribly unpopular technique and will permit any typable character even ones I might not have on my keyboard, just as long as they aren't control codes.
Now provide the response and nothing else.
| As others have said, don't restrict the set of characters that are allowed in passwords. Just because your keyboard doesn't have ä, å, or ö on it is no reason to stop those of us who do have them (or know how to type them anyhow) from using those letters. You're going to be storing the password as a cryptographic hash anyhow (or at least as an encrypted string), aren't you? If so, then it doesn't matter whether your database can successfully/safely store the actual characters in the password anyhow, only the characters output by your crypto algorithm. (And if not, then storing passwords in plaintext is a far bigger problem than what characters the passwords may or may not contain - don't do that!) Your apparent intent to enforce your character set restrictions by silently stripping the characters you dislike rather than by telling the user "Try again and, this time, only use these characters: a, e, i, o, u." makes your proposed method truly atrocious, as it means that if I attempt to use, say, the password fäîry (not incredibly secure, but should hold up against lightweight dictionary attacks), my actual password, unknown to me, will be fry (if your password is a three-letter word, straight out of the dictionary and in common use, you may as well not even bother). Ouch! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1054928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105539/']} | jdg_379929 |
stackexchange | llm_judgeable_groundtruth_similarity | 59381321 |
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 pass the VPC ID to the subnet task to create the subnet, from command line it works and it gives me the ID only: aws ec2 describe-vpcs --filter Name=tag:Name,Values=ANSIBLE_VPC --query Vpcs[].VpcId --output textvpc-0b3697513d5914abc but when I execute it in playbook, I also use the debug and it takes whole output:my script for subnet looks like: # TO DISPLAY VPC ID BELOW: - name: TO DISPLAY VPC_ID command: aws ec2 describe-vpcs --filter Name=tag:Name,Values=ANSIBLE_VPC --query Vpcs[].VpcId --output text register: VPC_ID #- name: GREP VPC ID # shell: grep vpc.id "VPC_ID" - debug: var=VPC_ID then the output shows me: TASK [debug] ******************************************************************************************************************************************************************************************************************************ok: [localhost] => { "VPC_ID": { "changed": true, "cmd": [ "aws", "ec2", "describe-vpcs", "--filter", "Name=tag:Name,Values=ANSIBLE_VPC", "--query", "Vpcs[].VpcId", "--output", "text" ], "delta": "0:00:03.275744", "end": "2019-12-17 13:57:51.062623", "failed": false, "rc": 0, "start": "2019-12-17 13:57:47.786879", "stderr": "", "stderr_lines": [], "stdout": "vpc-0b3697513d5914abc", "stdout_lines": [ "vpc-0b3697513d5914abc" ] }} how I can get in the output only: vpc-0b3697513d5914abc ? Thanks.Michael.
Now provide the response and nothing else.
| I would probably declare IHeaderProps.children as: children: React.ReactElement<IHeaderProps> | React.ReactElement<IHeaderProps>[]; To account for the possibility of having both a single and multiple children. In any case, what you want is not possible. See: How do I restrict the type of React Children in TypeScript, using the newly added support in TypeScript 2.3? React Component children typecheck with typescript What you could do instead is declare a prop, let's say links?: IHeaderLinkProps[] , to pass down the props you need to create those HeaderLink s, rather than their JSX, and render them inside Header : interface IHeaderProps { children?: never; links?: IHeaderLinkProps[];}...const Header: React.FC<IHeaderProps> = ({ links }) => { return ( ... <ul className="header__nav"> { links.map(link => <HeaderLink key={ link.url } { ...link } />) } </ul> ... );}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59381321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10119249/']} | jdg_379930 |
stackexchange | llm_judgeable_groundtruth_similarity | 9413313 |
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: [HttpGet]public ActionResult Edit(int req){ var viewModel = new EditViewModel(); viewModel.RequestId = int; return View(viewModel);}[HttpPost]Public ActionResult Edit(EditViewModel viewModel){// some code here...} It works fine: when the edit form is posted, I have the action controller who is called. Now I modify some little bit my code like this: [HttpGet]public ActionResult Edit(int req){ var viewModel = new EditViewModel(req); return View(viewModel);}[HttpPost]Public ActionResult Edit(EditViewModel viewModel){// some code here...}public class EditViewModel(){ public EditViewModel(int req) { requestId = req; } ...} In this new version, I have a view model with a contructor. This time, when my form is posted back, the action controller is never triggered. Any idea? Thanks.
Now provide the response and nothing else.
| That's normal. The default model binder can no longer instantiate your view model as it doesn't have a parameterless constructor. You will have to write a custom model binder if you want to use view models that don't have a default constructor. Normally you don't need such custom constructor. You could simply have your view model like that: public class EditViewModel(){ public int RequestId { get; set; }} and the POST action like that: [HttpPost]public ActionResult Edit(EditViewModel viewModel){ // some code here...} and now all you have to do is POST the requestId parameter instead of req and the default model binder will do the job. And if for some reason you wanted to use a view model with custom constructor, here's an example of how the custom model binder might look like: public class EditViewModelBinder : DefaultModelBinder{ protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var req = bindingContext.ValueProvider.GetValue("req"); if (req == null) { throw new Exception("missing req parameter"); } int reqValue; if (!int.TryParse(req.AttemptedValue, out reqValue)) { throw new Exception(string.Format("The req parameter contains an invalid value: {0}", req.AttemptedValue)); } return new EditViewModel(reqValue); }} which will be registered in your Application_Start : ModelBinders.Binders.Add(typeof(EditViewModel), new EditViewModelBinder()); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9413313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/693560/']} | jdg_379931 |
stackexchange | llm_judgeable_groundtruth_similarity | 46916992 |
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 AddActivity, which lets you get the URI from either a picture you can take from the camera, or an image that you can select from the gallery. Then you can go to DetailsActivity to view the image. I have it working right now until you restart the device. After you restart and try to go to DetailsActivity for that image, this is the error: Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{3a5e86d 2915:jeremy.com.wineofmine/u0a321} (pid=2915, uid=10321) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs I went to the "Open Files Using Storage Access Framework" Android Development page and read up on the Persist Permissions section. I'm having trouble applying it to my project though. I think the main thing I don't understand is that it looks like you need to call an intent (in my case inside the DetailsActivity), but I don't even have an intent there. Here is the intent that lets you pick the gallery image. This is in AddActivity: Intent intentGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT); intentGallery.addCategory(Intent.CATEGORY_OPENABLE); intentGallery.setType("image/*"); intentGallery.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intentGallery.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); startActivityForResult(intentGallery, SELECT_IMAGE); In the DetailsActivity, this is where it actually crashes: imageURI = Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE)));bitmap = null; try { //If the cursor does not have anything in the image column, set the image to null, with a height so the textviews look decent if (cursor.isNull(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE))){ mFullImage.setImageBitmap(null); mFullImage.setMaxHeight(300); }else{ //remake the bitmap from the URI in the image column //********This next line is where the program crashes********** bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageURI); mFullImage.setImageBitmap(bitmap); } Could I get some help with figuring out how to apply this to my project?
Now provide the response and nothing else.
| To handle permission results overide onRequestPermissionsResult as below @Override public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case General.REQUESTPERMISSION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //reload my activity with permission granted or use the features that required the permission } else { Messenger.makeToast(getContext(), R.string.noPermissionMarshmallow); } break; }} and to persist the permission implement as shown below in your onActivityResult method @Overridepublic void onActivityResult (int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //if ok user selected a file if (resultCode == RESULT_OK) { Uri sourceTreeUri = data.getData(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getContext().getContentResolver().takePersistableUriPermission(sourceTreeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46916992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8709842/']} | jdg_379932 |
stackexchange | llm_judgeable_groundtruth_similarity | 31974851 |
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 df like this Month <- c('JAN','JAN','JAN','JAN','FEB','FEB','MAR','APR','MAY','MAY') Category <- c('A','A','B','C','A','E','B','D','E','F')Year <- c(2014,2015,2015,2015,2014,2013,2015,2014,2015,2013)Number_Combinations <- c(3,2,3,4,1,3,6,5,1,1)df <- data.frame(Month ,Category,Year,Number_Combinations)df Month Category Year Number_Combinations1 JAN A 2014 32 JAN A 2015 23 JAN B 2015 34 JAN C 2015 45 FEB A 2014 16 FEB E 2013 37 MAR B 2015 68 APR D 2014 59 MAY E 2015 110 MAY F 2013 1 I have another df that I got from the above dataframe with a condition df1 <- subset(df,Number_Combinations > 2)df1 Month Category Year Number_Combinations1 JAN A 2014 33 JAN B 2015 34 JAN C 2015 46 FEB E 2013 37 MAR B 2015 68 APR D 2014 5 Now I want to create a table reporting the month, the total number of rows for the month in df and the total number of for the month in df1 Desired Output would be Month Number_Month_df Number_Month_df11 JAN 4 32 FEB 2 13 MAR 1 14 APR 1 15 MAY 2 0 While I used table(df) and table(df1) and tried merging but not getting the desired result. Could someone please help me in getting the above dataframe?
Now provide the response and nothing else.
| Here is my attempt. It's in C++, but can be easily ported to python since most are OpenCV functions. A brief outline of the method, comments in the code should help, too. Load the image Convert to grayscale Binaryze the image (threshold) Thinning, to have thin contours and help findContours Get contours For each contour, get convex hull (to handle open contours), and classify according to circularity . Handle each shape differently. Circle : find the minimum encolsing circle, or the best fitting ellipse Recrangle : find the boundinx box, or the minimum oriented bounding box. Triangle : search for the intersection of the minimum enclosing circle with the original shape, as they would intersect in the three vertices of the triangle. NOTES: I needed to modify the original image to 3 channel RGB from a png with transparency. The thinning code is from here . There is also the Python version. Circularity is defined as: A measures how close to a circle the shape is. E.g. a regular hexagon has higher circularity than say a square. Is defined as (\frac{4*\pi*Area}{perimeter * perimeter}). This means that a circle has a circularity of 1, circularity of a square is 0.785, and so on. Because of the contours, there may be multiple detection for each shape. These can be filtered out according to, for example, intersection over union condition. I did't inserted this part in the code for now, since it requires additional logic that isn't strictly related to the main task of finding the shapes. UPDATE - Just noticed that in OpenCV 3.0.0 there is the function minEnclosingTriangle . This might be helpful to use instead of my procedure to find the triangle vertices. However, since inserting this function in the code would be trivial, I'll leave my procedure in the code in case one doesn't have OpenCV 3.0.0. The code: #include <opencv2\opencv.hpp>#include <vector>#include <iostream>using namespace std;using namespace cv;/////////////////////////////////////////////////////////////////////////////////////////////// Thinning algorithm from here:// https://github.com/bsdnoobz/zhang-suen-thinning/////////////////////////////////////////////////////////////////////////////////////////////void thinningIteration(cv::Mat& img, int iter){ CV_Assert(img.channels() == 1); CV_Assert(img.depth() != sizeof(uchar)); CV_Assert(img.rows > 3 && img.cols > 3); cv::Mat marker = cv::Mat::zeros(img.size(), CV_8UC1); int nRows = img.rows; int nCols = img.cols; if (img.isContinuous()) { nCols *= nRows; nRows = 1; } int x, y; uchar *pAbove; uchar *pCurr; uchar *pBelow; uchar *nw, *no, *ne; // north (pAbove) uchar *we, *me, *ea; uchar *sw, *so, *se; // south (pBelow) uchar *pDst; // initialize row pointers pAbove = NULL; pCurr = img.ptr<uchar>(0); pBelow = img.ptr<uchar>(1); for (y = 1; y < img.rows - 1; ++y) { // shift the rows up by one pAbove = pCurr; pCurr = pBelow; pBelow = img.ptr<uchar>(y + 1); pDst = marker.ptr<uchar>(y); // initialize col pointers no = &(pAbove[0]); ne = &(pAbove[1]); me = &(pCurr[0]); ea = &(pCurr[1]); so = &(pBelow[0]); se = &(pBelow[1]); for (x = 1; x < img.cols - 1; ++x) { // shift col pointers left by one (scan left to right) nw = no; no = ne; ne = &(pAbove[x + 1]); we = me; me = ea; ea = &(pCurr[x + 1]); sw = so; so = se; se = &(pBelow[x + 1]); int A = (*no == 0 && *ne == 1) + (*ne == 0 && *ea == 1) + (*ea == 0 && *se == 1) + (*se == 0 && *so == 1) + (*so == 0 && *sw == 1) + (*sw == 0 && *we == 1) + (*we == 0 && *nw == 1) + (*nw == 0 && *no == 1); int B = *no + *ne + *ea + *se + *so + *sw + *we + *nw; int m1 = iter == 0 ? (*no * *ea * *so) : (*no * *ea * *we); int m2 = iter == 0 ? (*ea * *so * *we) : (*no * *so * *we); if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) pDst[x] = 1; } } img &= ~marker;}void thinning(const cv::Mat& src, cv::Mat& dst){ dst = src.clone(); dst /= 255; // convert to binary image cv::Mat prev = cv::Mat::zeros(dst.size(), CV_8UC1); cv::Mat diff; do { thinningIteration(dst, 0); thinningIteration(dst, 1); cv::absdiff(dst, prev, diff); dst.copyTo(prev); } while (cv::countNonZero(diff) > 0); dst *= 255;}int main(){ RNG rng(123); // Read image Mat3b src = imread("path_to_image"); // Convert to grayscale Mat1b gray; cvtColor(src, gray, COLOR_BGR2GRAY); // Binarize Mat1b bin; threshold(gray, bin, 127, 255, THRESH_BINARY_INV); // Perform thinning thinning(bin, bin); // Create result image Mat3b res = src.clone(); // Find contours vector<vector<Point>> contours; findContours(bin.clone(), contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); // For each contour for (vector<Point>& contour : contours) { // Compute convex hull vector<Point> hull; convexHull(contour, hull); // Compute circularity, used for shape classification double area = contourArea(hull); double perimeter = arcLength(hull, true); double circularity = (4 * CV_PI * area) / (perimeter * perimeter); // Shape classification if (circularity > 0.9) { // CIRCLE //{ // // Fit an ellipse ... // RotatedRect rect = fitEllipse(contour); // Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // ellipse(res, rect, color, 5); //} { // ... or find min enclosing circle Point2f center; float radius; minEnclosingCircle(contour, center, radius); Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); circle(res, center, radius, color, 5); } } else if (circularity > 0.75) { // RECTANGLE //{ // // Minimum oriented bounding box ... // RotatedRect rect = minAreaRect(contour); // Point2f pts[4]; // rect.points(pts); // Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // for (int i = 0; i < 4; ++i) // { // line(res, pts[i], pts[(i + 1) % 4], color, 5); // } //} { // ... or bounding box Rect box = boundingRect(contour); Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); rectangle(res, box, color, 5); } } else if (circularity > 0.7) { // TRIANGLE // Select the portion of the image containing only the wanted contour Rect roi = boundingRect(contour); Mat1b maskRoi(bin.rows, bin.cols, uchar(0)); rectangle(maskRoi, roi, Scalar(255), CV_FILLED); Mat1b triangle(roi.height, roi.height, uchar(0)); bin.copyTo(triangle, maskRoi); // Find min encolsing circle on the contour Point2f center; float radius; minEnclosingCircle(contour, center, radius); // decrease the size of the enclosing circle until it intersects the contour // in at least 3 different points (i.e. the 3 vertices) vector<vector<Point>> vertices; do { vertices.clear(); radius--; Mat1b maskCirc(bin.rows, bin.cols, uchar(0)); circle(maskCirc, center, radius, Scalar(255), 5); maskCirc &= triangle; findContours(maskCirc.clone(), vertices, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); } while (vertices.size() < 3); // Just get the first point in each vertex blob. // You could get the centroid for a little better accuracy Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); line(res, vertices[0][0], vertices[1][0], color, 5); line(res, vertices[1][0], vertices[2][0], color, 5); line(res, vertices[2][0], vertices[0][0], color, 5); } else { cout << "Some other shape..." << endl; } } return 0;} The results ( minEnclosingCircle and boundingRect ): The results ( fitEllipse and minAreaRect ): | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31974851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2359320/']} | jdg_379933 |
stackexchange | llm_judgeable_groundtruth_similarity | 1530890 |
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's say $(X,\sigma)$ and $(X,\tau)$ are topological spaces, and $f$ is a continuous function from the former to the latter. (That is, the inverse images of elements of $\tau$ are elements of $\sigma$.) How would I write this? Saying: Let $f:X\to X$ be continuous clearly doesn't work, since they are meant to have separate topologies. However, saying: Let $f:(X,\sigma)\to(X,\tau)$ be continuous doesn't seem right, as the domain of $f$ is $X$, not the ordered pair $(X,\tau)$, and similarly for the codomain. Should I just do away with function notation completely, and say this?: Let $f$ be a continuous function from the topological space $(X,\sigma)$ to the topological space $(X,\tau)$. The same problem arises for metric spaces.
Now provide the response and nothing else.
| There is exactly one such homomorphism, namely the constant map $x\mapsto 1$, because $1$ is the only number whose $k$th roots are all rational. In more detail: Let $x$ be arbitrary. Since $f(x)=f(\frac x2+\frac x2)=f(\frac x2)^2$ it must be positive; take $f(x)=n/m$ in lowest terms. Suppose that $n/m\ne 1$; then there is some prime $p$ that divides either $n$ or $m$. Suppose it is $p\mid n$; the other case is similar. Let $k$ be some integer such that $p^k>n$. Then what can $f(\frac{x}{k})$ be?\We know that $f(x) = f(k\frac{x}{k}) = f(\frac{x}{k})^k$. But if $f(\frac{x}{k})=a/b$ in lowest terms, then we must have $a^k=n$. Since $p$ divides $n$, $p$ must divide $a$ too, but then $p^k$ divides $a^k=n$, which contradicts $p^k$ being larger than $n$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1530890', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166353/']} | jdg_379934 |
stackexchange | llm_judgeable_groundtruth_similarity | 39627852 |
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 know that numpy array has a method called shape that returns [No.of rows, No.of columns], and shape[0] gives you the number of rows, shape[1] gives you the number of columns. a = numpy.array([[1,2,3,4], [2,3,4,5]])a.shape>> [2,4]a.shape[0]>> 2a.shape[1]>> 4 However, if my array only have one row, then it returns [No.of columns, ]. And shape[1] will be out of the index. For example a = numpy.array([1,2,3,4])a.shape>> [4,]a.shape[0]>> 4 //this is the number of columna.shape[1]>> Error out of index Now how do I get the number of rows of an numpy array if the array may have only one row? Thank you
Now provide the response and nothing else.
| The concept of rows and columns applies when you have a 2D array. However, the array numpy.array([1,2,3,4]) is a 1D array and so has only one dimension, therefore shape rightly returns a single valued iterable. For a 2D version of the same array, consider the following instead: >>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces>>> a.shape(1, 4) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39627852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6861122/']} | jdg_379935 |
stackexchange | llm_judgeable_groundtruth_similarity | 3119329 |
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 first question so hope it is suitable: Shared interface assembly - I have a 'shared' assembly which has an interface, let's call it IDocRepository . It's marked with [ServiceContract] and there are several [OperationContract] -marked methods. WCF implementation assemblies - I have two WCF service projects, each referencing the shared assembly, each implementing that interface as a WCF service. Consumer assembly - Finally, I have a 'client' project, also referencing the shared assembly, with a reference to each of the two WCF services. However, the service references generated in the consumer assembly derive from an auto-generated version of the interface: public partial class ExampleClient : System.ServiceModel.ClientBase<SomeNamespace.ExampleSvcRef.IDocRepository>, SomeNamespace.ExampleSvcRef.IDocRepository { What I expected I would have hoped that both references would instead automatically inherit the interface I defined, that the consumer/client assembly is also referencing. Kind of like the re-use of classes that it provides for parameter and return types, but for the service interface. Why So that I can create an instance of either service reference proxy and cast it to my interface type. So I could modify the generated code by hand each time, but there should be better way...? (edit: I do have 'Reuse types in referenced assemblies' and 'Reuse types in all referenced assemblies' options selected for both service references)
Now provide the response and nothing else.
| "Reuse types in referenced assemblies" only allows you to reuse Data Contracts, not Service Contracts. If you want to share Service Contracts, you don't need to use "Add Service Reference" at all. You can just use ChannelFactory directly. // Supply the binding and address in codeBinding binding = new BasicHttpBinding();EndpointAddress address = new EndpointAddress("http://tempuri.org/address");IServiceContract channel = ChannelFactory<IServiceContract>.CreateChannel(binding, address);// Or read them from the config fileChannelFactory<IServiceContract> channelFactory = new ChannelFactory<IServiceContract>();IServiceContract channel = channelFactory.CreateChannel(); The channel object will also implement ICommunicationObject , so you can cast it if you need to call methods like Open() or Close(). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3119329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376409/']} | jdg_379936 |
stackexchange | llm_judgeable_groundtruth_similarity | 7458110 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
EDIT: solved see comments--don't know how to mark as solved with out an answer. After watching a Channel 9 video on Perfect Forwarding / Move semantics in c++0x i was some what led into believing this was a good way to write the new assignment operators. #include <string>#include <vector>#include <iostream>struct my_type { my_type(std::string name_) : name(name_) {} my_type(const my_type&)=default; my_type(my_type&& other) { this->swap(other); } my_type &operator=(my_type other) { swap(other); return *this; } void swap(my_type &other) { name.swap(other.name); }private: std::string name; void operator=(const my_type&)=delete; void operator=(my_type&&)=delete;};int main(){ my_type t("hello world"); my_type t1("foo bar"); t=t1; t=std::move(t1);} This should allow both r-values and const& s to assigned to it. By constructing a new object with the appropriate constructor and then swapping the contents with *this. This seems sound to me as no data is copied more than it need to be. And pointer arithmetic is cheap. However my compiler disagrees. (g++ 4.6) And I get these error. copyconsttest.cpp: In function ‘int main()’:copyconsttest.cpp:40:4: error: ambiguous overload for ‘operator=’ in ‘t = t1’copyconsttest.cpp:40:4: note: candidates are:copyconsttest.cpp:18:11: note: my_type& my_type::operator=(my_type)copyconsttest.cpp:30:11: note: my_type& my_type::operator=(const my_type&) <deleted>copyconsttest.cpp:31:11: note: my_type& my_type::operator=(my_type&&) <near match>copyconsttest.cpp:31:11: note: no known conversion for argument 1 from ‘my_type’ to ‘my_type&&’copyconsttest.cpp:41:16: error: ambiguous overload for ‘operator=’ in ‘t = std::move [with _Tp = my_type&, typename std::remove_reference< <template-parameter-1-1> >::type = my_type]((* & t1))’copyconsttest.cpp:41:16: note: candidates are:copyconsttest.cpp:18:11: note: my_type& my_type::operator=(my_type)copyconsttest.cpp:30:11: note: my_type& my_type::operator=(const my_type&) <deleted>copyconsttest.cpp:31:11: note: my_type& my_type::operator=(my_type&&) <deleted> Am I doing something wrong? Is this bad practice (I don't think there is way of testing whether you are self assigning)? Is the compiler just not ready yet? Thanks
Now provide the response and nothing else.
| Be very leery of the copy/swap assignment idiom. It can be sub-optimal, especially when applied without careful analysis. Even if you need strong exception safety for the assignment operator, that functionality can be otherwise obtained. For your example I recommend: struct my_type { my_type(std::string name_) : name(std::move(name_)) {} void swap(my_type &other) { name.swap(other.name); }private: std::string name;}; This will get you implicit copy and move semantics which forward to std::string's copy and move members. And the author of std::string knows best how to get those operations done. If your compiler does not yet support implicit move generation, but does support defaulted special members, you can do this instead: struct my_type { my_type(std::string name_) : name(std::move(name_)) {} my_type(const mytype&) = default; my_type& operator=(const mytype&) = default; my_type(mytype&&) = default; my_type& operator=(mytype&&) = default; void swap(my_type &other) { name.swap(other.name); }private: std::string name;}; You may also choose to do the above if you simply want to be explicit about your special members. If you're dealing with a compiler that does not yet support defaulted special members (or implicit move members), then you can explicitly supply what the compiler should eventually default when it becomes fully C++11 conforming: struct my_type { my_type(std::string name_) : name(std::move(name_)) {} my_type(const mytype& other) : name(other.name) {} my_type& operator=(const mytype& other) { name = other.name; return *this; } my_type(mytype&& other) : name(std::move(other.name)) {} my_type& operator=(mytype&& other) { name = std::move(other.name); return *this; } void swap(my_type &other) { name.swap(other.name); }private: std::string name;}; If you really need strong exception safety for assignment, design it once and be explicit about it (edit to include suggestion by Luc Danton): template <class C>typename std::enable_if< std::is_nothrow_move_assignable<C>::value, C&>::typestrong_assign(C& c, C other){ c = std::move(other); return c;}template <class C>typename std::enable_if< !std::is_nothrow_move_assignable<C>::value, C&>::typestrong_assign(C& c, C other){ using std::swap; static_assert(std::is_nothrow_swappable_v<C>, // C++17 only "Not safe if you move other into this function"); swap(c, other); return c;} Now your clients can choose between efficiency (my type::operator=), or strong exception safety using strong_assign . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7458110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401196/']} | jdg_379937 |
stackexchange | llm_judgeable_groundtruth_similarity | 16189088 |
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 switching between fragments by hiding the last fragment and adding a new one (See code below) - adding it to the back-stack as well. This way, users can quickly switch between the fragments without reloading the fragment data. This works well until the app is killed (Scenario: users uses several other apps and my app is getting persisted and killed). When a user opens the app, it is being restored and all the fragments are shown - overlapping one another. Question: How can the restored fragments be restored with their hidden state? Perhaps I'm missing some flag? somewhere? Perhaps there is a better solution for fast switching between fragments (without reloading the data)? Sample code of adding fragments - invoked several times with different fragments upon clicking somewhere: FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();fragmentTransaction.hide(lastFragment);fragmentTransaction.add(newFragment);fragmentTransaction.addToBackStack(null);fragmentTransaction.commit();lastFragment = newFragment;
Now provide the response and nothing else.
| Hope somebody finds a better solution. I'll wait for one before I accept my solution: In general, I use generated tags to find the unhidden fragments and hide them. In details, I generate a unique tag for each fragment (StackEntry) and stack the tags as the fragments themselves get stacked. I persist the stack in the bundel and load it when the app gets restored in order to continure using it. Then I use the list of tags to find all of the unhidden fragments and hide them - except for the last one. Heres sample code: public class FragmentActivity extends Activity { private static final String FRAGMENT_STACK_KEY = "FRAGMENT_STACK_KEY"; private Stack<StackEntry> fragmentsStack = new Stack<StackEntry>(); public FragmentActivity() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_frame); if (savedInstanceState == null) { // Init for the first time - not restore // ... } else { Serializable serializable = savedInstanceState.getSerializable(FRAGMENT_STACK_KEY); if (serializable != null) { // Workaround Android bug. // See: http://stackoverflow.com/questions/13982192/when-using-an-android-bundle-why-does-a-serialised-stack-deserialise-as-an-arra // And: https://code.google.com/p/android/issues/detail?id=3847 @SuppressWarnings("unchecked") List<StackEntry> arrayList = (List<StackEntry>) serializable; fragmentsStack = new Stack<StackEntry>(); fragmentsStack.addAll(arrayList); } // Hide all the restored fragments instead of the last one if (fragmentsStack.size() > 1) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); for (int i = 0; i < fragmentsStack.size()-1; i++) { String fragTag = fragmentsStack.get(i).getFragTag(); Fragment fragment = getFragmentManager().findFragmentByTag(fragTag); fragmentTransaction.hide(fragment); } fragmentTransaction.commit(); } } getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() { @Override public void onBackStackChanged() { Fragment lastFragment = getLastFragment(); if (lastFragment.isHidden()) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.show(lastFragment); fragmentTransaction.commit(); } } }); } private Fragment getLastFragment() { if (fragmentsStack.isEmpty()) return null; String fragTag = fragmentsStack.peek().getFragTag(); Fragment fragment = getFragmentManager().findFragmentByTag(fragTag); return fragment; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(FRAGMENT_STACK_KEY, fragmentsStack); } @Override public void onBackPressed() { if (!fragmentsStack.isEmpty()) { fragmentsStack.pop(); } } public void switchContent(Fragment fragment) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); Fragment lastFragment = getLastFragment(); if (lastFragment != null) { fragmentTransaction.hide(lastFragment); } String fragTag; if (fragment.isAdded()) { fragmentTransaction.show(fragment); fragTag = fragment.getTag(); } else { fragTag = Long.toString(System.currentTimeMillis()); fragmentTransaction.add(R.id.content_frame, fragment, fragTag); } if (!isFirstFragment()) { // Add to backstack only the first content fragment and not the state before (that has nothing) fragmentTransaction.addToBackStack(null); } fragmentTransaction.commit(); fragmentsStack.push(new StackEntry(fragTag)); } public boolean isFirstFragment() { return fragmentsStack.size() == 0; } private static class StackEntry implements Serializable { private static final long serialVersionUID = -6162805540320628024L; private String fragTag = null; public StackEntry(String fragTag) { super(); this.fragTag = fragTag; } public String getFragTag() { return fragTag; } } public static class Intent extends android.content.Intent { public Intent(Context packageContext) { super(packageContext, FragmentActivity.class); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16189088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435605/']} | jdg_379938 |
stackexchange | llm_judgeable_groundtruth_similarity | 1430113 |
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 believe the answer to this question is yes. I was hoping someone would critique my logic. Let X be a separable and metrizable space. Then it has a countable dense subset A. Let B be a basis for X. For every a in A, choose a basis element U in B such that a is in U (if such exists). This forms a countable collection V. Suppose, for a contradiction, there is an element x that is in no element of V. Then x is in a basis element U. U must contain an element of A since A is dense. But this U is not in our collection V, a contradiction.
Now provide the response and nothing else.
| For a metric space $(X,d)$ and an infinite cardinal number $\kappa$, the following are equivalent: $X$ has a base of cardinality $\le \kappa$. X has a network of cardinality $\le \kappa$. (A network is a collection $\mathcal{N}$ of subsets of $X$ such that every open set is a union of elements from $\mathcal{N}$; a base is just a network that consists of open sets.) Every open cover of $X$ has a subcover of cardinality $\le \kappa$. Every closed discrete subspace $A$ of $X$ has cardinality $\le \kappa$. Every discrete subspace $A$ of $X$ has cardinality $\le \kappa$. Every pairwise disjoint family of non-empty open sets of $X$ has cardinality $\le \kappa$. $X$ has a dense subspace of cardinality $\le \kappa$. $1)\rightarrow 2)$ is obvious, and true for all topological spaces $X$. $2)\rightarrow 3)$ is true in general as well: Let $\mathcal{N}$ be a network with $\left|\mathcal{N}\right| \le \kappa$. If $\mathcal{U} = \left\{ U_i : i \in I \right\}$ is an open cover of $X$, then for each $x \in X$ we pick $i(x) \in I$ and $N_x \in \mathcal{N}$, such that $x \in N_x \subset U_{i(x)}$.Then $\left\{N_x : x \in X\right\} = \mathcal{N}'$ has cardinality $\le \kappa$, and for each distinct element $A$ from $\mathcal{N}'$ we pick $U(A)$ from $\mathcal{U}$ with $A \subset U(A)$ ($A = N_x$ for some $x$, and we pick $U(A) = U_{i(x)}$). Then $\left\{U(A) : A \in \mathcal{N}'\right\}$ is the required subcover. $3)\rightarrow 4)$ is always true as well: Let $A$ be closed and discrete. Each $x \in A$ has an open neighbourhood $U_x$that intersects $A$ in $\{x\}$ only. The open cover $\mathcal{U} = \left\{U_x : x \in A\right\} \cup \{X \setminus A\}$cannot spare any $U_x$ (or $x$ will not be covered), so the cover $\mathcal{U}$ has cardinality $|A|$ and no subcover of cardinality strictly less than $|A|$. So $|A| \le \kappa$, or we'd have a contradiction with 3). $4)\rightarrow 5)$ Here we need only perfect normality of $X$, in the sense only thateach open set is a countable union of closed sets, or equivalently that each closed set is a $G_\delta$. Let $A$ be discrete, then I claim that $A$ is open in $\overline{A}$. Proof of claim (needs only that singletons are closed): let $x$ be in $A$ and let $U_x$ be an open neighbourhood of $x$ that intersects $A$ only in $\{x\}$. This $U_x$ has the property that $\overline{A} \cap U_x = \{x\}$ as well: $y \neq x$ and $y \in \overline{A} \cap U_x$, then $U_x\setminus\{x\}$ is an open neighbourhood of $y$, $y \in \overline{A}$ so $U_x\setminus\{x\}$ must intersect $A$, but this can only happen in $\{x\}$, contradiction, so that $\{x\}$ is open in $\overline{A}$. But then, as $A$ is perfectly normal (being metrisable), $A = \cup_{i \in \mathbb{N}} A_i$ where the $A_i$ are closed in $\overline{A}$ (and thus closed in $X)$. So the $A_i$ are closed and discrete, and by 4) we have $|A_i| \le \kappa$. So $|A| \le \aleph_0 \cdot \kappa = \kappa$, as well. $5)\rightarrow 6)$ is true for all topological spaces: pick $x_i \in U_i$ for anypairwise disjoint family $\left\{U_i : i \in I\right\}$ of non-empty open sets. By definition we have that $\left\{x_i: i \in I\right\}$ is discrete (as witnessed by the $U_i$), and so $\left|I\right| \le \kappa$, and 6) has been proved. $6)\rightarrow 7)$ Here we need the metric in a more essential way.For each $n \in \mathbb{N}$, let $D_n$ be a family of points with the property that$x,y \in D_n$ with $x \neq y$ implies $d(x,y) \ge \frac{1}{n}$, and $D_n$ is maximal with that property. Here we use Zorn's lemma, or some equivalent principle.Note that the balls with radius $\frac{1}{2n}$ around the points of $D_n$ are disjointso that $|D_n| \le \kappa$ by 6). Let $D = \cup_n D_n$, we claim that $D$ is dense in $X$.We already see that $D$ is of the right size, as $|D| \le \aleph_0 \cdot \kappa = \kappa$.For if $x$ is not in $\overline{D}$, we have that $d(x,\overline{D}) > 0$ and so for some $m \in \mathbb{N}$ we know that $d(x,\overline{D}) > \frac{1}{m}$. But then, for this $m$,$d(x,\overline{D_m}) \ge d(x,\overline{D}) > \frac{1}{m}$ and in particular: $d(x,y) > \frac{1}{m}$ for all $y \in D_m$. But then we could have added $x$ to $D_m$ and would have obtained a strictly larger $D_m$, and this cannot be. So $D$ is dense. $7)\rightarrow 1)$ This needs the metric "most". Let $D$ be the dense subset ofcardinality at most $\kappa$. Let $\mathcal{B} = \left\{B(x,r): x \in D; r \in \mathbb{Q}\right\}$, then $\left|\mathcal{B}\right| \le \aleph_0 \cdot \kappa = \kappa$. I claim that $\mathcal{B}$ is a base for $X$: let $U$ be open and $x \in U$. Some $\epsilon>0 $ exists such that $B(x,e) \subset U$, and as $D$ is dense there is some $y \in D$ in$B(x,\frac{\epsilon}{3})$. Now pick $r \in \mathbb{Q}$ such that $\frac{\epsilon}{3} < r < \frac{\epsilon}{2}$, then $x \in B(y,r)$ (which is from $\mathcal{B}$) and $B(y,r) \subset B(x,\epsilon)$: if for some $z$, $d(z,y) < r$ then $d(z,x) \le d(z,y) + d(y,x) < r + r < \epsilon$, and so there is a $B_x = B(y,r)$ from $\mathcal{B}$ such that $x \in B_x \subset U$, as required for a base. This concludes the proof of the equivalence, which shows that weight, network weight, Lindelöf number, extent, cellularity and other cardinal invariants are all the same for metrisable spaces. In particular, their countable variants coincide, so separability is equivalent to second countability, etc. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1430113', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/247065/']} | jdg_379939 |
stackexchange | llm_judgeable_groundtruth_similarity | 15113716 |
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 database with three tables. I need to move historic partitioned data to other schemaNow that i´m planning to creatre the new "historic" tables. I don´t know how to measure the size of partition and subpartitions. Can u help me? please gimme some advices. Thanxs in advance.Lou
Now provide the response and nothing else.
| The following query can be used to detemine tablespace and other params: select df.tablespace_name "Tablespace", totalusedspace "Used MB", (df.totalspace - tu.totalusedspace) "Free MB", df.totalspace "Total MB", round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free" from (select tablespace_name, round(sum(bytes) / 1048576) TotalSpace from dba_data_files group by tablespace_name) df, (select round(sum(bytes)/(1024*1024)) totalusedspace, tablespace_name from dba_segments group by tablespace_name) tu where df.tablespace_name = tu.tablespace_name and df.totalspace <> 0; Source: https://community.oracle.com/message/1832920 For your case if you want to know the partition name and it's size just run this query: select owner, segment_name, partition_name, segment_type, bytes / 1024/1024 "MB" from dba_segments where owner = <owner_name>; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15113716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2115594/']} | jdg_379940 |
Subsets and Splits