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
178528
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 have read that a subset of Euclidean space may be called compact if it is both closed and bounded. I was wondering what a good example of a closed but unbounded set would be? Would a closed ball inside a sphere with an infinite radius do the trick? If that example works are there any other examples people could think of? Now provide the response and nothing else.
Being closed means nothing but being the complement of an open set . So take any bounded open subset $S \subset \mathbb R^n$ , then $\mathbb R^n \setminus S$ is closed but not bounded. What you are looking for. I.e:, Any complement of any open ball!
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/178528', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35079/']}
jdg_382341
stackexchange
llm_judgeable_groundtruth_similarity
24203
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose you are using $\alpha = 0.01$ as the significance level. IF you are not getting significant results, is it better to increase the significance level to $\alpha = 0.05$? Now provide the response and nothing else.
Expanding on @EpiGrad 's answer (which is a good answer): There are many reasons to ignore p-values altogether: Principally, they answer a question we are very rarely interested in. If you are going to use p-values, using them as cutoffs often makes little sense. If you are going to use them as cut-offs, you should decide on the cutoff before the analysis Making a more stringent cutoff for type I error means lower power (more type II error). Typical values are .05 for type I and .20 for type II (power = .8). But there is no reason why type II errors are necessarily less bad than type I errors. Suppose you develop a drug that treats a disease that is terminal and rapidly so (e.g. something like Ebola). You test it. Type I error - you say the drug does something when it doesn't, and then give a useless drug to dying people. Type II error - you say the drug does nothing when it does something, and you fail to give a beneficial drug to dying people. Which is worse? Type II, by my book. To quote Prof. David Cox There are no routine statistical questions, only questionable statistical routines
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/24203', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/9648/']}
jdg_382342
stackexchange
llm_judgeable_groundtruth_similarity
195156
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: XOR has the following truth table: 0, 0 : 00, 1 : 11, 0 : 11, 1 : 0 So per bit in an XOR operation, there is a 50% chance of that result being 1 and 50% chance of it being 0. If you XOR a random number (all possibilities were equally likely when created, say from a CSPRNG) and a non-random number, does that result appear random? Now provide the response and nothing else.
A random value does not loose any of its randomness if it is combined without information loss with a non-random value. XOR against some fixed (i.e. non-random) value does not cause such information loss, i.e. the original random value can be recreated from the result by simply XORing again with the same fixed value. Contrary to that AND or OR would cause information loss, i.e. they can not be reversed. But the randomness does not increase either. Thus, if you XOR a 8 bit random value to a 32 bit non-random value it will result in 8 bit of randomness, not 32 bit.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/195156', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/187040/']}
jdg_382343
stackexchange
llm_judgeable_groundtruth_similarity
1380746
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 is an introduction for Lebesgue integral of simple function in Carothers' Real Analysis . We say that a simple function $\phi$ is Lebesgue integrable if the set { $\phi$ $\ne$ 0} has finite measure. In this case, we may write the standard representation for $\phi$ as $\phi = \sum_{i=0}^{n} a_i \chi_{A_i}$ , where $a_0 = 0, a_1, .., a_n$ are distinct real numbers, where $A_0 = \{\phi = 0\}, A_1, ..., A_n$ are pairwise disjoint and measurable, and where only $A_0$ has infinite measure, Once $\phi$ is so written, there is an obvious definition for $\int \phi$ , namely, $$\int \phi = \int_{\mathbb R} \phi = \int_{-\infty}^{+\infty} \phi(x) dx = \sum_{i=1}^{n} a_i m(A_i)$$ . I've noticed that wikipedia's definition of Lebesgue integral(see here https://en.wikipedia.org/wiki/Lebesgue_integration ) uses $d\mu$ . So What does $dx$ or $d\mu$ mean in Lebesgue integral? Update: I don't think it is a exactly duplicate one coz I didn't mean using $d\mu$ instead of $dx$ . Before my typing this question, I have read Rodyen's Real Analysis, 3rd and he also uses $dx$ in Lebesgue integral as well. $d\mu$ is just from wikipedia. I have this question in this May when I was reading Caorthers' book and during that time, I treated it as a whole of symbols and being equal to a fixed formula -- $\sum_{i=1}^{n}a_i m(A_i)$ . And then when I was trying to solve some problems with this symbol in Lebesgue integral, I felt weird for quite a while, recalling the Riemann's definition and then realized "ohhh, man, it is not Riemann integral". Now provide the response and nothing else.
The meaning of the $dx$ in a Lebesgue integral, or any other integral, depends on the extended framework in which the theory is situated. If you are working in a framework in which the measure is the main focus, where there is a wide class of possible measures, for example on a differentiable manifold or in a topological vector spaces, or something more exotic, then the $dx$ would have to be replaced by $d\mu$ to indicate which measure you are talking about. If you're just talking about the standard measure on a Cartesian space $\mathbb{R}^n$, then $dx$ is adequate. The $x$ then serves as a dummy variable (or "bound variable" in mathematical logic) so that you can use inline functions as integrands. For example $\int x^2\,dx$. If the measure is variable, you might like something like $\int x^2\,d\mu(x)$, which indicates the choice of measure and also the dummy variable. In the framework of differential forms, the $dx$ has a different meaning. But that's a different kettle of fish. In reality, integration theory has diverged in so many ways, the notations of the 17th and 18th centuries are no longer adequate. The "generalization thrusts" of integration theory include the following. Generalization from Riemann integrable to very general kinds of functions. Generalization of the class of measurable sets to a maximal class which extends the Borel measurable sets. Generalization of the measure from the standard invariant measure on $\mathbb{R}^n$ to axiomatically defined very general measures. Generalization from real-valued functions to distributions such as Radon measures, Schwartz distributions, Stieltjes integrals, etc. Generalization from volume measures to surface measures, involving maybe differential forms, for example, as in the Stokes theorem. Generalization to fractional dimensional measures, like Carathéodory measures, Hausdorff measures etc. Generalization to extremely discontinuous domain sets, as in geometric measure theory. Generalization to infinite-dimensional spaces, and spaces which are not vector spaces. In these generalized frameworks, the traditional notations for integrals look more and more and more inadequate to describe what the integral is. So what I'm saying is that the problem is much bigger than you describe. The integral notation is just a shorthand, and you have to fill in the details by reading the context. I.e all of the notations are wrong or inaccurate or incomplete. And the extent of the inaccuracy or ambiguity is greater in the more generalized frameworks.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1380746', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/108145/']}
jdg_382344
stackexchange
llm_judgeable_groundtruth_similarity
534229
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have set up a tunnel via autossh. This works: autossh -M 33201 -N -i myIdFile -R 33101:localhost:22 [email protected] I would like to run autossh in background. Seems easy using the -f option. This does not work, however: autossh -f -M 33201 -N -i myIdFile -R 33101:localhost:22 [email protected] Autossh runs in the background fine, but the ssh connection seems to fail every time. In /var/syslog I see multiple occurences of: autossh[3420]: ssh exited with error status 255; restarting ssh What am I doing wrong? A wild guess is it has something to do with the authentication via key file. How can I debug this (adding -v to the ssh options does not seem to log anywhere). Edit: I got some ssh logs using the -y option /usr/bin/ssh[3484]: debug1: Next authentication method: publickey/usr/bin/ssh[3484]: debug1: Trying private key: /home/myuser/.ssh/id_rsa/usr/bin/ssh[3484]: debug1: Trying private key: /home/myuser/.ssh/id_dsa/usr/bin/ssh[3484]: debug1: Trying private key: /home/myuser/.ssh/id_ecdsa/usr/bin/ssh[3484]: debug1: No more authentication methods to try./usr/bin/ssh[3484]: fatal: Permission denied (publickey).autossh[3469]: ssh exited with error status 255; restarting ssh So it seems autossh does not accept my identiy file ( -i myIdFile ) when using the -f option. Why is that? (autossh 1.4c on Raspian) Now provide the response and nothing else.
It seems like when autossh drops to the background (-f option) it is changing the working directory, meaning relative paths do not work any longer. Or more specific: By entering the absolute path of your id file you will probably succeed. I re-created the scenario by creating a key with no password at a non-default location: ~/$ mkdir test~/$ cd test~/test$ ssh-keygen -f test_id_rsa I simply hit enter twice to generate a key that is not protected by a password. I copied the new key to my server (which allows password authentication currently): ~/test$ ssh-copy-id -i test_id_rsa user@server First I confirmed the key was working with regular ssh, then using autossh like you: ~/test$ ssh -i test_id_rsa user@server~/test$ autossh -M 13000 -N -i test_id_rsa user@server^C They both worked fine, so I recreated the problem you had: ~/test$ autossh -f -M 13000 -N -i test_id_rsa user@server This did not work and the following was written to /var/log/syslog : autossh[2406]: ssh exited prematurely with status 255; autossh exiting By changing the path of the keyfile to be absolute, it worked though: ~/test$ autossh -f -M 13000 -N -i /home/user/test/test_id_rsa user@server No errors in /var/log/syslog .
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/534229', 'https://serverfault.com', 'https://serverfault.com/users/156029/']}
jdg_382345
stackexchange
llm_judgeable_groundtruth_similarity
967376
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 working on a windowed Direct3D data plotting application that needs to display multiple overlays on top of the data (similar to HUDs in games). Since there could be a large amount of data that needs plotting, and not all overlays will be changed every time, I figured it wouldn't be a good idea to replot verticies when only one overlay in the display changes. This led me to the idea of rendering the textures and verticies of the overlays to multiple textures with transparent backgrounds that could be overlaid in the render loop and updated independently (similar to layers in Photoshop). Before I embark on changing a large portion of this program to render to textures as opposed to surfaces, I was just wondering if using textures is the best approach. Now provide the response and nothing else.
Not sure if you want the slider scale to be in proportion to your values* but if so, I provided a solution to this for someone else who asked the same question. You can find my solution here . Basically I make use of the slide event that gets triggered when you move the slider to mimic the stepping, but based off a custom array defining the steps. This way it only allows you to "step" to your predefined values, even if they're not evenly spread. *In other words if you want your slider to look like this: |----|----|----|----|----|----|----|0 10 20 100 1000 2000 10000 20000 then go with one of the other solutions here, but if you want your slider to look like this (diagram not to scale): |--|--|-------|-----------|-----------|--------------------|--------------------|0 10 20 100 1000 2000 10000 20000 Then the solution I linked to may be more what you're after. Edit: Ok, this version of the script should work with dual sliders: $(function() { var values = [0, 500, 750, 1000, 1250, 1500, 2000, 2500, 75000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 500000, 1000000]; var slider = $("#price-range").slider({ orientation: 'horizontal', range: true, min: 0, max: 1000000, values: [0, 1000000], slide: function(event, ui) { var includeLeft = event.keyCode != $.ui.keyCode.RIGHT; var includeRight = event.keyCode != $.ui.keyCode.LEFT; var value = findNearest(includeLeft, includeRight, ui.value); if (ui.value == ui.values[0]) { slider.slider('values', 0, value); } else { slider.slider('values', 1, value); } $("#price-amount").html('$' + slider.slider('values', 0) + ' - $' + slider.slider('values', 1)); return false; }, change: function(event, ui) { getHomeListings(); } }); function findNearest(includeLeft, includeRight, value) { var nearest = null; var diff = null; for (var i = 0; i < values.length; i++) { if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) { var newDiff = Math.abs(value - values[i]); if (diff == null || newDiff < diff) { nearest = values[i]; diff = newDiff; } } } return nearest; }}); Note that it looks a little funny down the far left end, since the jumps are so close together compared to the right hand end, but you can see its stepping as desired if you use your keyboard arrows to move the slider. Only way to get around that is to change your scale to not be quite so drastically exponential. Edit 2: Ok, if the spacing is too exaggerated when you use the true values, you could use a set of fake values for the slider & then look up the real value this corresponds to when you need to use the real value (in a similar way to what the other solutions here suggested). Here's the code: $(function() { var trueValues = [0, 500, 750, 1000, 1250, 1500, 2000, 2500, 75000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 500000, 1000000]; var values = [0, 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 25, 30, 40, 50, 60, 75, 100]; var slider = $("#price-range").slider({ orientation: 'horizontal', range: true, min: 0, max: 100, values: [0, 100], slide: function(event, ui) { var includeLeft = event.keyCode != $.ui.keyCode.RIGHT; var includeRight = event.keyCode != $.ui.keyCode.LEFT; var value = findNearest(includeLeft, includeRight, ui.value); if (ui.value == ui.values[0]) { slider.slider('values', 0, value); } else { slider.slider('values', 1, value); } $("#price-amount").html('$' + getRealValue(slider.slider('values', 0)) + ' - $' + getRealValue(slider.slider('values', 1))); return false; }, change: function(event, ui) { getHomeListings(); } }); function findNearest(includeLeft, includeRight, value) { var nearest = null; var diff = null; for (var i = 0; i < values.length; i++) { if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) { var newDiff = Math.abs(value - values[i]); if (diff == null || newDiff < diff) { nearest = values[i]; diff = newDiff; } } } return nearest; } function getRealValue(sliderValue) { for (var i = 0; i < values.length; i++) { if (values[i] >= sliderValue) { return trueValues[i]; } } return 0; }}); You can fiddle with the numbers in the values array (which represent the slider stop points) until you get them spaced out how you want. This way you can make it feel, from the user's perspective, like it's sliding proportionally to the values, but without being as exaggerated. Obviously if your true values are dynamically created, you may need to come up with an algorithm to generate the slider values instead of statically defining them...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/967376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23504/']}
jdg_382346
stackexchange
llm_judgeable_groundtruth_similarity
4623029
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an address that I would like to modify. I have the process. I have the new value. So now what? // My Processvar p = Process.GetProcessesByName("ePSXe").FirstOrDefault();// Addressvar addr = 0x00A66E11;// Valuevar val = 0x63; How can I write 0x63 (99) to this address on another process memory? Now provide the response and nothing else.
@Harvey, from your answer I dug up and found a lot: Open, Close and Write signatures: [DllImport("kernel32.dll")]static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);[DllImport("kernel32.dll", SetLastError = true)]static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);[DllImport("kernel32.dll")]public static extern Int32 CloseHandle(IntPtr hProcess); Flags: [Flags]public enum ProcessAccessFlags : uint{ All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VMOperation = 0x00000008, VMRead = 0x00000010, VMWrite = 0x00000020, DupHandle = 0x00000040, SetInformation = 0x00000200, QueryInformation = 0x00000400, Synchronize = 0x00100000} Make my life easier method: public static void WriteMem(Process p, int address, long v){ var hProc = OpenProcess(ProcessAccessFlags.All, false, (int)p.Id); var val = new byte[] { (byte)v }; int wtf = 0; WriteProcessMemory(hProc, new IntPtr(address), val, (UInt32)val.LongLength, out wtf); CloseHandle(hProc);} Writing into another process memory: static void Main(string[] args){ var p = Process.GetProcessesByName("ePSXe").FirstOrDefault(); WriteMem(p, 0x00A66DB9, 99);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4623029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340760/']}
jdg_382347
stackexchange
llm_judgeable_groundtruth_similarity
105081
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am evaluating a new controller and see a circuit I do not quite understand. I've built the circuit and I see the following (see image), but not understand why. Can someone please give me the name of this circuit so I can look it up? Bottom line, I do not understand how the cap and resistor in parallel = DC. Now provide the response and nothing else.
It is a capacitive power supply with a half-wave rectifier. Most of the grid voltage is dropped on the capacitor due to its impedance. The rest is rectified and regulated using a Zener diode. You must be careful when using this kind of power supply because it is not isolating the grid from low voltage side. Also remember that special (X-rated) capacitor is needed in order to provide minimum security.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/105081', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/18789/']}
jdg_382348
stackexchange
llm_judgeable_groundtruth_similarity
179759
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider the elliptic PDE $$(CR)\;\;\;\;\;\;\begin{cases} U_{xx}=V_{yy}\\U_{yy}=-V_{xx} \end{cases}$$ And its consequence $$(LAP)\;\;\;\;\;\;U_{xxxx}+U_{yyyy}=0$$ . Somehow, these equations are similar to the classical Cauchi Riemann and Laplace equation. 1.Assume that $U$ satisfies the "LAP" equation. Is there a function $V$ such that the pair $(U,V)$ satisfies the "CR" equations? 2.Is there an infinite dimensional algebra of complex functions $f(z)=U+iV$ which satisfies the "CR" equations?If it is the case, can one find such algebra which is invariant under the operator $D(U+iV)=U_{xx}+iV_{xx}$ ?(Motivated by classical holomorphic differentiation $U_{x}+iV_{x}$ ) 3.Is there a geometric way (in term of Reimannian metric) to introduce the above equations on an arbitrary Riemannian manifold. (Similar to the situation of conformal maps and Laplace operator=the composition of div and gradient)?If the answer is yes, what would be the index of "LAP" operator? In the other word, is there a geometric meaning for these equations/ Now provide the response and nothing else.
1.If $U$ satisfies LAP then there exists a $V$ such that $(U,V)$ satisfies CR. In fact, $V$ is unique up to the addition of a term of the form $a + bx + cy + d xy$, where $a$, $b$, $c$, and $d$ are constants. This is an elementary consequence of the Frobenius Theorem. 2.You need to specify what you mean by 'algebra'. The space of functions $F = U + i V$ that satisfy your CR is infinite dimensional. In fact, any real solution to your LAP can be written in the form$$U(x,y) = h_1(x + \omega y) + h_3(x + \omega^3 y) + h_5(x + \omega^5 y) + h_7(x + \omega^7 y)$$where $\omega = \mathrm{e}^{i\pi/4}$ and where each $h_{2i+1}$ is holomorphic in one (complex) variable, satisfying $\overline{h_1(z)}=h_7(\bar z)$ and $\overline{h_3(z)}=h_5(\bar z)$. (I'll let you figure out the corresponding formula for $V$.) This is also provable by the Frobenius Theorem. Added remark about algebras: There are two infinite dimensional subspaces of the space of solutions of CR that are closed under multiplication: Just notice that the operator $C = {\partial_x}^2+i\, {\partial_y}^2$ factors as ${\partial_x}^2+i\, {\partial_y}^2 = \bigl({\partial_x}+\omega^3\, {\partial_y}\bigr)\bigl({\partial_x}-\omega^3\, {\partial_y}\bigr)$, and these two factors commute. Thus $C(F)=0$ is satisfied by any function $F = U+iV = h_1(x + \omega y)$ where $h_1$ is a holomorphic function of its argument (and these functions form a subalgebra) and also by any function $F = U+iV = h_5(x + \omega^5 y)$ where $h_5$ is a holomorphic function of its argument (and these functions also form a subalgebra). In fact, the space of solutions to $C(F)=0$ is almost the direct sum of these two subalgebras; they intersect in the space of constant functions and their sum is the whole space. Because these two factors also commute with $D={\partial_x}^2$, the two subalgebras are each invariant under this operator. 3.Generally, no. Just see what you have to do for surfaces. The point is that the symbol of LAP on a surface will be a quartic form that is the sum of two real, linearly independent fourth powers, and such a quartic form on a surface will determine a splitting of the tangent bundle of the surface into a sum of two line bundles. Thus, there cannot be such an operator on a compact surface with nonvanishing Euler characteristic, e.g., the $2$-sphere.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/179759', 'https://mathoverflow.net', 'https://mathoverflow.net/users/36688/']}
jdg_382349
stackexchange
llm_judgeable_groundtruth_similarity
18849825
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a class which implements the IDisposable interface to dispose a private variable _MailMessage The same class has a async method that makes use of the private IDisposable variable, namely async public Task<bool> Send My question is: Will the normal IDisposable implementation dispose the private variable after the async method completes? Here is an example of the class I am talking about: public class Email : IEmail{ private readonly IEmailData _EmailData; private MailMessage _MailMessage = new MailMessage(); public Email(IEmailData emailData) { if (emailData == null) { throw new ArgumentNullException("emailData"); } if (String.IsNullOrEmpty(emailData.To)) { throw new ArgumentNullException("emailData.To"); } if (String.IsNullOrEmpty(emailData.From)) { throw new ArgumentNullException("emailData.From"); } if (String.IsNullOrEmpty(emailData.FromName)) { throw new ArgumentNullException("emailData.FromName"); } if (String.IsNullOrEmpty(emailData.Subject)) { throw new ArgumentNullException("emailData.Subject"); } if (String.IsNullOrEmpty(emailData.Body)) { throw new ArgumentNullException("emailData.Body"); } _EmailData = emailData; } async public Task<bool> Send() { return await Task.Run<bool>(() => { using (SmtpClient smtp = new SmtpClient()) { smtp.Send(_MailMessage); } return true; }); } #region "IDisposable implementation" public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Email() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_MailMessage != null) _MailMessage.Dispose(); } } #endregion} I have changed the IDisposable implementation according to one of the answer that suggest not to use a destructor: #region "IDisposable implementation"public void Dispose(){ Dispose(true); GC.SuppressFinalize(this);}protected virtual void Dispose(bool disposing){ if (disposing) { if (_MailMessage != null) _MailMessage.Dispose(); }}#endregion Now provide the response and nothing else.
You are doing it pretty fundamentally wrong. A good rule to keep in mind that if you think that you need a destructor then you're wrong 99.9% of the time. A destructor is only required if you have a private variable of an unmanaged type that needs to be released. You don't. The way that you can tell you are doing it wrong is when you find out that you are not actually doing anything at all if the disposing argument is false. Or in other words, the destructor doesn't actually do anything. So it isn't needed. Then you don't need the disposable pattern either. There's more wrongness, you need to inherit the IDisposable interface to implement your own Dispose() method. You forgot. Your Dispose() method needs to be called by the client code that creates an instance of your Email class. You cannot call it yourself, you don't know when the client code stops using your Email object. So that's a quick answer to your question, you cannot dispose yourself in the Send() method. There's no guarantee whatsoever that the client code will actually call it. You will have to leave it up to the client code to get it right.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18849825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2600162/']}
jdg_382350
stackexchange
llm_judgeable_groundtruth_similarity
1542956
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 {${a_i}$} $1\le i \le 55$ be a sequence of positive integers (not 0), and $\sum_{i=1}^{55}a_i \lt 95$. And i'm asked to prove that there must exist a sequence $k \lt l$ in $[55]$ , such that $\sum_{i=k+1}^{l}a_i = 15$. i thought about this: if all the sequence is 1's so there, the must exist one,ina case that not all of them 1, all of them cannot be 2, so the sum of the sequence is got to be bounded by 55 and 94, i just feel like it was intended to use the pigeonhole principle and I can't figure out how. Now provide the response and nothing else.
Consider the sequence of initial sums $S(0),S(1),\ldots,S(55)$ $$S(n)=\sum_{i=1}^na_i.$$ We have $$S(0)=0<S(1)<S(2)<\cdots<S(55)<95,$$ a sequence of 56 distinct integers in the interval $[0,94]$ of $95$ possibilities. Consider also the sequence of numbers $T(i)=S(i)-15$ . There are 56 of those as well, all integers in the range $[-15,79]$ . Because they are all distinct, at least $56-15=41$ of them are non-negative. Hints: Can you show that the sets $\{S(i)\mid 0\le i<56\}$ and $\{T(i)\mid 0\le i<56\}$ must have a non-empty intersection? Do you see how the claim follows from this? Spoiler #1 Between them the two sets have 97 positive integers in the range $[0,94]$ so the pigeonhole principle tells us that there is some overlap. Spoiler #2 If $T(\ell)=S(\ell)-15=S(k)$ then $$ \sum_{i=k+1}^\ell a_i=S(\ell)-S(k)=15.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1542956', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/290629/']}
jdg_382351
stackexchange
llm_judgeable_groundtruth_similarity
28033616
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 div called .testimonial-inner and using the :after pseudo element I have an arrow that sits underneath it pointing down. The problem I'm having is adding a box-shadow to it all so they both look like one natural element. Without box-shadow on the triangle: body { background: #eee}.testimonial-inner { background: #fff; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; padding: 30px; display: block; margin-bottom: 25px; position: relative; -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25); -moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25); box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);}.testimonial-inner:after { top: 100%; left: 48px; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(255, 255, 255, 0); border-top-color: #fff; border-width: 18px; margin-left: -18px;} <div class="c-4 testimonial-wrap"> <div class="testimonial-inner"> <p>Using Facebook was unquestionably the best decision I could possibly have made at the point in my journalistic journey. It enabled me to share my fears, frustrations as well as successes.</p> </div></div> Notice the box shadow currently doesn't wrap around the arrow. When I add it to the :after declaration I get the following result: body { background: #eee}.testimonial-inner { background: #fff; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; padding: 30px; display: block; margin-bottom: 25px; position: relative; -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25); -moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25); box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);}.testimonial-inner:after { top: 100%; left: 48px; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(255, 255, 255, 0); border-top-color: #fff; border-width: 18px; margin-left: -18px; -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25); -moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25); box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);} <div class="c-4 testimonial-wrap"> <div class="testimonial-inner"> <p>Using Facebook was unquestionably the best decision I could possibly have made at the point in my journalistic journey. It enabled me to share my fears, frustrations as well as successes.</p> </div></div> Now provide the response and nothing else.
You could add another :pseudo-element, rotate it by 45deg and add box-shadow to it. Updated Fiddle body { background: #eee}.testimonial-inner { background: #fff; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; padding: 30px; display: block; margin-bottom: 25px; position: relative; box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);}.testimonial-inner:after { top: 100%; left: 48px; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(255, 255, 255, 0); border-top-color: #fff; border-width: 18px; margin-left: -18px;}.testimonial-inner:before { content: ''; position: absolute; transform: rotate(45deg); width: 36px; height: 36px; bottom: -12px; z-index: -1; box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);} <div class="c-4 testimonial-wrap"> <div class="testimonial-inner"> <p>Using Facebook was unquestionably the best decision I could possibly have made at the point in my journalistic journey. It enabled me to share my fears, frustrations as well as successes.</p> </div></div> Another approach using svg as a triangle. body { background: #eee}.testimonial-wrap { position: relative;}.testimonial-inner { background: #fff; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; padding: 30px; display: block; margin-bottom: 25px; position: relative; box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.75);}#triangle { position: absolute; top: 100%; margin-top: -1px; left: 50px;} <div class="c-4 testimonial-wrap"> <div class="testimonial-inner"> <p>Using Facebook was unquestionably the best decision I could possibly have made at the point in my journalistic journey. It enabled me to share my fears, frustrations as well as successes.</p> </div> <svg id="triangle" width="40" height="26"> <defs> <filter id="f" width="150%" height="130%"> <feGaussianBlur in="SourceAlpha" stdDeviation="2.5" /> <feComponentTransfer> <feFuncA type="linear" slope="0.8" /> </feComponentTransfer> <feMerge> <feMergeNode/> <feMergeNode in="SourceGraphic" /> </feMerge> </filter> </defs> <path filter="url(#f)" d="M0,0 h40 l-20,20z" fill="white" /> </svg></div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28033616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1160619/']}
jdg_382352
stackexchange
llm_judgeable_groundtruth_similarity
2599452
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 $A=\begin{pmatrix} I \\ v \end{pmatrix} \in \mathbb R^{n\times n-1}$ with $I\in \mathbb R^{n-1\times n-1}$identity matrix and $v=(v_1...v_{n-1})$. Show that $\det(A^TA)=1+v_1^2+...+v_{n-1}^2$ I tried multiplying it out$$A^TA=\begin{pmatrix} I &v^T \\ \end{pmatrix}\begin{pmatrix} I \\ v \end{pmatrix}=\begin{pmatrix} 1+v_1^2 & v_1v_2 & \dots &v_1v_{n-1} \\ v_1v_2 & 1+v_2^2 & \dots & v_2v_{n-1}\\\\vdots&\vdots &\ddots &\vdots\\v_1v_{n-1}& v_2v_{n-1}&\dots &1+v_{n-1}^2 \end{pmatrix}$$ and use induction, but I can't go further. Now provide the response and nothing else.
If $v = 0$, then the answer is immediate from your multiplied-out matrix. Otherwise, the product may be simplified as $I + v^Tv$. Now, the determinant of a matrix is known to be the product of all eigenvalues (with multiplicity), so we try to see if we can find any:$$\det(I+v^Tv - \lambda I) = \det(v^Tv - \eta I)$$where $\eta = \lambda - 1$. Thus we've transformed the problem from finding the eigenvalues of $I+v^Tv$ to finding the eigenvalues of $v^Tv$, and then adding $1$ to all of them. The matrix $v^Tv$ has eigenvalue $0$. The corresponding eigenspace is the space of all vectors orthogonal to $v^T$, which has dimension one less than the space in which $v^T$ lives; this is where I use $v\neq 0$, mostly for simplicity. So the multiplicity of this eigenvalue is $n-2$. (If you want to nit-pick algebraic vs. geometric multiplicity here, then I say that $v^Tv$ is symmetric, therefore diagonalizable, and the two notions are therefore equal. Alternatively, the algebraic multiplicity is at least as large as the geometric multiplicity. As we yet have one eigenvalue to take care of, the algebraic multiplicity must be the same as the geometric in this case; there is no room for higher multiplicity.) Also, $v^T$ is an eigenvector of $v^Tv$:$$(v^Tv)v^T = v^T(vv^T) = v^T\cdot \|v^T\|^2$$and the corresponding eigenvalue, as we can see, is $\|v^T\|^2$. So that's it. $v^Tv$ has eigenvalues $0$ with multiplicity $n-2$, and $\|v^T\|^2$ with multiplicity $1$. This means that $I+v^Tv$ has eigenvalues $1$ with multiplicity $n-2$ and $\|v^T\|^2 + 1$ with multiplicity $1$. Multiply them all together, and you get your answer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2599452', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/237775/']}
jdg_382353
stackexchange
llm_judgeable_groundtruth_similarity
29472848
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 no idea how to ask this question or what title to use. I hope i do not violate any rules. Anyway, can someone explain to me the following behavior? I have this code: X x = new X();x.dosmth(null);static class X{ void dosmth(Object obj) { System.out.println("X:Object"); } void dosmth(Double obj) { System.out.println("X:Double"); } void dosmth(int obj) { System.out.println("X:int"); } void dosmth(double obj) { System.out.println("X:double"); } void dosmth(char obj) { System.out.println("X:char"); } void dosmth(byte obj) { System.out.println("X:byte"); }} What i get is this: X:Double Why it ignores completely the line void dosmth(Object obj) { System.out.println("X:Object"); } And why null corresponds to Double and not Object? In addition, if i add this line: void dosmth(Integer obj) {System.out.println("X:Integer"); } i get the following error: both method dosmth(java.lang.Integer) and method dosmth(java.lang.Double) match Now provide the response and nothing else.
When choosing an overloaded method, null can correspond to any reference type. When there are two candidates - Object and Double in your case - the most specific one is chosen - Double ( Double is more specific than Object since it's a sub-class of Object ). When you introduce void dosmth(Integer obj) , there are three candidates - Object , Double and Integer - but since neither Double nor Integer is more specific than the other - the compiler can't choose between then and you get an error. As mentioned by FINDarkside, if you which a specific method to be chosen, you can cast the null to the desired type. For example, this will force the compiler to choose void dosmth(Object obj) : x.dosmth((Object)null);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29472848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1276686/']}
jdg_382354
stackexchange
llm_judgeable_groundtruth_similarity
550918
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm creating a cursor at runtime from a image resource. The HotSpot of the new Cursor is always set to 16x16 (32x32 image). Is it possible to change the HotSpot at runtime or will I need to create .cur files? Now provide the response and nothing else.
You sure can. Here are my utility functions, edit as you see fit :) public struct IconInfo { public bool fIcon; public int xHotspot; public int yHotspot; public IntPtr hbmMask; public IntPtr hbmColor; } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo); [DllImport("user32.dll")] public static extern IntPtr CreateIconIndirect(ref IconInfo icon); /// <summary> /// Create a cursor from a bitmap without resizing and with the specified /// hot spot /// </summary> public static Cursor CreateCursorNoResize(Bitmap bmp, int xHotSpot, int yHotSpot) { IntPtr ptr = bmp.GetHicon(); IconInfo tmp = new IconInfo(); GetIconInfo(ptr, ref tmp); tmp.xHotspot = xHotSpot; tmp.yHotspot = yHotSpot; tmp.fIcon = false; ptr = CreateIconIndirect(ref tmp); return new Cursor(ptr); } /// <summary> /// Create a 32x32 cursor from a bitmap, with the hot spot in the middle /// </summary> public static Cursor CreateCursor(Bitmap bmp) { int xHotSpot = 16; int yHotSpot = 16; IntPtr ptr = ((Bitmap)ResizeImage(bmp, 32, 32)).GetHicon(); IconInfo tmp = new IconInfo(); GetIconInfo(ptr, ref tmp); tmp.xHotspot = xHotSpot; tmp.yHotspot = yHotSpot; tmp.fIcon = false; ptr = CreateIconIndirect(ref tmp); return new Cursor(ptr); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/550918', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26566/']}
jdg_382355
stackexchange
llm_judgeable_groundtruth_similarity
26786460
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In order to open a print dialog for the current page we do something like so: <a href="javascript:window.print()">Print</a> How to make a link in the current page that will open the print dialog with different context than the actual page? Print dialog box in Chrome: Now provide the response and nothing else.
Print Dialog After playing around (and some googling), I came out with this solution: I added a non-printable class to the current view and printable class to the printable container element. In my CSS, I used css media queries where @media screen and @media print states contains the corresponding display behavior: @media screen { .printable { display: none; } .non-printable { display: block; }}@media print { .printable { display: block; } .non-printable { display: none; }} Now, I can print new content from my current view without opening a new tab or changing my current view. Check out this jsFiddle and the supported browser 's list.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26786460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1843451/']}
jdg_382356
stackexchange
llm_judgeable_groundtruth_similarity
2114757
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 CSS, I can do something like this: But I've no idea how to change that to something like: Is this possible with CSS? If yes, how can I do it without explicitly specifying the height (let the content grow)? Now provide the response and nothing else.
Grid Nowadays, I prefer grid because it allows keeping all layout declarations on parent and gives you equal width columns by default: .row { display: grid; grid-auto-flow: column; gap: 5%;}.col { border: solid;} <div class="row"> <div class="col">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div> <div class="col">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div> <div class="col">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.</div></div> Flexbox Use Flexbox if you want children to control column width: .row { display: flex; justify-content: space-between;}.col { flex-basis: 30%; box-sizing: border-box; border: solid;} <div class="row"> <div class="col">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div> <div class="col">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div> <div class="col">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.</div></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2114757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89771/']}
jdg_382357
stackexchange
llm_judgeable_groundtruth_similarity
8188548
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Imagine I have an JS array like this: var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; What I want is to split that array into N smaller arrays. For instance: split_list_in_n(a, 2)[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]For N = 3:[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]For N = 4:[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]For N = 5:[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]] For Python, I have this: def split_list_in_n(l, cols): """ Split up a list in n lists evenly size chuncks """ start = 0 for i in xrange(cols): stop = start + len(l[i::cols]) yield l[start:stop] start = stop For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator). function split(array, cols) { if (cols==1) return array; var size = Math.ceil(array.length / cols); return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));} Here's a jsfiddle of that: http://jsfiddle.net/uduhH/ How would you do that? Thanks! Now provide the response and nothing else.
You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length): function chunkify(a, n, balanced) { if (n < 2) return [a]; var len = a.length, out = [], i = 0, size; if (len % n === 0) { size = Math.floor(len / n); while (i < len) { out.push(a.slice(i, i += size)); } } else if (balanced) { while (i < len) { size = Math.ceil((len - i) / n--); out.push(a.slice(i, i += size)); } } else { n--; size = Math.floor(len / n); if (len % size === 0) size--; while (i < size * n) { out.push(a.slice(i, i += size)); } out.push(a.slice(size * n)); } return out;}///////////////////////onload = function () { function $(x) { return document.getElementById(x); } function calc() { var s = +$('s').value, a = []; while (s--) a.unshift(s); var n = +$('n').value; $('b').textContent = JSON.stringify(chunkify(a, n, true)) $('e').textContent = JSON.stringify(chunkify(a, n, false)) } $('s').addEventListener('input', calc); $('n').addEventListener('input', calc); calc();} <p>slice <input type="number" value="20" id="s"> items into<input type="number" value="6" id="n"> chunks:</p><pre id="b"></pre><pre id="e"></pre>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8188548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55283/']}
jdg_382358
stackexchange
llm_judgeable_groundtruth_similarity
18711384
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: stru = "۰۱۲۳۴۵۶۷۸۹"strlist = stru.decode("utf-8").split()print strlist[0] my output is : ۰۱۲۳۴۵۶۷۸۹ But when i use: print strlist[1] I get the following traceback : IndexError: list index out of range My question is, how can I split my string ? Of course, remember I get my string from a function , consider it's a variable ? Now provide the response and nothing else.
The split() method by default splits on whitespace. Therefore, strlist is a list that contains the whole string in strlist[0] , and one single element. If you want a list with one element for each unicode codepoint you can do transform it into a list in different ways: Function: list(stru.decode("utf-8")) List comprension: [item for item in stru.decode("utf-8")] Not convert at all. Do you really need a list? You can iterate over the unicode string just like over any other sequence type ( for character in stru.decode("utf-8"): ...)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18711384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1058591/']}
jdg_382359
stackexchange
llm_judgeable_groundtruth_similarity
52739367
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I got this question in one of my interviews, which I unfortunately skipped, but I'm very curious to get the answer. Can you help me? int sum = 0;int num = 100000000;for (int i = 0; i < num; i++){ for (int j = 0; j < num; j++ ){ sum += m_DataX[i] * m_DataX[j]; }} EDITED: Also I would like to see if it is possible to optimize if we have the following expression for sum : sum += m_DataX[i] * m_DataY[j]; Now provide the response and nothing else.
Simply, square of sum of the numbers.Why? Let, an array is, |1|2|3| Then, the code produces 1*1 + 1*2 + 1*32*1 + 2*2 + 2*33*1 + 3*2 + 3*3 That is, (1*1 + 1*2 + 1*3) + (2*1 + 2*2 + 2*3) + (3*1 + 3*2 + 3*3) => 1(1+2+3) + 2(1+2+3) + 3(1+2+3) => (1+2+3) * (1+2+3) Therefore, the code will be int tempSum = 0;for (int i = 0; i < num ; i ++){ tempSum+=m_DataX [i];}sum=tempSum*tempSum; Update: What if, sum += m_DataX[i]*m_DataY[j] Let, two arrays are, |1|2|3| and |4|5|6| Therefore, 1*4 + 1*5 + 1*52*4 + 2*5 + 2*63*4 + 3*5 + 3*6 => 1*4 + 2*4 + 3*4 + 1*5 + 2*5 + 3*5 + 1*6 + 2*6 + 3*6 => (1+2+3) * (4+5+6)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52739367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1608933/']}
jdg_382360
stackexchange
llm_judgeable_groundtruth_similarity
74398
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: Often restaurants add slices of lemon to water. They seem to make the water taste better and perhaps reduce or at least cover up the chlorine taste. I've heard that Vitamin C tablets can be used to remove chlorine from tap water. Q : Does anyone know if lemons, being rich in vit C, will encourage the removal of chlorine from tap water? Now provide the response and nothing else.
Yes , a quick and cheap way to reduce chlorine residual is to add ascorbic acid (VITAMIN C) , which if added in an equal molar amount to free chlorine would completely eliminate chlorine residual within 1 min. I am quoting from ABSTRACT from a paper from, Int. Journal of Engineering Research and Applications , ISSN : 2248-9622, Vol. 3, Issue 5, Sep-Oct 2013, pp.1647-1651. "Society’s preference for bottled water mainly comes from a dislike of the mildly pungent taste and odor of tap water. Such odor and taste may be caused by chlorine residual (in the form of free chlorine or chloramines), which is maintained in a water distribution system to prevent regrowth of microorganisms and is thus present in tap water. "Two methods of reducing chlorine residual, boiling tap water and adding ascorbic acid totap water, were tested. The results showed that, for free chlorine, a quick and cheap way to reduce chlorine residual is to add ascorbic acid , which if added in an equal molar amount to free chlorine would complete eliminate chlorine residual within 1 min " Reduction of Chlorine Residual in Tap Water with Temperature source : https://www.ijera.com/papers/Vol3_issue5/JN3516471651.pdf As shown aboce, the chlorine residual decreased faster at higher temperatures. Reduction of Free Chlorine and Monochloramine in Tap Water through Boiling source : https://www.ijera.com/papers/Vol3_issue5/JN3516471651.pdf As shown in Figure 2, both residuals of free chlorine and monochloramine decreased with boiling time, and the residual of free chlorine decreased slightly faster than that of monochloramine. The boiling time required to completely remove free chlorine was about 33 min . $\ce{^1}$ Effect of Ascorbic Acid on Free Chlorine and Monochloramine Ascorbic acid added in a molar ratio of 1:1 (free chlorine to ascorbic acid) completely eliminated free chlorine. The DPD indicator(A DPD solution can also be used for the measurement of chlorine residual) did not produce a red color when added within 1 min,indicating complete elemination chlorine residual within 1 min . $\ce{^2}$ The reduction of free chlorine by ascorbic acid can be expressed as follows: $\ce{C6H8O6}$ + $\ce{HOCl}$ → $\ce{C6H6O6}$ + $\ce{HCl}$ + $\ce{H2O}$ Ascorbic acid $\ce{(C6H8O6)}$ is oxidized to dehydroascorbic acid $\ce{(C6H6O6)}$ . Simultaneously, free chlorine $\ce{(HOCl)}$ is reduced to chloride ions (HCl). In the experiment conducted it was determined that 10 mg of ascorbic acid is required to treat 1 L of tap water. and the quickest way to reduce the concentration of free chlorine in tap water is to add powdered vitamin C (ascorbic acid) tablets in less than 1 min. $\ce{^3}$ Thanks to N4v i will be using this cost effective method to remove chlorine from water.(wow). Reference https://www.ijera.com/papers/Vol3_issue5/JN3516471651.pdf https://www.ijera.com/papers/Vol3_issue5/JN3516471651.pdf https://www.ijera.com/papers/Vol3_issue5/JN3516471651.pdf
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/74398', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/38680/']}
jdg_382361
stackexchange
llm_judgeable_groundtruth_similarity
17912307
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got an error with the following exception message: UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' inposition 155: ordinal not in range(128) Not sure what u'\ufeff' is, it shows up when I'm web scraping. How can I remedy the situation? The .replace() string method doesn't work on it. Now provide the response and nothing else.
The Unicode character U+FEFF is the byte order mark, or BOM, and is used to tell the difference between big- and little-endian UTF-16 encoding. If you decode the web page using the right codec, Python will remove it for you. Examples: #!python2#coding: utf8u = u'ABC'e8 = u.encode('utf-8') # encode without BOMe8s = u.encode('utf-8-sig') # encode with BOMe16 = u.encode('utf-16') # encode with BOMe16le = u.encode('utf-16le') # encode without BOMe16be = u.encode('utf-16be') # encode without BOMprint 'utf-8 %r' % e8print 'utf-8-sig %r' % e8sprint 'utf-16 %r' % e16print 'utf-16le %r' % e16leprint 'utf-16be %r' % e16beprintprint 'utf-8 w/ BOM decoded with utf-8 %r' % e8s.decode('utf-8')print 'utf-8 w/ BOM decoded with utf-8-sig %r' % e8s.decode('utf-8-sig')print 'utf-16 w/ BOM decoded with utf-16 %r' % e16.decode('utf-16')print 'utf-16 w/ BOM decoded with utf-16le %r' % e16.decode('utf-16le') Note that EF BB BF is a UTF-8-encoded BOM. It is not required for UTF-8, but serves only as a signature (usually on Windows). Output: utf-8 'ABC'utf-8-sig '\xef\xbb\xbfABC'utf-16 '\xff\xfeA\x00B\x00C\x00' # Adds BOM and encodes using native processor endian-ness.utf-16le 'A\x00B\x00C\x00'utf-16be '\x00A\x00B\x00C'utf-8 w/ BOM decoded with utf-8 u'\ufeffABC' # doesn't remove BOM if present.utf-8 w/ BOM decoded with utf-8-sig u'ABC' # removes BOM if present.utf-16 w/ BOM decoded with utf-16 u'ABC' # *requires* BOM to be present.utf-16 w/ BOM decoded with utf-16le u'\ufeffABC' # doesn't remove BOM if present. Note that the utf-16 codec requires BOM to be present, or Python won't know if the data is big- or little-endian.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17912307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2407162/']}
jdg_382362
stackexchange
llm_judgeable_groundtruth_similarity
42927
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am researching vaccinations as a merit good and I am focusing on an article which discusses how some people are rejecting one of the COVID vaccines because of misinformation about how it may be less effective than the other vaccine. Can this externality be internalised since the vaccine is free to those receiving it because for example, with the flu vaccine the externality can be internalised by providing people with a voucher to receive a free vaccine however the COVID vaccines are already free. If not, is there any other way in which I can discuss how this can be done? Article Link - https://www.theguardian.com/world/2021/feb/25/acceptance-problem-as-most-oxford-covid-jabs-delivered-to-eu-not-yet-used Thanks Now provide the response and nothing else.
Here is an example where the two are actually compatible: The consumer's utility function $U:\mathbb{R}_+\to\mathbb{R}$ is given by $U(c,1-n_ns)=c-n_s$ , the initial labor endowment is $1$ and $F:\mathbb{R}_+\to\mathbb{R}$ is given by $$F(n)=n(1-e^{-n}).$$ This function has IRTS, but still turns a unit of labor into less than one unit of consumption at any amount of input. If you let the price of consumption be $1$ and $w\geq 1$ , you have a competitive equilibrium in which nothing is produced and the consumer simply consumes their endowment. Side rant: The usual definition of IRTS is that when the inputs are multiplied by a number larger than $1$ , the resulting output increases more than proportionally. Under this definition, no production function for which an input of $0$ is feasible has IRTS. Even if one restricts oneself to nonzero inputs, the definition does not work the way people seem to think. The standard example of a production function with IRTS is a Cobb-Douglas production function in which the sum of exponents is larger than $1$ . The standard definition of IRTS applied to an input combination with some, but not all, entries $0$ would show that IRTS does not hold here. It does work when we restrict ourselves to input combinations that produce a positive output, and the function in the example is of this kind. However, one can show that no competitive equilibrium exists if one makes the assumption that the consumer prefers to turn some labor into consumption and the production function produces zero output with zero input and is continuous and increasing, and the consumer's utility function is strictly increasing on the interior. For example, with Cobb-Douglas utility, every bundle in which the consumer enjoys both consumption and leisure is better for the consumer than a bundle in which they enjoy only one of these in a positive amount. Since every competitive equilibrium is Pareto efficient by the first welfare theorem (whose assumptions hold here), some amount of consumption must be produced here, and this is not compatible with profit maximization. Indeed, suppose there is an equilibrium with $p$ the price of the consumption good and $w$ the wage. Since the consumer's utility function is strictly increasing on the interior, an optimal consumption bundle can only exist if $p>0$ and $w>0$ . Let $c_e$ and $n_e$ be the equilibrium consumption and labor supply. Efficiency requires $c_e>0$ and, therefore, also $n_e>0$ . Since the firm can always have a profit of $0$ by using no input, profit maximization implies that $$pF(n_e)-wn_e\geq 0.$$ But then, $$p F(2n_e)-w 2n_e>p 2F(n_e)- w 2n_e=2\big(p F(n_e)-wn_e\big)\geq p F(n_e)-wn_e.$$ Here, the strict inequality comes from IRTS and the weak inequality from $pF(n_e)-wn_e\geq 0.$ We see that the production plan that use an input of $2n_e$ produces a higher profit than the production plan that uses $n_e$ , in contradiction to the firm maximizing profit with a production plan with input $n_e$ .
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/42927', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/32735/']}
jdg_382363
stackexchange
llm_judgeable_groundtruth_similarity
717460
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: Can somebody help me with a query that I'm trying to figure out? I am currently using 2 files. One file has the contents in a list with 2 columns with values below. File_A.txt: 1 MSFT2 YHOO3 GOOG4 APPL5 SUN FILE_B.txt: ### Client A ###123### Client B ###2345 ++++ What I'm trying to achieve using any substitution method, for every occurrence of 1, change the value in File B to MFST. For every occurrence of 2 in File B, change that value to YHOO, 3 to GOOG, etc. The only way I can do this currently is a manual and long process with the use of interactive sed. Is there any looping syntax I could use? sed -i 's/\1\>/MSFT/g' FILE_B.txt Thanks Very Much Now provide the response and nothing else.
Like that? awk 'NR==FNR{a[$1]=$2} NR!=FNR{if($1 in a){$1=a[$1]};print}' File_A.txt FILE_B.txt### Client A ###MSFTYHOOGOOG### Client B ###YHOOGOOGAPPLSUN If that works for you redirect the output to a tmp-file and then mv the tmp file over FILE_B.txt ... if sponge is installed you could just awk 'NR==FNR{a[$1]=$2} NR!=FNR{if($1 in a){$1=a[$1]};print}' File_A.txt FILE_B.txt | sponge FILE_B.txt
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/717460', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/444844/']}
jdg_382364
stackexchange
llm_judgeable_groundtruth_similarity
30766885
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 use Glide to step through frames in a video file (without running into the keyframe seeking issue that Android suffers from). I can do this in Picasso by doing something like: picasso = new Picasso.Builder(MainActivity.this).addRequestHandler(new PicassoVideoFrameRequestHandler()).build();picasso.load("videoframe://" + Environment.getExternalStorageDirectory().toString() + "/source.mp4#" + frameNumber) .placeholder(drawable) .memoryPolicy(MemoryPolicy.NO_CACHE) .into(imageView); (frameNumber is simply an int which increases by 50000 microseconds each time). I also have a PicassoVideoFrameRequestHandler like this: public class PicassoVideoFrameRequestHandler extends RequestHandler {public static final String SCHEME = "videoframe";@Override public boolean canHandleRequest(Request data) { return SCHEME.equals(data.uri.getScheme());}@Overridepublic Result load(Request data, int networkPolicy) throws IOException { FFmpegMediaMetadataRetriever mediaMetadataRetriever = new FFmpegMediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(data.uri.getPath()); String offsetString = data.uri.getFragment(); long offset = Long.parseLong(offsetString); Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(offset, FFmpegMediaMetadataRetriever.OPTION_CLOSEST); return new Result(bitmap, Picasso.LoadedFrom.DISK);}} I'd like to use Glide instead, as it handles memory a little better. Is there any way to have this functionality in Glide? Or, really, any other way to create a set of frames from a video which I can step through! Thanks! Now provide the response and nothing else.
You'll need to pass ".override(width, height)" to make Sam Judd's method to work. Otherwise you'll get only the first frame of the video as I've tested variety of approaches for hours. Hope it saves time for someone. BitmapPool bitmapPool = Glide.get(getApplicationContext()).getBitmapPool();int microSecond = 6000000;// 6th second as an exampleVideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);Glide.with(getApplicationContext()) .load(yourUri) .asBitmap() .override(50,50)// Example .videoDecoder(fileDescriptorBitmapDecoder) .into(yourImageView);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30766885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4292311/']}
jdg_382365
stackexchange
llm_judgeable_groundtruth_similarity
227127
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: What's the difference between a negation and a contrapositive? I keep mixing them up, but it seems that a contrapositive is a negation where the terms' order is changed and where there is an imply sign. Now provide the response and nothing else.
Consider the statement: $$P \implies Q.\tag{1}$$ Then, as you know, the contrapositive of (1) is $$\lnot Q \implies \lnot P.\tag{2}$$ Now, note that statements (1) and (2) are equivalent . I.e., $$\;P \implies Q\equiv \lnot Q \implies \lnot P.$$ One additional observation: Note that the contrapositive of statement $(2)$ is $(1)$, so a contrapositive need not contain any negation symbol $(\lnot)$ at all! Negating statement (1) (and hence negating (2)) would be a statement to the effect that it is NOT the case that $P \implies Q$. I.e. the negation of statement (1) is given by $$\lnot (P \implies Q)\tag{3}$$and since $(P \implies Q) \equiv (\lnot P \lor Q)$, we can write (3) as follows: $$\lnot(\lnot P \lor Q)\tag{4}$$By DeMorgan's, (4) is equivalent to: $$\lnot(\lnot P) \land \lnot Q\tag{5}$$ which yields$$(P \land \lnot Q)\tag{6}$$So (3), (4), (5) and (6) are all equivalent expressions, each negating statement (1). Put another way, the contrapositve of a statement is equivalent to the statement [both a statement and its contrapositive have the same truth-value], while the negation of the statement negates or reverses the truth-value of the original statement. One last comment:When one speaks of the contrapositive of a statement, one is usually speaking about the contrapositive of an implication , whereas one can negate any logical statement whatsoever simply by enclosing the original statement in parentheses and negating it, as in statement (3) above.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/227127', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44374/']}
jdg_382366
stackexchange
llm_judgeable_groundtruth_similarity
24025173
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 created the following class named contact data : public class ContactData { String contact_id; String first_name; String last_name; String email; Uri icon; public ContactData(String contact_id,String first_name,String last_name,String email){ this.contact_id=contact_id; this.first_name=first_name; this.last_name=last_name; this.email=email; this.icon= Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,contact_id); if (this.icon == null){ this.icon = Uri.parse("android.resource://com.project.iandwe/drawable/ic_contacts"); } } public String getContact_id() { return contact_id; } public void setContact_id(String contact_id) { this.contact_id = contact_id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Uri getIcon() { if (this.icon == null){ this.icon = Uri.parse("android.resource://com.project.iandwe/drawable/ic_contacts"); } return this.icon; } public void setIcon(Uri icon) { this.icon = icon; }} Now i try to create the object of this class like this: package com.project.iandwe.Adaptor;import android.content.Context;import android.content.res.Resources;import android.database.Cursor;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.CheckBox;import android.widget.ImageView;import android.widget.TextView;import com.project.iandwe.Data.ContactData;import com.project.iandwe.R;import java.util.ArrayList;/** * Created by NathanDrake on 6/4/2014. */public class ContactSelectAdaptor extends BaseAdapter { ArrayList<ContactData> listViewRows; Context context; public ContactSelectAdaptor(Context context){ //Resources resources = context.getResources(); this.context =context; UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(context); Cursor cursor = userDatabaseAdapter.getUserContacts(); while (cursor.moveToNext()){ // ContactData listViewRow = new ListViewRow(); String contact_id = cursor.getString(0); String first_name = cursor.getString(1); String last_name = cursor.getString(2); String email = cursor.getString(3); // String icon = cursor.getString(4); Log.d("ContactSelectAdaptor"," " + contact_id + " " + first_name + " " + last_name+ " " + email); if (last_name ==null){ last_name = " "; } listViewRows.add(new ContactData(contact_id,first_name,last_name,email)); } } @Override public int getCount() { return listViewRows.size(); } @Override public Object getItem(int position) { return listViewRows.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.listview_contact_select,parent,false); ImageView imageView = (ImageView) view.findViewById(R.id.imageViewProfile); TextView textViewName = (TextView) view.findViewById(R.id.textViewDisplayName); TextView textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress); CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected); ContactData contactData = listViewRows.get(position); imageView.setImageURI(contactData.getIcon()); textViewName.setText(contactData.getFirst_name()); textViewEmail.setText(contactData.getEmail()); checkBox.setChecked(false); return view; }} I added the log.d to check if the data was null but its coming out correctly as follows: 06-03 17:00:37.757 2392-2392/com.project.iandwe D/ContactSelectAdaptor﹕ 3 Batman null [email protected] and i get the following error: 06-03 17:00:37.767 2392-2392/com.project.iandwe E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.project.iandwe, PID: 2392 java.lang.NullPointerException at com.project.iandwe.Adaptor.ContactSelectAdaptor.<init>(ContactSelectAdaptor.java:49) at com.project.iandwe.Menu.ContactsFragments.onActivityCreated(ContactsFragments.java:42) The errors are occurring the following two lines of code: listViewRows.add(new ContactData(contact_id,first_name,last_name,email)); this is inside the ContactSelectAdaptor classs and i am creating the class object by this method inside a fragment: listView.setAdapter(new ContactSelectAdaptor(getActivity())); I think the errors were occurring as either due to last_name being null or Uri being getting set to null but even in that case ContactData should be able to create an object. I am using the above adaptor class to fill in the custom listview. Please let me know what i am missing here Now provide the response and nothing else.
Send mouse events. Like so: //--- Get the first link that has "stackoverflow" in its URL.var targetNode = document.querySelector ("a[href*='stackoverflow']");if (targetNode) { //--- Simulate a natural mouse-click sequence. triggerMouseEvent (targetNode, "mouseover"); triggerMouseEvent (targetNode, "mousedown"); triggerMouseEvent (targetNode, "mouseup"); triggerMouseEvent (targetNode, "click");}else console.log ("*** Target node not found!");function triggerMouseEvent (node, eventType) { var clickEvent = document.createEvent ('MouseEvents'); clickEvent.initEvent (eventType, true, true); node.dispatchEvent (clickEvent);} That works if the web page is statically loaded. If the web page is AJAX-driven , use a technique as in: "Normal" button-clicking approaches are not working in Greasemonkey script? Choosing and activating the right controls on an AJAX-driven site Beware: The question code has an error. You need to pass a class name to that function. Like so: document.getElementsByClassName ("SomeClassName")[0].click();
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24025173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3136105/']}
jdg_382367
stackexchange
llm_judgeable_groundtruth_similarity
12237268
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two classes : base class name Component and inheritd class named DBComponent [Serializable]public class Component{ private string name = string.Empty; private string description = string.Empty; }[Serializable]public class DBComponent : Component{ private List<string> spFiles = new List<string>(); // Storage Procedure Files [XmlArrayItem("SPFile", typeof(string))] [XmlArray("SPFiles")] public List<string> SPFiles { get { return spFiles; } set { spFiles = value; } } public DBComponent(string name, string description) : base(name, description) { }} [Serializable]public class ComponentsCollection{ private static ComponentsCollection instance = null; private List<Component> components = new List<Component>(); public List<Component> Components { get { return components; } set { components = value; } } public static ComponentsCollection GetInstance() { if (ccuInstance == null) { lock (lockObject) { if (instance == null) PopulateComponents(); } } return instance; } private static void PopulateComponents() { instance = new CCUniverse(); XmlSerializer xs = new XmlSerializer(instance.GetType()); instance = xs.Deserialize(XmlReader.Create("Components.xml")) as ComponentsCollection; }} } I want read\write from a Xml file. I know that I need to implement the Serialization for DBComponent class otherwise it will not read it.But i cannot find any simple article for that. all the articles that I found were too complex for this simple scenario. The Xml file looks like this: <?xml version="1.0" encoding="utf-8" ?> <ComponentsCollection> <Components> <DBComponent Name="Tenant Historical Database" Description="Tenant Historical Database"> <SPFiles> <SPFile>Setup\TenantHistoricalSP.sql</SPFile> </SPFiles> </DBComponent> <Component Name="Agent" Description="Desktop Agent" /> </Components> </ComponentsCollection> Can someone please give me a simple example of how to read this kind of xml file and what should be implemented ? Thanks Lior Now provide the response and nothing else.
Unfortunately, you need to tell the XmlSerializer the classes you intend to serialize or deserialize using the XmlArrayItem() attribute. Each different type also needs its own element name. For example: public class ComponentDerviedClass1: Componentpublic class ComponentDerivedClass2: Componentpublic class ComponentDerivedClass3: Component// ...public class ComponentsCollection{ [XmlArray("Components")] [XmlArrayItem("ComponentDerivedClass1", typeof(ComponentDerivedClass1))] [XmlArrayItem("ComponentDerivedClass2", typeof(ComponentDerivedClass2))] [XmlArrayItem("ComponentDerivedClass3", typeof(ComponentDerivedClass3))] public List<Component> Components { // ... }} This would read an XML file like: <?xml version="1.0" encoding="utf-8" ?><ComponentsCollection> <Components> <ComponentDerivedClass1> <!-- ... --> </ComponentDerivedClass1> <ComponentDerivedClass2> <!-- ... --> </ComponentDerivedClass2> <ComponentDerivedClass3> <!-- ... --> </ComponentDerivedClass3> </Components> </ComponentsCollection> Multiple instances of each element can be present (or none).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12237268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1324601/']}
jdg_382368
stackexchange
llm_judgeable_groundtruth_similarity
267707
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 weight 2, level 1 Eisenstein series $E_2(z)$ is a non-holomorphic automorphic form. It is defined as the analytic continuation to $s = 0$ of the series$$ E_2(z, s) = \sum_{\substack{m, n \in \mathbf{Z} \\ (m, n) \ne (0,0)}} \frac{\operatorname{Im}(z)^s}{(mz + n)^2 |mz + n|^{2s}} $$which is convergent for $\operatorname{Re}(s) > 0$ (but not for $s = 0$). Moreover for any prime p the function $E_2(z)-pE_2(pz)$ is holomorphic. My question is: what's the Archimedean component of the automorphic representation corresponding to $E_2$? (If it it the holomorphic discrete series of weight two then seems the vector corresponding to $E_2$ should be holomorphic.) Now provide the response and nothing else.
Excellent question indeed. The quick answer is that $E_2(z)$ is an almost holomorphic modular form of weight $2$ and level $1$, so the automorphic representation generated by it is not irreducible. For more details (and my thought process), read below. Consider the Maass raising operator in weight $0$,$$ R:=y\left(i\frac{\partial}{\partial x}+\frac{\partial}{\partial y}\right).$$Let $(m,n)\in\mathbb{Z}^2$ be a nonzero pair of integers. Then a small calculation gives that, for $z=x+iy$ and $s\in\mathbb{C}$,$$ R\left(\frac{y^s}{|mz+n|^{2s}}\right) =\frac{sy^s}{(mz+n)^2|mz+n|^{2s-2}}.$$ Now let us introduce the usual weight $0$ level $1$ (nonholomorphic) Eisenstein series $$ E(z,s):=\sum_{\substack{m, n \in \mathbb{Z} \\ (m, n) \ne (0,0)}} \frac{\operatorname{Im}(z)^s}{|mz + n|^{2s}},\qquad \operatorname{Re}(s)>1$$then we see that$$ R\,E(z,s+1) = (s+1)\,yE_2(z,s),\qquad \operatorname{Re}(s)>0.\tag{1}$$On the right hand side, $yE_2(z,s)$ is the canonical weight $2$ level $1$ (nonholomorphic) Eisenstein series, the one which transforms as a weight $2$ Maass form. It is worthwhile to recall here that weight $k$ holomorphic forms embed into the weight $k$ Maass spectrum by multiplying each weight $k$ holomorphic form by $y^{k/2}$. In our case $k=2$, which explains why we multiply by $y$. So your Eisenstein series, after inserting the factor $y$ to make it into a canonical weight $2$ form, and also inserting the scaling factor $s+1$, equals the Maass raising shift of $E(z,s+1)$. It belongs to the same automorphic representation as $E(z,s+1)$, hence it has the same Langlands parameters as $E(z,s+1)$ at every place. In particular, the archimedean Langlands parameters are$$ (s+1)-\frac{1}{2}=s+\frac{1}{2}\qquad\text{and}\qquad \frac{1}{2}-(s+1)=-s-\frac{1}{2}.$$ Added and revised. Well, we still need to specify all this to $s=0$, but in this case the above argument breaks down, because $E(z,s+1)$ has a pole at $s=0$. So we need to be more careful. Let us use the results and notation of Section 4 of Duke-Friedlander-Iwaniec: The subconvexity problem for Artin L-functions (Invent. Math. 149 (2002), 489-577). Then for $\operatorname{Re}(s)>1$ we have the Fourier decomposition \begin{align*} \frac{1}{2}E(z,s)&=\ \zeta(2s)y^s+\pi^{2s-1}\frac{\Gamma(1-s)}{\Gamma(s)}\zeta(2-2s)y^{1-s}\\&+\ \frac{\pi^s}{\Gamma(s)}\sum_{n=1}^\infty\frac{\sigma_{2s-1}(n)}{n^s}\bigl\{f_0^+(nz,s)+f_0^-(nz,s)\bigr\}.\end{align*}Let us replace $s$ by $s+1$ here, and then apply the raising operator $R$ along with $(1)$. Then for $\operatorname{Re}(s)>0$ we obtain the Fourier decomposition \begin{align*} \frac{1}{2}E_2(z,s)&=\ \zeta(2s+2)y^s+\pi^{2s+1}\frac{\Gamma(1-s)}{\Gamma(2+s)}\zeta(-2s)y^{-s-1}\\&-\ \frac{\pi^{s+1}}{y\Gamma(2+s)}\sum_{n=1}^\infty\frac{\sigma_{2s+1}(n)}{n^{s+1}}\bigl\{f_2^+(nz,s+1)+s(s+1)f_2^-(nz,s+1)\bigr\}.\end{align*}The right hand side is indeed holomorphic at $s=0$, and at this value it specifies to\begin{align} \frac{1}{2}E_2(z)&=\ \frac{\pi^2}{6}-\frac{\pi}{2y}- \frac{\pi}{y}\sum_{n=1}^\infty\frac{\sigma_1(n)}{n}f_2^+(nz,1)\\&=\ \frac{\pi^2}{6}-\frac{\pi}{2y}-4\pi^2\sum_{n=1}^\infty\sigma_1(n)e(nz).\tag{2}\end{align}It is clear now that the $L$-function of $E_2(z)$ is $\zeta(s-1/2)\zeta(s+1/2)$, and $E_2(z)$ should belong to the holomorphic discrete series of weight $2$ even though its constant term is not holomorphic. I think this paradox arises from the fact that $E_2(z)$ is not a true automorphic form. (More precisely, $E_2(z)$ is not a vector from an irreducible automorphic representation, see the Added 3 section below.) Added 2. Indeed, $E_2(z)$ is an almost holomorphic modular form of weight $2$ and level $1$: it equals $2G_2^*(z)$ in the notation of Section 2.3 of Bruinier-v.d.Geer-Harder-Zagier's book "The 1-2-3 of modular forms". In particular, (19) and (21) in this book reveal that $E_2(z)$ transforms precisely like a holomorphic modular form of weight $2$ and level $1$, even though it is not holomorphic. Of course, the same also follows from the fact that $E_2(z)=\lim_{s->0+}E_2(z,s)$, where $yE_2(z,s)$ for $\operatorname{Re}(s)>0$ transforms precisely like a Maass form of weight $2$ and level $1$. One can read more about almost holomorphic modular forms in Section 5.3 of the book. Added 3. We can learn more by applying the Maass lowering operator in weight $2$,$$L:=1+y\left(i\frac{\partial}{\partial x}-\frac{\partial}{\partial y}\right).$$Using the Fourier decomposition (2), we can see directly that$$ L(yE_2(z))=-\pi, $$which harmonizes with the facts that $ L(yE_2(z,s)) = -s E(z,s+1)$ for $\operatorname{Re}(s)>0$ and $\operatorname{res}_{s=0}E(z,s+1)=\pi$. So we see that the automorphic representation generated by the weight $2$ vector $yE_2(z)$ is reducible: it contains the trivial representation $\mathbb{C}$ as a subrepresentation, while its quotient by $\mathbb{C}$ is irreducible and belongs to the holomorphic discrete series of weight $2$. See also Theorem 2.5.2 in Bump: Automorphic forms and representations, specified to $k=2$ and $\lambda=0$, which helped me understand what is going on.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/267707', 'https://mathoverflow.net', 'https://mathoverflow.net/users/108548/']}
jdg_382369
stackexchange
llm_judgeable_groundtruth_similarity
426617
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am stuck on the following question: Let $X=\{x \in [0,1]: x \neq \frac1n: n \in \Bbb N\}$ be given the subspace topology. Then I have to prove that $X$ is neither compact nor connected . Can someone give some explanation about how to tackle it? Thanks in advance for your time. Now provide the response and nothing else.
Let's consider a picture of $X$ : For convenience / as a suggestion, define $$U_n=(\tfrac{1}{n+1},\tfrac{1}{n})$$ so that $$X=U_1\cup U_2\cup\cdots\cup\{0\}.$$ Can you find an infinite open cover of $X$ with no subcover (demonstrating that $X$ is not compact)? Can you find two disjoint non-empty open sets of $X$ whose union is $X$ ? (recall that any union of open sets is itself an open set) Edit: I wrote this answer mistaking thinking that $\{0\}$ is open in $X$ , when of course it is not. Therefore, the answer that was (intentionally) heavily suggested by what I wrote for compactness is not actually correct. TonyK's suggestion below, to give an infinite open cover of one of the $U_n$ 's and then cover the rest of $X$ , is correct. For connectedness, you can still break $X$ into $U_1$ and $U_2\cup U_3\cup\cdots\cup\{0\}$ because the latter is just $X\cap (-\frac{1}{2},\frac{1}{2})$ , and hence is indeed an open set of $X$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/426617', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33640/']}
jdg_382370
stackexchange
llm_judgeable_groundtruth_similarity
22036576
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got in HTML the following construct: <div id="text"> some&nbsp;text</div> If I trim the text and test it with: $("#text").text().trim() === "some text" it returns false , also: $("#text").text().trim() === "some&nbsp;text" returns false , but: /^some\s{1}text$/.test($("#text").text().trim()) returns true .So please tell me, what´s wrong here. As you would suggest, I am using jQuery (1.6). Now provide the response and nothing else.
That's because the no breaking space (charCode 160) does not exactly equal to space (charCode 32) jquery's .text() encodes HTML entities to their direct unicode equivalence, and so &nbsp; becomes String.fromCharCode(160) You can solve it by replaceing all the the non-breaking spaces with ordinary spaces: d.text().replace(String.fromCharCode(160) /* no breaking space*/, " " /* ordinary space */) == "some text" or better yet: d.text().replace(/\s/g /* all kinds of spaces*/, " " /* ordinary space */) == "some text"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22036576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2838044/']}
jdg_382371
stackexchange
llm_judgeable_groundtruth_similarity
179671
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: Like jumping to the end of a line is Ctrl + E , where E can be thought of as end, why does it jump to the start using A ? Now provide the response and nothing else.
There are two sides to the question, the technical side and the historical side. The technical answer is because bash uses GNU Readline . In readline Control-a is bound to the function beginning-of-line , you can show this with: $ bind -q beginning-of-linebeginning-of-line can be invoked via "\C-a", "\M-OH", "\M-[1~", "\M-[7~", "\M-[H". where \C-a means "Control-a". bind -p will show all bindings (be careful using bind , it's easy to break your keyboard if you accidentally provide additional options or arguments). Some of the above bindings are added by default, others I have added (via .inputrc ) for various terminals I have used. Since bash-2.0, if the terminal termcap contains the capabilities kh , and kH then Home and End will be set to beginning-of-line and end-of-line . Both bash and readline are developed by Chet Ramey , an Emacs user and also the developer of ce an Emacs clone. (Please note, this endeavours to summarise many years of history from many decades ago, and glosses over some details.) Now, why is it Control-a in particular? Readline uses by default Emacs-like bindings . Control-a in GNU Emacs invokes move-beginning-of-line , what we consider to be the "home" function now. Stallman and Steel's original EMACS was inspired by Fred Wright's E editor (an early WYSIWYG editor) and TECO (a cryptic modal editor/language) -- EMACS was a set of macros for TECO. See Essential E [PDF] (from SAIL , 1980). E however used Control-Form for "beginning of line", this was on the "DataDisc" keyboard which had a Control key, and a Form key. The space-cadet keyboard of the time (lacking a Home key by the way, though it had an End ) is commonly blamed for the Emacs keyboard interface. One of the desirable features of EMACS was its use of TECO's Control-R "real-time" line editing mode (TECO predates CRT/keyboard terminals), you can see the key bindings on page 6 of the MIT AI Lab 1978 ITS Introduction to the EMACS editor [scanned PDF], where ┌ is used to denote Control. In this mode, the key bindings were all control sequences, largely mnemonic: Control-E End of this line , Control-P move to previous line , Control-N move to next line , Control-B backward one character , and not least Control-A move to beginning of this line , Costas' suggestion of "first letter of the alphabet" for this is as good as any. (A similar key-binding is in the tvlib macro package which aimed to make EMACS behave like the TVEDIT editor, binding control A and E to backward and forward sentence , but used different sequences for beginning and end of line.) The Control-A/Control-E bindings in "^R mode" were implemented directly in the ITS TECO (1983, version 1208, see the _teco_.tgz archive at the nocrew PDP10/ITS site, or on Github ), though I cannot determine more accurately when they first appeared, and the TECO source doesn't indicate why any particular bindings were chosen. The 1978 MIT EMACS document above implies that in 1978 EMACS did not use TECO native Control-A/Control-E, it's possible that the scrlin macro package (screen line) implemented these. To recap: bash uses readline readline key bindings follow Emacs/EMACS the original EMACS was created with TECO, inheriting many features TECO's interactive mode macros used (mostly) mnemonic control key bindings, and "start of line" ended up assigned to Control-A See also: http://www.gnu.org/gnu/rms-lisp.html http://xahlee.info/kbd/keyboard_hardware_and_key_choices.html http://blog.djmnet.org/2008/08/05/origin-of-emacs/ http://www.jwz.org/doc/emacs-timeline.html http://www.multicians.org/mepap.html *
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/179671', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/80904/']}
jdg_382372
stackexchange
llm_judgeable_groundtruth_similarity
442979
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 someone explain, in simple terms, why the following limit doesn't exist? $$\lim \limits_{x\to0}\sin\left(\left|\frac{1}{x}\right|\right)$$ The function is even, so the left hand limit must equal the right hand limit. Why does this limit not exist? Now provide the response and nothing else.
The function is indeed even, as we will see, this does not prove the existence of the limit. Assume that the limit exists. $$ \lim_{x\to 0^+} \sin\left(\frac1x \right) $$ Which is the same as your limit because the left-hand limit and right-hand limit will be equal (if the limit exists). Then since $x > 0$, I removed the absolute value sign. $$ \lim_{u\to\infty} \sin u $$ Using $u = 1/x$, we see that the limit certainly does not exist.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/442979', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35878/']}
jdg_382373
stackexchange
llm_judgeable_groundtruth_similarity
8592156
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ActiveAdmin is giving me an Undefined mixin 'global-reset'. error when it try to run rake assets:precompile ActiveAdmin is 0.3.4. I have ActiveAdmin and an assets group in my Gemfile with sass, coffee-rails and uglifier. Now provide the response and nothing else.
The problem is indeed, as @dimitar points out, the line with the catch all because the asset pipeline is trying to compile partials and since they aren't written to be compiled on their own, dependency issues appear. Depending on your app, you might need that catch all, specially if you have many JS, CoffeScript and SCSS/SASS files in several child folders. In that situation you might encounter that rails complains because something isn't compiled for production when the catch all is removed. The solution is to have a catch all that excludes the SASS partials, _filename.css.[scss|sass] and that would solve it (worked for me!). I also included some other tips from other activeadmin suggestions including exactly some ActiveAdmin dependencies to be compiled. Here's my code: # Include all JS files, also those in subdolfer or javascripts assets folder # includes for exmaple applicant.js. JS isn't the problem so the catch all works. config.assets.precompile += %w(*.js) # Replace %w( *.css *.js *.css.scss) with complex regexp avoiding SCSS partials compilation config.assets.precompile += [/^[^_]\w+\.(css|css.scss)$/] #Adding active_admin JS and CSS to the precompilation list config.assets.precompile += %w( active_admin.css active_admin.js active_admin/print.css )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8592156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1064395/']}
jdg_382374
stackexchange
llm_judgeable_groundtruth_similarity
31960010
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 confused about the input sequence and output sequence in boost asio::streambuf classes. According to the code examples (for sending data) in the documentation it seems that the buffer representing the input sequence is used for writting to socket and the one representing the output sequence is used for reading. Example - boost::asio::streambuf b;std::ostream os(&b);os << "Hello, World!\n";// try sending some data in input sequencesize_t n = sock.send(b.data());b.consume(n); // sent data is removed from input sequence Now, is there a nomenclature problem? Now provide the response and nothing else.
The nomenclature for boost::asio::streambuf is similar to that of which is defined in the C++ standard, and used across various classes in the standard template library, wherein data is written to an output stream and data is read from an input stream. For example, one could use std::cout.put() to write to the output stream, and std::cin.get() to read from the input stream. When manually controlling the streambuf input and output sequences, the general lifecycle of data is as follows: Buffers get allocated with prepare() for the output sequence. After data has been written into the output sequence's buffers, the data will be commit() ed. This committed data is removed from the output sequence and appended to the input sequence from which it can be read. Data is read from the input sequence's buffers obtained via data() . Once data has been read, it can then be removed from the input sequence by consume() . When using Boost.Asio operations that operate on streambuf or stream objects that use a streambuf , such as std::ostream , the underlying input and output sequences will be properly managed. If a buffer is provided to an operation instead, such as passing passing prepare() to a read operation or data() to a write operation, then one must explicitly handle the commit() and consume() . Here is an annotated version of the example code which writes directly from an streambuf to a socket: // The input and output sequence are empty.boost::asio::streambuf b;std::ostream os(&b);// prepare() and write to the output sequence, then commit the written// data to the input sequence. The output sequence is empty and// input sequence contains "Hello, World!\n".os << "Hello, World!\n";// Read from the input sequence, writing to the socket. The input and// output sequences remain unchanged.size_t n = sock.send(b.data());// Remove 'n' bytes from the input sequence. If the send operation sent// the entire buffer, then the input sequence would be empty.b.consume(n); And here is the annotated example for reading from a socket directly into an streambuf . The annotations assume that the word "hello" has been received, but not yet read, on the socket: boost::asio::streambuf b;// prepare() 512 bytes for the output sequence. The input sequence// is empty.auto bufs = b.prepare(512);// Read from the socket, writing into the output sequence. The// input sequence is empty and the output sequence contains "hello".size_t n = sock.receive(bufs);// Remove 'n' (5) bytes from output sequence appending them to the// input sequence. The input sequence contains "hello" and the// output sequence has 507 bytes.b.commit(n);// The input and output sequence remain unchanged.std::istream is(&b);std::string s;// Read from the input sequence and consume the read data. The string// 's' contains "hello". The input sequence is empty, the output// sequence remains unchanged.is >> s; Note how in the above examples, the steam objects handled committed and consuming the streambuf's output and input sequences. However, when the buffers themselves were used (i.e. data() and prepare() ), the code needed to explicitly handle commits and consumes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31960010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2161003/']}
jdg_382375
stackexchange
llm_judgeable_groundtruth_similarity
904630
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to show that the integral $\int_{0}^{\infty}{\frac{e^{-nx}}{\sqrt{x}}}\mathrm dx$ exists ($n$ is a natural number). I tried to use the comparison theorem by bounding from above the integrand by another function which is integrable, but I wasn't successful. The same question for this integral as well : $\int_{0}^{\infty}x^2e^{-nx}\mathrm dx$ Any help is much appreciated? Thanks! Now provide the response and nothing else.
The integrand is less than $1/\sqrt{x}$, so that $0<\int_\varepsilon^1 \frac{e^{-nx}dx}{\sqrt{x}}<\int_0^1 \frac{dx}{\sqrt{x}}=2$, and $\int_0^1 \frac{e^{-nx}dx}{\sqrt{x}}$ exists. As to $\int_1^\infty \frac{e^{-nx}dx}{\sqrt{x}}$, the integrand rapidly decreases to $0$ as $x\rightarrow\infty$, in particular, $0<\int_1^N \frac{e^{-nx}dx}{\sqrt{x}}<\int_1^\infty \frac{dx}{x^2}=1$ is sufficient.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/904630', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/132383/']}
jdg_382376
stackexchange
llm_judgeable_groundtruth_similarity
14564074
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 created some web apis and when an error happens the api returns HttpResponseMessage that is created with CreateErrorResponse message. Something like this: return Request.CreateErrorResponse( HttpStatusCode.NotFound, "Failed to find customer."); My problem is that I cannot figure out how to retrieve the message (in this case " Failed to find customer. ") in consumer application. Here's a sample of the consumer: private static void GetCustomer(){ var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); string data = "{\"LastName\": \"Test\", \"FirstName\": \"Test\""; var content = new StringContent(data, Encoding.UTF8, "application/json"); var httpResponseMessage = client.PostAsync( new Uri("http://localhost:55202/api/Customer/Find"), content).Result; if (httpResponseMessage.IsSuccessStatusCode) { var cust = httpResponseMessage.Content. ReadAsAsync<IEnumerable<CustomerMobil>>().Result; }} Any help is greatly appreciated. Now provide the response and nothing else.
Make sure you set the accept and or content type appropriately (possible source of 500 errors on parsing the request content): client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json"); Then you could just do: var errorMessage = response.Content.ReadAsStringAsync().Result; That's all on the client of course. WebApi should handle the formatting of the content appropriately based on the accept and/or content type. Curious, you might also be able to throw new HttpResponseException("Failed to find customer.", HttpStatusCode.NotFound);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14564074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82005/']}
jdg_382377
stackexchange
llm_judgeable_groundtruth_similarity
11380400
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So basically what I am trying to achieve is, when people click on first image, the rest will slide and fade, then the content loads up, when people close, it will be back into 4 images, when people click on 2nd image; images 1, 3 and 4 will slide and fade out, content shows up and so on. I tried to play around with Jquery, and still ended up with zero result. Here is the link: http://homethai.com.au/testing/test.swf Now provide the response and nothing else.
Since the blur event fires before the actual loss of focus, you cannot use .focus() right away. You have to push it down the stack, so that it executes after the input has lost focus. Put your .focus() in a timer (no delay necessary): $('input.dateValue').on('blur', function(event){ if ( ! /(\d){4}$/.test(this.value) ) { var $this = $(this).val(''); setTimeout(function (){ $this.focus(); }, 0); };}); Here's the fiddle: http://jsfiddle.net/TdfFs/ Update: to demonstrate that this does work in Chrome, I made another fiddle: http://jsfiddle.net/TdfFs/1/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11380400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1509494/']}
jdg_382378
stackexchange
llm_judgeable_groundtruth_similarity
5096194
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is probably no other way to do this, but is there a way to append the contents of one text file into another text file, while clearing the first after the move? The only way I know is to just use a reader and writer, which seems inefficient for large files... Thanks! Now provide the response and nothing else.
No, I don't think there's anything which does this. If the two files use the same encoding and you don't need to verify that they're valid, you can treat them as binary files, e.g. using (Stream input = File.OpenRead("file1.txt"))using (Stream output = new FileStream("file2.txt", FileMode.Append, FileAccess.Write, FileShare.None)){ input.CopyTo(output); // Using .NET 4}File.Delete("file1.txt"); Note that if file1.txt contains a byte order mark, you should skip past this first to avoid having it in the middle of file2.txt . If you're not using .NET 4 you can write your own equivalent of Stream.CopyTo ... even with an extension method to make the hand-over seamless: public static class StreamExtensions{ public static void CopyTo(this Stream input, Stream output) { if (input == null) { throw new ArgumentNullException("input"); } if (output == null) { throw new ArgumentNullException("output"); } byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, bytesRead); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5096194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435418/']}
jdg_382379
stackexchange
llm_judgeable_groundtruth_similarity
12648373
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since the new ADT preview version (version 21) , they have a new lint warning that tells me the next thing on the manifest file (in the application tag): Should explicitly set android:allowBackup to true or false (it's true by default, and that can have some security implications for the application's data) In the official website , they've written: A couple of new checks: you must explicitly decide whether your app allows backups, and a label check. There's a new command line flag for setting the library path. Many improvements to the incremental lint analysis while editing. What is this warning? What is the backup feature, and how do I use it? Also, why does the warning tell me it has security implications? What are the disadvantages and advantages of disabling this feature? There are two concepts of backup for the manifest: "android: allowBackup " allows to backup and restore via adb, as shown here : Whether to allow the application to participate in the backup and restore infrastructure. If this attribute is set to false, no backup or restore of the application will ever be performed, even by a full-system backup that would otherwise cause all application data to be saved via adb. The default value of this attribute is true. This is considered a security issue because people could backup your app via ADB and then get private data of your app into their PC. However, I think it's not that of a problem, since most users don't know what adb is, and if they do, they will also know how to root the device. ADB functions would only work if the device has the debugging feature enabled, and this needs the user to enable it. So, only users that connect their devices to the PC and enable the debugging feature would be affected. If they have a malicious app on their PC that uses the ADB tools, this could be problematic since the app could read the private storage data. I think Google should just add a feature that is disabled by default, in the developer category, to allow backup&restore of apps via ADB. "android: backupAgent " allows to use the backup and restore feature of the cloud, as shown here and here : The name of the class that implement's the application's backup agent, a subclass of BackupAgent. The attribute value should be a fully qualified class name (such as, "com.example.project.MyBackupAgent"). However, as a shorthand, if the first character of the name is a period (for example, ".MyBackupAgent"), it is appended to the package name specified in the element. There is no default. The name must be specified. This isn't a security issue. Now provide the response and nothing else.
For this lint warning, as for all other lint warnings, note that you can get a fuller explanation than just what is in the one line error message; you don't have to search the web for more info. If you are using lint via Eclipse, either open the lint warnings view, where you can select the lint error and see a longer explanation, or invoke the quick fix (Ctrl-1) on the error line, and one of the suggestions is "Explain this issue", which will also pop up a fuller explanation. If you are not using Eclipse, you can generate an HTML report from lint ( lint --html <filename> ) which includes full explanations next to the warnings, or you can ask lint to explain a particular issue. For example, the issue related to allowBackup has the id AllowBackup (shown at the end of the error message), so the fuller explanation is: $ ./lint --show AllowBackupAllowBackup-----------Summary: Ensure that allowBackup is explicitly set in the application'smanifestPriority: 3 / 10Severity: WarningCategory: Security The allowBackup attribute determines if an application's data can be backed up and restored, as documented here . By default, this flag is set to true . When this flag is set to true , application data can be backed up and restored by the user using adb backup and adb restore . This may have security consequences for an application. adb backup allows users who have enabled USB debugging to copy application data off of the device. Once backed up, all application data can be read by the user. adb restore allows creation of application data from a source specified by the user. Following a restore, applications should not assume that the data, file permissions, and directory permissions were created by the application itself. Setting allowBackup="false" opts an application out of both backup and restore. To fix this warning, decide whether your application should support backup and explicitly set android:allowBackup=(true|false) Click here for More information
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12648373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878126/']}
jdg_382380
stackexchange
llm_judgeable_groundtruth_similarity
571951
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have configured a Linux dhcpd server with multiple scopes on the same interface(eth0). The devices which needs these IP address(DHCP clients) are on two different remote networks. The networking team has completed all the configuration including DHCP relays in between so the requests are reaching my DHCP server in the following format: DHCPDISCOVER from macaddress via 10.238.16.10 (remote_network_1)DHCPDISCOVER from macaddress via 10.238.25.20 (remote_network_2) (I think the IPs mentioned above belongs to the remote routers which are forwarding DHCP requests to my server.) Right now the DHCP server is successfully assigning IPs from the first configured scope(10.238.16.x) to clients requesting from both remote_network_1 and remote_network_2. How can I configure it so that when a request comes in from 10.238.16.10, it assigns an 10.238.16.X IP and when it comes from 10.238.25.20, it assigns an 10.238.25.X IP. I know there are other ways to tackle this issue - like configuring dhcpd to listen on two different interfaces etc, but that won't work for me. I tried "option broadcast-address" but that didn't work. My dhcpd.conf: ddns-update-style none;default-lease-time 6000;max-lease-time 72000;authoritative;log-facility local7;subnet 10.238.24.0 netmask 255.255.255.248 {}shared-network DA { subnet 10.238.16.0 netmask 255.255.255.0{ range 10.238.16.52 10.238.16.254; option routers 10.238.24.9; option broadcast-address 10.238.16.255; } subnet 10.238.25.0 netmask 255.255.255.0{ range 10.238.25.52 10.238.25.254; option routers 10.238.24.9; option broadcast-address 10.238.25.255; }} From syslog: Feb 3 13:32:18 linux-server dhcpd: DHCPDISCOVER from b8:5e:7b:1e:c2:89 via 10.238.25.20Feb 3 13:32:19 linux-server dhcpd: DHCPOFFER on 10.238.16.53 to b8:5e:7b:1e:c2:89 (android-ba98679bfc07f0cb) via 10.238.25.20Feb 3 13:32:19 linux-server dhcpd: DHCPREQUEST for 10.238.16.53 (10.238.24.20) from b8:5e:7b:1e:c2:89 (android-ba98679bfc07f0cb) via 10.238.25.20Feb 3 13:32:19 linux-server dhcpd: DHCPACK on 10.238.16.53 to b8:5e:7b:1e:c2:89 (android-ba98679bfc07f0cb) via 10.238.25.20Feb 3 13:35:40 linux-server dhcpd: DHCPDISCOVER from 40:f3:08:89:3f:13 via 10.238.16.10Feb 3 13:35:41 linux-server dhcpd: DHCPOFFER on 10.238.16.54 to 40:f3:08:89:3f:13 (android-47aa390064e91817) via 10.238.16.10Feb 3 13:35:41 linux-server dhcpd: DHCPREQUEST for 10.238.16.54 (10.238.24.20) from 40:f3:08:89:3f:13 (android-47aa390064e91817) via 10.238.16.10Feb 3 13:35:41 linux-server dhcpd: DHCPACK on 10.238.16.54 to 40:f3:08:89:3f:13 (android-47aa390064e91817) via 10.238.16.10 Now provide the response and nothing else.
The simplest answer is, in this case, the correct answer: You will no longer be able to get firmware updates for HP equipment which is not (a) under its original factory warranty, or (b) covered by an active support contract with HP. This has a number of implications, chief among them: As a sysadmin you will have to ensure that you have an HP support contract to get continued firmware upgrades for machines that are beyond the factory warranty period. As a business this alters the cost of continuing to operate equipment beyond its initial factory warranty period (as you now have to purchase support contracts, which adds to the cost of the equipment). Ultimately what this means is the cost/benefit analysis of running HP hardware has just become more complex. How that analysis plays out for you, your company, or your clients will depends on your own internal requirements, constraints, and budgeting (and likely on your company's relationship with HP -- A company buying $500,000 of HP gear every quarter will likely get more favorable support contract terms than one that buys $50,000 every 5 years).
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/571951', 'https://serverfault.com', 'https://serverfault.com/users/101753/']}
jdg_382381
stackexchange
llm_judgeable_groundtruth_similarity
38017076
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On the face of it, this might seem like a weird thing to request but I need a comma-separated string of related items for a model. Taking the Author/Book model example from any tutorial, here's what I'm currently doing: authors = Authors.objects.all().prefetch_related('books')for author in authors: author.book_titles = ', '.join([book.title for book in author.books.all()]) It's by no means heavy, but it feels redundant. Like the database could be doing it. In an ideal world, I feel like I should able to annotate this on with one of these fancy new database functions . Here's a fantasy example, using a made-up function called Joiner(..) : Authors.objects.annotate(book_titles=Joiner('books__title', separator=', ') Is that possible? If so, how? Now provide the response and nothing else.
from django.db.models import Aggregate, CharField, Valueclass GroupConcat(Aggregate): function = 'GROUP_CONCAT' template = '%(function)s(%(expressions)s)' def __init__(self, expression, delimiter, **extra): output_field = extra.pop('output_field', CharField()) delimiter = Value(delimiter) super(GroupConcat, self).__init__( expression, delimiter, output_field=output_field, **extra) def as_postgresql(self, compiler, connection): self.function = 'STRING_AGG' return super(GroupConcat, self).as_sql(compiler, connection) Usage: Author.objects.annotate(book_titles=GroupConcat('book__title', ', ')) Custom aggregates . This should work on SQLite, MySQL and PostgreSQL.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38017076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12870/']}
jdg_382382
stackexchange
llm_judgeable_groundtruth_similarity
36484560
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now, my problem is that when I am trying to count a score line if a person writes something that is not the same as "42" in a textfield (which will be the same as the label.text) they will get punished by 1 minus point. If I have written something which is not "42" it gives me 1 minus point for it but only the first time. If I do it again the scoreline will not change so I will be stuck at the -1 scoreline. How can i do so every time I write something which is not "42" it will give me a -1 point even if I already got a -1 score? (As you can see I have set the label.text to be the same as textfield.text if you are wondering) import UIKit class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: PROBERTIES @IBOutlet weak var label: UILabel! @IBOutlet weak var textField: UITextField! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label1: UILabel! let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() textField.delegate = self imagePicker.delegate = self } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidEndEditing(textfield: UITextField) { label.text = textField.text var score = 0 if textField.text != "42" { score -= 1 } // MARK: if-statements if label.text! == "42" { label1.text = "You are correct" self.view.backgroundColor = UIColor.greenColor() score += 10 } if label.text != "42" { label1.text = "Damn, wrong" self.view.backgroundColor = UIColor.redColor() } if label.text!.isEmpty { label1.text = "Still waiting for an answer..." } if label.text == "happiness" { label1.text = "It is not a key element in the meaning of life" } if label.text == "to be happy" { label1.text = "i would rather be rich" } if label.text == "money" { label1.text = "there is more in this world than money" } if label.text == "There is no meaning of life" { label1.text = "There is a meaning to everything" } if label.text == "there is no meaning of life" { label1.text = "there is a meaning to everything" } if label.text == "to be rich" { label1.text = "Money does not solve every problem" } var scoreString = String(score) scoreLabel.text = "Your score is \(scoreString)" } Now provide the response and nothing else.
Oracle Setup : CREATE TABLE account1 ( account_id INT, name VARCHAR2(20));INSERT INTO account1 VALUES ( 1, 'Bob' );CREATE OR REPLACE FUNCTION get_accounts( Acc_id IN Account1.account_id%TYPE) RETURN account1%ROWTYPEAS l_cust_record account1%ROWTYPE;BEGIN SELECT * INTO l_cust_record FROM account1 WHERE account_id = Acc_id; RETURN l_cust_record;END;/ PL/SQL Block : DECLARE r_acct ACCOUNT1%ROWTYPE;BEGIN r_acct := get_accounts( 1 ); DBMS_OUTPUT.PUT_LINE( r_acct.name );END;/ Output : Bob
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36484560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6130454/']}
jdg_382383
stackexchange
llm_judgeable_groundtruth_similarity
9720
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Here are two questions I had ever since I first heard about plate-tectonics. How can the plates move? Before you suggest me some page to read about plate movement mechanics, let me clarify that I am not asking about the mechanics behind plate movement here. But I am talking about the physical possibility of plate movement. When we look at the map of plates, all of them are tightly packed, with not an inch of space or gap to move. The complex shape of surrounding plates, blocks all freedom of movement. Then how can the theory say that plates can move? If you can't follow my explanation, consider a jigsaw puzzle in which the blocks are correctly set up. Can we move a block from the middle now? We can not because the blocks are tightly interlocked, and because of their complex shape. The same is the situation here too, in fact much more complex! Each plates is tightly surrounded by complex shaped other plates, making any movement in any direction impossible! See the below given a map of tectonic plates for example. It is evident the plates are actually interlocked so tightly that, it is impossible to move in any direction, because of the presence of another plate in opposite direction. There is no freedom of movement available, in any direction! The complex shape of plates make movements impossible! My second question is this: It is said that, all continents were a single large continent millions of years ago. And then much later, continents 'drifted away', reaching current shape and locations. If tectonic plates does not even have hundreds of miles of gaps between them to move, how can continents drift away so far, even thousands of miles away? Certainly plates can't move this far, because the whole earth surface is divided into plates, with no space left for plates to move thousands of miles. So how did the continents drift away this far? Or do we have to assume that continents are simply floating over the tectonic plates? Is the plate tectonics theory a complete hoax? Now provide the response and nothing else.
isn't the plate tectonics theory a complete hoax? No, it isn't. It's a perfectly valid theory that has much supporting evidence from all disciples of earth sciences, and it explains features that would otherwise remain unexplained. It is so widely and universally accepted that questioning it (particularly in the way you are doing) is likely to elicit a very hostile response from the scientific community, similar to how people would react to questioning Newton's laws of gravity. How can the plates move? (before you suggest me some page to read about plate movement mechanics, let me clarify that i am not asking about the mechanics behind plate movement here. But i am talking about the physical possibility of plate movement) Since you are not asking about the mechanics I will spare you from explanation about mantle convection and similar processes. all of them are tightly packed, with not an inch of space or gap to move... You are entirely correct. They don't have any gap to move. This is why we have mountain ranges where continental plates collide (or converge): In places where an oceanic plate converges, plates can go underneath one the other in a process called subduction. This causes melting around the subducting plate, causing the formation of volcanic arcs: Where plates pull apart and diverge you can have impressive rift valleys: Or submarine trenches: And of course, let's not forget about the earthquakes that occur when all of these things form. While you may doubt it, it is very real to the people affected by such natural disasters. Everything I just mentioned happens because the plates are so tight and have nowhere to move. Just because you think a theory is incorrect because it doesn't fit your extremely simplistic way of how things should work, does not mean it is in fact incorrect. Nature does its thing regardless of what you, me, and everyone else thinks. (Photographs either public domain or mine)
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/9720', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/7534/']}
jdg_382384
stackexchange
llm_judgeable_groundtruth_similarity
7350258
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After trying to print retainCount of object I get 2147483647. Why do I get such a result? It should be 1, shouldn't? NSString *myStr = [NSString new];NSUInteger retCount = [myStr retainCount];NSLog(@"refCount = %u", retCount); 2011-09-08 17:59:18.759 Test[51972:207] refCount = 2147483647 I use XCode Version 4.1. Tried compilers GCC 4.2 and LLVM GCC 4.2 - the same result.Garbage Collection option was set to unsupported. Now provide the response and nothing else.
NSString is somewhat special when it comes to memory management. String literals (something like @"foo" ) are effectively singletons, every string with the same content is the same object because it can't be modified anyway. As [NSString new] always creates an empty string that cannot be modified, you'll always get the same instance which cannot be released (thus the high retainCount ). Try this snippet: NSString *string1 = [NSString new];NSString *string2 = [NSString new];NSLog(@"Memory address of string1: %p", string1);NSLog(@"Memory address of string2: %p", string2); You'll see that both strings have the same memory address and are therefore the same object.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7350258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/378882/']}
jdg_382385
stackexchange
llm_judgeable_groundtruth_similarity
12084177
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say a table has, name, ID, age, sex, education, etc. ID is the key and the table is also indexed for name, age and sex. I need all male students, older than 25, sorted by their names. This is easy in mySQL: SELECT * FROM table WHERE age > 25 AND sex = "M" ORDER BY name IndexDB allows creation of an index and orders the query based on that index. But it doesn't allow multiple queries like age and sex. I found a small library called queryIndexedDB (https://github.com/philikon/queryIndexedDB) which allows compound queries but doesn't provide sorted results. So is there a way to make a sorted compound query, while using IndexedDB? Now provide the response and nothing else.
The term compound query as used in this answer refers to an SQL SELECT statement involving more than one condition in its WHERE clause. Although such queries are not mentioned in the indexedDB specification, you can approximate the behavior of a compound query by creating an index with a keypath that consists of an array of property names. This is completely unrelated to using the multi-entry flag when creating an index. The multi-entry flag adjusts how indexedDB creates an index over a single array property. We are indexing an array of object properties, not the values of a single array property of an object. Creating the index In this example, 'name', 'gender', and 'age' correspond to property names of student objects stored within the students object store. // An example student object in the students storevar foo = { 'name': 'bar', 'age': 15, 'gender': 'M'};function myOnUpgradeNeeded(event) { var db = event.target.result; var students = db.createObjectStore('students'); var name = 'males25'; var keyPath = ['name', 'gender', 'age']; students.createIndex(name, keyPath);} Opening a cursor on the index You can then open a cursor on the index: var students = transaction.objectStore('students');var index = students.index('males25');var lowerBound = ['AAAAA','male',26];var upperBound = ['ZZZZZ','male',200];var range = IDBKeyRange.bound(lowerBound, upperBound);var request = index.openCursor(range); However , for reasons I am about to explain, this won't always work. Aside: using a range parameter to openCursor or get is optional. If you do not specify a range, then IDBKeyRange.only is implicitly used for you. In other words, you only need to use IDBKeyRange for bounded cursors. Fundamental index concepts Indices are like object stores but are not directly mutable. Instead, you use CRUD (create read update delete) operations on the referenced object store, and then indexedDB automatically cascades updates to the index. Understanding sorting is fundamental to understanding indices. An index is basically just a specially sorted collection of objects. Technically, it is also filtered, but I'll touch on that in a moment. Generally, when you open a cursor on an index, you are iterating according to the index's order. This order could be, and probably is, different than the order of the objects in the referenced object store. The order is important because this allows iteration to be more efficient, and allows a custom lower and upper bound that only makes sense in the context of an index-specific order. The objects in the index are sorted at the time changes to the store occur. When you add an object to the store, it is added to the proper position in the index. Sorting boils down to a comparison function, similar to Array.prototype.sort, that compares two items and returns whether one object is less than the other one, greater than the other one, or equal. So we can understand sorting behavior better by diving into more details on comparison functions. Strings are compared lexicographically This means, for example, that 'Z' is less than 'a' and that the string '10' is greater than the string '020'. Values of different types are compared using a specification-defined order For example, the specification specifies how a string-type value comes before or after a date-type value. It does not matter what the values contain, just the types. IndexedDB does not coerce types for you. You can shoot yourself in the foot here. You generally never want to be comparing different types. Objects with undefined properties do not appear in indices whose keypath is comprised of one or more of those properties As I mentioned, indices may not always include all objects from the referenced object store. When you put an object into an object store, the object will not appear in the index if it has missing values for the properties upon which the index is based. For example, if we have a student where we don't know the age, and we insert this into the students store, the particular student will not appear in the males25 index. Remember this when you wonder why an object doesn't appear when iterating a cursor on the index. Also note the subtle difference between null and an empty string. An empty string is not a missing value. An object with an empty string for a property could still appear in an index based on that property, but will not appear in the index if the property is present but undefined or not present. And if it is not in the index, you won't see it when iterating a cursor over the index. You must specify each property of an array keypath when creating an IDBKeyRange You must specify a valid value for each property in the array keypath when creating a lower or upper bound to use in a range for when opening a cursor over that range. Otherwise, you will get some type of Javascript error (varies by browser). For example, you cannot create a range such as IDBKeyRange.only([undefined, 'male', 25]) because the name property is undefined. Confusingly, if you specify the wrong type of value, such as IDBKeyRange.only(['male', 25]) , where name is undefined, you won't get an error in the above sense, but you will get nonsensical results. There is an exception to this general rule: you can compare arrays of different lengths. Therefore, you technically can omit properties from the range, provided that you do so from the end of the array, and that you appropriately truncate the array. For example, you could use IDBKeyRange.only(['josh','male']) . Short-circuited array sorting The indexedDB specification provides an explicit method for sorting arrays: Values of type Array are compared to other values of type Array as follows: Let A be the first Array value and B be the second Array value. Let length be the lesser of A's length and B's length. Let i be 0. If the ith value of A is less than the ith value of B, then A is lessthan B. Skip the remaining steps. If the ith value of A is greater than the ith value of B, then A is greater than B. Skip the remaining steps. Increase i by 1. If i is not equal to length, go back to step 4. Otherwise continue to next step. If A's length is less than B's length, then A is less than B. If A's length is greater than B's length, then A is greater than B. Otherwise A and B are equal. The catch is in steps 4 and 5: Skip the remaining steps . What this basically means is that if we are comparing two arrays for order, such as [1,'Z'] and [0,'A'], the method only considers the first element because at that point 1 is > 0. It never gets around to checking Z vs A because of short-circuited evaluation (steps 4 and 5 in the spec). So, the earlier example is not going to work. It actually works more like the following: WHERE (students.name >= 'AAAAA' && students.name <= 'ZZZZZ') || (students.name >= 'AAAAA' && students.name <= 'ZZZZZ' && students.gender >= 'male' && students.gender <= 'male') || (students.name >= 'AAAAA' && students.name <= 'ZZZZZ' && students.gender >= 'male' && students.gender <= 'male' && students.age >= 26 && students.age <= 200) If you have any experience with such Boolean clauses in SQL or in general programming, then you already should recognize how the full set of conditions are not necessarily involved. That means you will not get the list of objects you want, and this is why you cannot truly get the same behavior as SQL compound queries. Dealing with short-circuiting You cannot easily avoid this short-circuiting behavior in the current implementation. In the worst case you have to load all objects from the store/index into memory and then sort the collection using your own custom sorting function. There are ways to minimize or avoid some of the short-circuiting issues: For example, if you are using index.get(array) or index.openCursor(array), then there is no short-circuiting concern. There is either an entire match or not an entire match. In this case, the comparison function is only evaluating whether two values are the same, not whether one is greater than or less than the other. Other techniques to consider: Rearrange the elements of the keypath from narrowest to widest. Basically provide early clamps on ranges that cut off some of the unwanted results of short-circuiting. Store a wrapped object in a store that uses specially customized properties so that it can be sorted using a non-array keypath (a non-compound index), or, can make use of a compound index that is not affected by the short-circuiting behavior. Use multiple indices. This leads to the exploding index problem . Note this link is about another no-sql database, but the same concepts and explanation applies to indexedDB, and the link is a reasonable (and lengthy and complicated) explanation so I am not repeating it here. One of the creators of indexedDB (the spec, and the Chrome implementation) recently suggested using cursor.continue: https://gist.github.com/inexorabletash/704e9688f99ac12dd336 Testing with indexedDB.cmp The cmp function provides a quick and simple way to examine how sorting works. For example: var a = ['Hello',1];var b = ['World',2];alert(indexedDB.cmp(a,b)); One nice property of the indexedDB.cmp function is that its signature is the same as the function parameter to Array.prototype.sort . You can easily test values from the console without dealing with connections/schemas/indices and all that. Furthermore, indexedDB.cmp is synchronous, so your test code does not need to involve async callbacks/promises.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12084177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218900/']}
jdg_382386
stackexchange
llm_judgeable_groundtruth_similarity
4020757
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 never been this frustrated in my life. cant even do the basics here.. just need to make a simple tic tac toe program. i feel so alone in this world right now.. i get the basic idea, but can't put it together logically. Class instance variables: private char[][] board; private char player; // 'X' or 'O' Methods: public TicTacToe() public void print() public boolean play(String s) public boolean won() public boolean stalemate() Here's what i've got for code: import java.util.Scanner;public class Six1{ public static void main(String[] args) { TicTacToe ttt = new TicTacToe(); ttt.TicTacToe(); ttt.print(); } static class TicTacToe { private char player; // 'X' or 'O' private char[][] board; // make board public TicTacToe() { // construct board board = new char[3][3]; // initialize elements for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = ' ' ; } } } // print board public void print() { for ( int i = 0; i < 3; i++) { System.out.println(" "); for( int j = 0; j < 3; j++) { System.out.print(board[i][j] + " "); } System.out.println("\n------"); } } }} Now provide the response and nothing else.
You don't have a lot done yet, but what you have seems mostly reasonable. You may be over-complicating things by using an inner class. And you'll need to put something in main if you want something to happen. You can't write the whole program all at once. You can either start at the top and work down to the details, or work on the details and then assemble them into a working whole. Working top-down If you're not sure where to start, this can be a good way to get things moving. Write the main body of the code using whatever functions you wish existed. Maybe you'd start with public static void main(String[] args) { printBoard(); while (!isWinner()) { readMove(); // get move from stdin and mark on board printBoard(); // redraw board } printWinner(); // say who won} It's ok that these functions don't exist yet. Once you've got the main level, start implementing these made-up functions, using more made-up functions if necessary. Repeat until you get down to simple functions that you do know how to implement. If you want to compile your code without implementing every method, you can use throw new UnsupportedOperationException("not implemented"); as the body of any methods that need to return values. Working bottom-up If you know you'll need certain pieces but aren't sure how they'll fit together, start with this method. You know you'll need some way to ask the user what move they want to make. So create a function that does that and test it on it's own. You know you'll need a way to check if there's a winner. Hardcode some values into board[] and test your isWinner() function. Once you've got some working pieces you can assemble them into larger and larger chunks until you've got a functioning program.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4020757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485398/']}
jdg_382387
stackexchange
llm_judgeable_groundtruth_similarity
6380243
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 strip everything in a string after the character "-" has occurred for the second time? For example: Today is - Friday and tomorrow is - Saturday In this case i would want Saturday to be removed along with the last - so somehow strip : "- Saturday" Any help is very much appreciated :) I can only seem to get everything to be removed after the first "-". Now provide the response and nothing else.
Use strpos to find the first occurrence and use it again to find the point to end using the offset option with the value from previous. Then use substr . $newstr = substr($str, 0, strpos($str, '-', strpos($str, '-')+1));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6380243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597129/']}
jdg_382388
stackexchange
llm_judgeable_groundtruth_similarity
19099
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm starting to learn Machine learning from Tensorflow website. I have developed a very very rudimentary understanding of the flow a deep learning program follows (this method makes me learn fast instead of reading books and big articles). There are a few confusing things that I have come across, 2 of them are: Bias Weight In the MNIST tutorial on tensorflow website, they have mentioned that we need bias and weight to find the evidence of the existence of a particular pattern in an image. What I don't understand is, where and how the values for Bias and Weight are determined? Do we have to provide these values or does the TensorFlow library calculates these values automatically based on the training data set? Also if you could provide some suggestions on how to accelerate my pace in deep learning, that would be great! Tensorflow Beginners Tutorial Now provide the response and nothing else.
Mathematically speaking, Imagine you are a model (No! not that kind, figure 8 ones). Bias is simply how biased you are. If you are a Nigerian, and you are asked "Which nationality have the most beautiful women" you might say Nigerian Ladies. We can say it's because you are biased. So your formula is $Y = WX + nigerian$ . So what do you understand? Biased is that pre-assumption in a model like you have. As for weight, logically speaking, Weight is your Gradient (as in linear algebra). What is Gradient? it's the steepness of the Linear function. What makes the linear gradient very steep (High positive value)? It's because little changes in X(input) causes Large differences in Y axis(output). So you (Not as a Model anymore, but a brilliant Mathematician (your alter ego)) or your Computer tries to find this gradient, which you can call weight. The difference is that you use a pencil and graph book to find this, but the black box does its electronic Magic with registers. In the Machine Learning Process, computers, or you, try to draw many straight lines or Linear functions across the data points. Why do you try to draw many straight lines? Because in your graph book/Computer memory, you are trying the see the line that fit appropriately. How do I or Computer know the line that fits appropriately? In my secondary school, I was taught to draw a line across the data points, visually checking the line that cuts through perfectly in the middle of all the data point.(Forget those A.I hype, our brains can calculate by just staring at things). But as for the computer, it tries the standard deviation and variance of each line towards the data points. The line with the least deviation (sometimes we call it the error function) is chosen. Cool! so and what happens The gradient of that line is calculated, let's say the Weight of the Learning problem is Calculated. That's Machine Learning at its basic understand and a high school student plotting graph in his/her Graphbook.
{}
{'log_upvote_score': 5, 'links': ['https://datascience.stackexchange.com/questions/19099', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/32459/']}
jdg_382389
stackexchange
llm_judgeable_groundtruth_similarity
19485536
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: lets say we have a function which prints text to the console and in which we do not have control over the source but we are able to call it. For example void foo() { std::cout<<"hello world"<<std::endl; print_to_console(); // this could be printed from anything} is it possible to redirect the output of the above function to a string without changing the function itself? I'm not looking for a way to do this via terminal Now provide the response and nothing else.
Yes. That can be done. Here is a little demo: #include <sstream>#include <iostream>void print_to_console() { std::cout << "Hello from print_to_console()" << std::endl;}void foo(){ std::cout<<"hello world"<<std::endl; print_to_console(); // this could be printed from anything}int main(){ std::stringstream ss; //change the underlying buffer and save the old buffer auto old_buf = std::cout.rdbuf(ss.rdbuf()); foo(); //all the std::cout goes to ss std::cout.rdbuf(old_buf); //reset std::cout << "<redirected-output>\n" << ss.str() << "</redirected-output>" << std::endl;} Output: <redirected-output>hello worldHello from print_to_console()</redirected-output> See Online Demo .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19485536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/848277/']}
jdg_382390
stackexchange
llm_judgeable_groundtruth_similarity
23695736
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 starting a new project, and I am also fairly new to Zend Framework 2. What are your suggestions to generate a pdf from an html code that you want to pass as a variable ($html)? I was reading the web that DOMPDF is pretty good, but I'm not sure how to use it, looking at documentation. What would be the easiest way for a beginner? Now provide the response and nothing else.
Your selection of DOMPDF is right. It's the most easiest to use in Zend Framework 2. Just add a simple module(DOMPDFModule) and you are ready to go. As you are a newbie to Zend Framework 2; here is how to use it. Step 1: Downloading DOMPDFModule Add "dino/dompdf-module": "dev-master" to the require section in composer.json file Example: composer.json "require": { "php": ">=5.3.3", "zendframework/zendframework": "2.2.*", "dino/dompdf-module": "dev-master"} Now install or update the dependencies using composer . Composer will automatically include the dependencies which we would otherwise include using include("dompdf.php") Example: php composer.phar install Next we have to add DOMPDFModule to the modules section in config/application.config.php Example: application.config.php 'modules' => array( 'Application', 'DOMPDFModule',), And we are ready to use it in our project. Step 2: Using it in Zend Framework 2 Project Open up the controller in which we are going to generate the PDF and add use DOMPDFModule\View\Model\PdfModel; to the top; after the namespace. Example: IndexController.php <?phpnamespace Application\Controller;use Zend\Mvc\Controller\AbstractActionController;use Zend\View\Model\ViewModel;use DOMPDFModule\View\Model\PdfModel; Next we have to place the necessary PDF generation code to the required action. Example: I'm assuming; to download pdf we are using the following route. example.com/generatepdf For that create a generatepdfAction() method in which we will place the PDF generation logic as follows. IndexController.php public function generatepdfAction(){ $pdf = new PdfModel(); return $pdf;} As most Action in Zend Framework 2; this action will also have a corresponding view file generatepdf.phtml where we actually place the HTML which is to be converted to PDF. Example: generatepdf.phtml <html> <body> <h1>My Name is Blah</h1> </body></html> Now if we go to the route we created; a PDF will be shown in the same window if the browser supports viewing PDF. Passing variables to view file It can be done in generatepdfAction() by using the setVariables() method of PdfModel() Example: IndexController.php public function generatepdfAction(){ $pdf = new PdfModel(); $pdf->setVariables(array( 'name' => 'John Doe', )); return $pdf;} generatepdf.phtml <html> <body> <h1>My Name is <?php echo $this->name; ?></h1> </body></html> Setting filename and forcing download Setting filename will trigger auto download of the PDF file. A filename can be set using the setOption() method of PdfModel() . Example: IndexController.php public function generatepdfAction(){ $pdf = new PdfModel(); $pdf->setOption("filename", "my-file"); return $pdf;} File extension(.pdf) will be added automatically. Setting paper size and paper orientation Paper size and paper orientation can be set by the paperSize and paperOrientation options Example: IndexController.php public function generatepdfAction(){ $pdf = new PdfModel(); $pdf->setOption("paperSize", "a4"); //Defaults to 8x11 $pdf->setOption("paperOrientation", "landscape"); //Defaults to portrait return $pdf;} Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23695736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2610367/']}
jdg_382391
stackexchange
llm_judgeable_groundtruth_similarity
126107
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: suppose you have a sample of size $N$ that for some reason you want to bootstrap to produce a sample of size $M$ . I am trying to produce a closed form solution for the expected proportion of the sample that will be present when I bootstrap a sample. I have not been able to produce it, however, I have used Matlab to come up with a numerical approximation. I took a sample of size 100 and produced bootstrap 300 samples of sizes varying from 1 to 500. For a fixed bootstrap sample size, I later estimated the mean proportion of the original sample that got into the bootstrapped sample by averaging over the number of unique values. This is what I got: Any ideas on how to produced the closed form for this number? Now provide the response and nothing else.
This is related to collision-counting in the birthday problem . Imagine you walk into a room of $k$ people. The probability at least one shares a birthday with you is $q(k;n) = 1 - \left( \frac{n-1}{n} \right)^k$, where $n$ is the number of different birthday slots (days in the year). The expected number you add to the total number of different birthdays in the room when you walk in is therefore $1-q(k;n)=\left( \frac{n-1}{n} \right)^k$ So by the law of iterated expectations, the expected number of different birthdays after $m$ people have entered is $\sum_{i=1}^m \left( \frac{n-1}{n} \right)^{i-1} = \sum_{i=0}^{m-1} \left( \frac{n-1}{n} \right)^i$ This is sum to $m$ terms of a geometric series, which is straightforward: $\hspace{2.3cm} = \frac{1- \left( \frac{n-1}{n} \right)^m}{1-\frac{n-1}{n}}=n\left[1- \left( \frac{n-1}{n} \right)^m\right]$ Check: at n=100, m=50 this gives $\approx$ 39.4994, while simulation gives: > mean(replicate(10000,length(unique(sample(1:100,50,replace=TRUE)))))[1] 39.4938 so that looks okay. The expected fraction is then $\frac{1}{n}$th of that, $1- \left( \frac{n-1}{n} \right)^m$. Note that if $n$ is large, $(1-\frac{1}{n})^n\approx e^{-1}$, so if $m$ is some value that's at least a large fraction of $n$, $(1-\frac{1}{n})^m\approx e^{-\frac{m}{n}}$, so we get that the expected number is approximately $n (1- e^{-\frac{m}{n}})$. Let's try that approximation on the above example where $m=50$ and $n=100$: $100 (1-e^{-\frac{50}{100}})=100(1-e^{-\frac{1}{2}})\approx 39.347$, which is fairly close to the exact answer - for a given $m/n$ it improves with larger $n$. So a quick and reasonably accurate approximation to the fraction is $(1- e^{-\frac{m}{n}})$. Note that when $m=n$ this gives the usual "0.632" rule.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/126107', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/61812/']}
jdg_382392
stackexchange
llm_judgeable_groundtruth_similarity
14105422
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Reading about F# today and I'm not clear on one thing: From: http://msdn.microsoft.com/en-us/library/dd233200.aspx you need only one element of the tuple, the wildcard character (the underscore) can be used to avoid creating a new name for a variable that you do not need let (a, _) = (1, 2) I can't think of a time that I've been in this situation. Why would you avoid creating a variable name? Now provide the response and nothing else.
Interesting question. There are many trade-offs involved here. Your comparisons have been with the Ruby programming language so perhaps the first trade-off you should consider is static typing. If you use the pattern x, _, _ then F# knows you are referring to the first element of a triple of exactly three elements and will enforce this constraint at compile time. Ruby cannot. F# also checks patterns for exhaustiveness and redundancy. Again, Ruby cannot. Your comparisons have also used only flat patterns. Consider the patterns _, (x, _) or x, None | _, Some x or [] | [_] and so on. These are not so easily translated. Finally, I'd mention that Standard ML is a programming language related to F# and it does provide operators called #1 etc. to extract the first element of a tuple with an arbitrary number of elements (see here ) so this idea was implemented and discarded decades ago. I believe this is because SML's #n notation culminates in incomprehensible error messages within the constraints of the type system. For example, a function that uses #n is not making it clear what the arity of the tuple is but functions cannot be generic over tuple arity so this must result in an error message saying that you must give more type information but many users found that confusing. With the CAML/OCaml/F# approach there is no such confusion.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14105422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30946/']}
jdg_382393
stackexchange
llm_judgeable_groundtruth_similarity
17467441
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 bash, we can: python - << EOFimport osprint 'hello'EOF to embed python code snippet in bash script. But in Windows batch, this doesn't work - although I can still use python -c but that requires me to collpase my code into one line, which is something I try to avoid. Is there a way to achieve this in batch script? Thanks. Now provide the response and nothing else.
You could use a hybrid technic, this solution works also with an python import. 1>2# : ^'''@echo offecho normal echo batch codeecho Switch to pythonpython "%~f0"exit /brem ^'''print "This is Python code" The batch code is in a multiline string ''' so this is invisible for python. The batch parser doesn't see the python code, as it exits before. The first line is the key. It is valid for batch as also for python! In python it's only a senseless compare 1>2 without output, the rest of the line is a comment by the # . For batch 1>2# is a redirection of stream 1 to the file 2# . The command is a colon : this indicates a label and labeled lines are never printed. Then the last caret simply append the next line to the label line, so batch doesn't see the ''' line.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17467441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70198/']}
jdg_382394
stackexchange
llm_judgeable_groundtruth_similarity
309453
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: In Bash, piping tail -f to a read loop blocks indefinitely. while read LINE0 do echo "${LINE0}"; done < <( tail -n 3 -f /tmp/file0.txt | grep '.*' ) # hangs Remove the -f or | grep '.*' , then the loop will iterate. The following does not hang. tail -n 3 -f /tmp/file0.txt | grep '.*' What causes this behavior? Is there anyway in Bash to follow a file and read in a pipe expression? Now provide the response and nothing else.
In the pipeline, grep 's output is buffered. With the GNU implementation of grep , you can force flush the output after each line with --line-buffered ( documentation here ); for example: tail -n 3 -f /tmp/file0.txt | grep --line-buffered '.*' | while IFS= read -r LINE0 do printf '%s\n' "${LINE0}" done
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/309453', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/164612/']}
jdg_382395
stackexchange
llm_judgeable_groundtruth_similarity
43864856
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 get list of URLs in non-blocking mode, but not in parallel. It should be sequential requests one by one. How can I realize that? I cannot find examples. Documentation and articles highlight only parallel execution. Now my code looks like the following (simplified): my $delay = Mojo::IOLoop::Delay->new;$delay->steps( sub { build_report(); say "done"; });sub parse_data { ...; my $url = shift @urls; my $end = $delay->begin; $ua->get( $url => \&parse_data ); $end->();}my $end = $delay->begin;$ua->get( $url => \&parse_data );$end->();$delay->wait; I want to avoid multiple closures by using Mojo::IOLoop::Delay . Now provide the response and nothing else.
One solution without using np.rot90 to rotate in clockwise direction would be to swap the last two axes and then flip the last one - img.swapaxes(-2,-1)[...,::-1] For counter-clockwise rotation, flip the second last axis - img.swapaxes(-2,-1)[...,::-1,:] With np.rot90 , the counter-clockwise rotation would be - np.rot90(img,axes=(-2,-1)) Sample run - In [39]: img = np.random.randint(0,255,(7,4,3,5))In [40]: out_CW = img.swapaxes(-2,-1)[...,::-1] # ClockwiseIn [41]: out_CCW = img.swapaxes(-2,-1)[...,::-1,:] # Counter-ClockwiseIn [42]: img[0,0,:,:]Out[42]: array([[142, 181, 141, 81, 42], [ 1, 126, 145, 242, 118], [112, 115, 128, 0, 151]])In [43]: out_CW[0,0,:,:]Out[43]: array([[112, 1, 142], [115, 126, 181], [128, 145, 141], [ 0, 242, 81], [151, 118, 42]])In [44]: out_CCW[0,0,:,:]Out[44]: array([[ 42, 118, 151], [ 81, 242, 0], [141, 145, 128], [181, 126, 115], [142, 1, 112]]) Runtime test In [41]: img = np.random.randint(0,255,(800,600))# @Manel Fornos's Scipy based rotate funcIn [42]: %timeit rotate(img, 90)10 loops, best of 3: 60.8 ms per loopIn [43]: %timeit np.rot90(img,axes=(-2,-1))100000 loops, best of 3: 4.19 µs per loopIn [44]: %timeit img.swapaxes(-2,-1)[...,::-1,:]1000000 loops, best of 3: 480 ns per loop Thus, for rotating by 90 degrees or multiples of it, numpy.dot or swapping axes based ones seem pretty good in terms of performance and also more importantly do not perform any interpolation that would change the values otherwise as done by Scipy's rotate based function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43864856', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/874760/']}
jdg_382396
stackexchange
llm_judgeable_groundtruth_similarity
15419632
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 WebBrowser control on a form, but for the most part it remains hidden from the user. It is there to handle a series of login and other tasks. I have to use this control because there is a ton of Javascript that handles the login. (i.e., I can't just switch to a WebClient object.) After hopping around a bit, we end up wanting to download a PDF file. But instead of downloading, the file is displayed within the webBrowser control, which the user can not see. How can I download the PDF instead of having it load in the browser control? Now provide the response and nothing else.
Add a SaveFileDialog control to your form, then add the following code on your WebBrowser's Navigating event: private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e){ if (e.Url.Segments[e.Url.Segments.Length - 1].EndsWith(".pdf")) { e.Cancel = true; string filepath = null; saveFileDialog1.FileName = e.Url.Segments[e.Url.Segments.Length - 1]; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { filepath = saveFileDialog1.FileName; WebClient client = new WebClient(); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(e.Url, filepath); } }} //Callback function void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e){ MessageBox.Show("File downloaded");} Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d338a2c8-96df-4cb0-b8be-c5fbdd7c9202
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15419632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53531/']}
jdg_382397
stackexchange
llm_judgeable_groundtruth_similarity
5160045
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 new to jqGrid and I have found it difficult to follow the documentation jqGrid Documentation I cannot figure out how to call a WebMethod when setting up the JQGrid. I have been successful in making an Ajax call to get the data and then setting up the JQGrid with local data. I think its an extra step in the setup process and that I should be able to provide the path to the webmethod using the url property. The editurl property is the same way. I am never actually receiving the post to the server. Original Code Attempted JQGrid Setup function GetData(){ $('#list').jqGrid({ type: "POST", url: "Default.aspx/GetUsersJSON", datatype: "json", height: 250, colName: ['Username', 'Email'], colModel: [ ... }).jqGrid( 'navGrid', '#pager', { edit: true, add: true, del: true });} WebMethod [WebMethod] public static string GetUsersJSON() { var users = new List(); using(UserAdministrationSandboxDataContext uasd = new UserAdministrationSandboxDataContext()) { users = uasd.GetUserList(); } JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(users); } Current Code I got it working correctly now, but I still have one final question. Why did I have to set the 'repeatitems: false' in order to display the content? Some of the caveats to get this to work include the different ways to setup the ajax request. (Ajax: type) is (jqgrid : mtype)(Ajax: contentType) is (jqgrid : ajaxGridOptions: { contentType: }) And finally understanding the documentation from the documentation on how to setup the JSONReader. Hope this helps others and thanks Oleg for all your help. JS function GetUserDataFromServer(){ $('#list').jqGrid({ url: "Default.aspx/GetUsersJSON", mtype: 'POST', ajaxGridOptions: { contentType: "application/json" }, datatype: "json", serializeGridData: function (postData) { return JSON.stringify(postData); }, jsonReader: { root: function (obj) { return obj.d; }, page: function (obj) { return 1; }, total: function (obj) { return 1; }, records: function (obj) { return obj.d.length; }, id:'0', cell:'', repeatitems: false }, datatype: "json", height: 250, colName: ['Username', 'Email'], colModel: [ { name: 'Username', index: 'Username', width: 100, editable: true }, { name: 'Email', index: 'Email', width: 220, editable: true }, { name: 'IsLockedOut', index: 'IsLockedOut', width: 100, editable: true, edittype: 'checkbox' } ], caption: "Users" })} Web Method [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static List GetUsersJSON() { using (UserAdministrationSandboxDataContext uasd = new UserAdministrationSandboxDataContext()) { return uasd.GetUserList(); } } One JSON Object from the List {"__type":"UserAdministrationSandbox.UserData","PKID":"00000000-0000-0000-0000-000000000001","Username":"TestUser","ApplicationName":"Test","Email":"[email protected]","Comment":"TestUser","Password":"D41D8CD98F00B204E9800998ECF8427E","PasswordQuestion":"Is this a blank Password?","PasswordAnswer":null,"IsApproved":true,"LastActivityDate":"\/Date(1298869200000)\/","LastLoginDate":"\/Date(1298869200000)\/","LastPasswordChangedDate":"\/Date(1298869200000)\/","CreationDate":"\/Date(1298869200000)\/","IsOnLine":false,"IsLockedOut":false,"LastLockedOutDate":"\/Date(1298869200000)\/","FailedPasswordAttemptCount":0,"FailedPasswordAttemptWindowStart":null,"FailedPasswordAnswerAttemptCount":null,"FailedPasswordAnswerAttemptWindowStart":null} Now provide the response and nothing else.
First of all I hope the code examples from the answer could help you (see also this answer ). The main idea, that you should use following additional jqGrid parameters ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },serializeGridData: function (postData) { return JSON.stringify(postData);},jsonReader: { root: "d.rows", page: "d.page", total: "d.total", records: "d.records" }; If the server not set rows , page , total and records parameter in the response and just return the list of data like in your case you can use the following jsonReader jsonReader: { root: function (obj) { return obj.d; }, page: function (obj) { return 1; }, total: function (obj) { return 1; }, records: function (obj) { return obj.d.length; }} (see here and here ). In the case if you don't want implement server side data paging, sorting and filtering I recommend you to use loadonce:true . Moreover your code have some problems. The first one is that you call JavaScriptSerializer.Serialize manually in your web method. If you use dataType: "json" the JSON response will be converted to object by $.ajax . It is so in your case also. Because of that the msg parameter of the success handler has d property. But msg.d is not the object, but one more JSON string which you convert to object with eval(msg.d) . The reason is that the results of your method will be converted to JSON one more time. To fix the problem you should change the web method GetUsersJSON to the following: [WebMethod][ScriptMethod (ResponseFormat = ResponseFormat.Json)]public static List<User> GetUsersJSON(){ using(UserAdministrationSandboxDataContext uasd = new UserAdministrationSandboxDataContext()) { return uasd.GetUserList(); }} then you can place data: eval(msg.d) in your previous example to data: msg.d . Typically one use additional [ScriptMethod (ResponseFormat = ResponseFormat.Json)] or [ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] attribute for the web method, but in many cases (it seems also in your case) it is not needed. After the usage of ajaxGridOptions , serializeGridData and jsonReader jqGrid will able to read the page of data, but the data should be in JSON format and not twice encoded JSON format. UPDATED : You ask me to comment why you need to use repeatitems:false setting in the jsonReader to be able to read your data. It is important question for understanding how jsonReader work, but the answer will take a little place. In general there are two main styles how the JSON data can be formatted for jqGrid. It should be array of data for grid rows. Every item of the array represent the row in grid and the row should be in one from the two main form 1) as an object with named properties like {"Username":"TestUser","Email":"[email protected]","Comment":"..","IsApproved":true} or 2) an array of strings like ["TestUser","[email protected]","true"] or ["TestUser","[email protected]","1"] jqGrid map both "true" and "1" values to the boolean value "true" in case of edittype:'checkbox' setting. How you can understand if the grid has many checkbox-columns the usage of "1"/"0" format can reduce the size of transfered data. The repeatitems:false option means that jqGrid should scan JSON data for the first (object style) representation of data. The repeatitems:true means the second (array style) representation. By the way if you use the object style ( repeatitems:false ) the cell setting of the jsonReader will be not used and you can remove cell:'' setting which you use. The id option of the jsonReader in numeric form is practical if you have one column in the grid with unique values. The option id:'0' means that the value of the column "Username" will be used as the row id. If you examine the grid with Firebug of Developer tools of IE or Chrome you will see that the corresponding <tr> element has attribute id="TestUser" (used in your data). Because duplicate in ids are not allowed on one HTML page, you can understand that it is very important to define grid with correct unique ids. If jqGrid not find id column in the data it will use ids "1", "2", ... So if you see that your grid has the values you should search for the error in the id property of the jsonReader . The next important thing is the advantages and disadvantages of two ways of the data representation: object style ( repeatitems:false ) and array style ( repeatitems:true ) The object style has advantage in two main cases you want just post existing objects with as less work on the server as possible (quick and dirty solution) you get data from the server which interface you can not change. In all other situations the array style ( repeatitems:true ) has advantages compared with the object style. The main from there In the object style representation will be send frequently more data as needed . In your example the "Comment" property for example will be send which will not be used by jqGrid. The data from array style are much more compacter because you will not transfer the name of properties (which are constants ) in every row. So if you want to reduce the size of transfered data and you can make changes on the server side I would recommend you to use array style ( repeatitems:true ) of representation of data. In the case the cell:'' property of the jsonReader can be good used. I recommend you to look though the part of jqGrid documentation about jsonReader , xmlReader and localReader .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5160045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375512/']}
jdg_382398
stackexchange
llm_judgeable_groundtruth_similarity
16989647
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 tab delimited .txt file that I'm trying to import into a matrix array in Python of the same format as the text file is as shown below: 123088 266 248 244 266 244 277 123425 275 244 241 289 248 231 123540 156 654 189 354 156 987 Note there are many, many more rows of the stuff above (roughly 200) that I want to pass into Python and maintain the same formatting when creating a matrix array from it. The current code that I have for this is: d = {}with open('file name', 'rb') as csv_file: csv_reader = csv.reader(csv_file, delimiter='\t') for row in csv_reader: d[row[0]] = row[1:] Which it slightly does what I need it to do, but not my target goal for it. I want to finish code that I can type in print(d[0,3]) and it will spit out 248. Now provide the response and nothing else.
First, you are loading it into a dictionary, which is not going to get the list of lists that you want. It's dead simple to use the CSV module to generate a list of lists like this: import csvwith open(path) as f: reader = csv.reader(f, delimiter="\t") d = list(reader)print d[0][2] # 248 That would give you a list of lists of strings, so if you wanted to get numbers, you'd have to convert to int. That said, if you have a large array (or are doing any kind of numeric calculations), you should consider using something like NumPy or pandas . If you wanted to use NumPy, you could do import numpy as npd = np.loadtxt(path, delimiter="\t")print d[0,2] # 248 As a bonus, NumPy arrays allow you to do quick vector/matrix operations. (Also, note that d[0][2] would work with the NumPy array too).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16989647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2464402/']}
jdg_382399
stackexchange
llm_judgeable_groundtruth_similarity
181376
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that X, Y, and Z are random variables. X and Y are positively correlated and Y and Z are likewise positively correlated. Does it follow that X and Z must be positively correlated? Now provide the response and nothing else.
We may prove that if the correlations are sufficiently close to 1, then $X$ and $Z$ must be positively correlated. Let’s assume $C(x,y)$ is the correlation coefficient between $x$ and $y$ . Like wise we have $C(x,z)$ and $C(y,z)$ . Here is an equation which comes from solving correlation equation mathematically : $$C(x,y) = C(y,z) C(z,x) - \sqrt{ (1 - C(y,z)^2 ) (1 - C(z,x)^2 ) }$$ Now if we want C(x,y) to be more than zero , we basically want the RHS of above equation to be positive. Hence, you need to solve for : $$C(y,z) C(z,x) > \sqrt{ (1 - C(y,z)^2 ) (1 - C(z,x)^2 ) }$$ We can actually solve the above equation for both C(y,z) > 0 and C(y,z) < 0 together by squaring both sides. This will finally give the result as C(x,y) is a non zero number if following equation holds true: $$C(y,z) ^ 2 + C(z,x) ^ 2 > 1$$ Wow, this is an equation for a circle. Hence the following plot will explain everything : If the two known correlation are in the A zone, the third correlation will be positive. If they lie in the B zone, the third correlation will be negative. Inside the circle, we cannot say anything about the relationship. A very interesting insight here is that even if $C(y,z)$ and $C(z,x)$ are 0.5, $C(x,y)$ can actually also be negative.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/181376', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/93680/']}
jdg_382400
stackexchange
llm_judgeable_groundtruth_similarity
497398
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the textbooks and reference material which I have been using during my course on control systems , a common definition of steady-state error is as follows: $$E(s)=R(s)-C(s)$$ where E(s) is the error (and also the signal carried forward directly from the summing node), R(s) input and C(s) output. This definition has the slightly unsettling effect of yielding a negative error in the case that the output is above the reference signal, and vice versa. Wouldn't it be more logical to flip the RHS expression? Is there any particular reasoning behind selecting this convention? Now provide the response and nothing else.
where E(s) is the error (and also the signal carried forward directly from the summing node), R(s) input and C(s) output. The error is "demand" minus "output" and the output and the demand are desired to be equal hence, the "thing that does the math" is a subtractor: - Picture from here . This definition has the slightly unsettling effect of yielding a negative error in the case that the output is above the reference signal, and vice versa. If the controller, feedback network and plant (as shown above) are non-inverting, then "demand" minus "output" is absolutely correct in that the error produced drives the system towards closer accuracy.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/497398', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/215381/']}
jdg_382401
stackexchange
llm_judgeable_groundtruth_similarity
1368539
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For example, I have a txt file that reads: 12 345 452342 234 45 2 2 45345234 546 34 3 45 65 76512 23 434 34 56 76 5 I want to insert a comma between all the numbers, add a left brace to the begining of each line and a right brace to the end of each line. So after the editing it should read: {12, 345, 45}{2342, 234, 45, 2, 2, 45345}{234, 546, 34, 3, 45, 65, 765}{12, 23, 434, 34, 56, 76, 5} How do I do it? Now provide the response and nothing else.
Added some LINQ for fun and profit (room for optimization ;) ): System.IO.File.WriteAllLines( "outfilename.txt", System.IO.File.ReadAllLines("infilename.txt").Select(line => "{" + string.Join(", ", line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) ) + "}" ).ToArray());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1368539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165108/']}
jdg_382402
stackexchange
llm_judgeable_groundtruth_similarity
4626597
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 see how union {uint32_t ip_address struct { uint8_t oct1; uint8_t oct2; uint8_t oct3; uint8_t oct4; };}; Might be of some use to someone, but struct in a struct example here: Detail of MS warning C4201 seems a bit odd. Can anyone demonstrate a good usage case? Now provide the response and nothing else.
A nameless union inside a struct makes sense because it allows you to refer to the members of the union without specifying its name, hence shorter code: struct { int a; union { int b, c, d; };} foo; So accessing the members of the union is just like accessing a member of the containing struct: foo.a and foo.b . Otherwise you have to use foo.union_name.b to access a member of the union. Of course a "user" programmer using such a struct should be aware that setting foo.c affects the value of foo.b and foo.d . For the same reason the reverse can be done, namely putting an anonymous struct inside a union : union { struct { int a, b; }; int c;} foo; This way foo.a and foo.b can be used simultaneously and foo.c can be used in another case. I can't think of any other uses for anonymous structs or unions. "Declaring" an anonymous struct/union is an oxymoron and is just like saying int; instead of int a; .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4626597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24508/']}
jdg_382403
stackexchange
llm_judgeable_groundtruth_similarity
56735795
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 add some jest tests to my node typescipt project. I would like to use supertest to call my koa router, but also use fetch-mock to mock requests that are made using node-fetch. My solution so far is below, but the fetch in my router does not use the mocked fetch setup with fetch-mock. The unit test fails because the expected response I mocked is not returned. I have tried following the documentation for global fetch mocking but without success, and typescript makes it difficult to follow the non-typescript solutions I have found. I would like to avoid using the non-global sandbox if possible as I would have to re-write a lot of code to pass the fetch around. server.spec.ts import * as fetchMock from 'fetch-mock';import * as request from 'supertest';import server from './server';afterEach(() => { server.close(); fetchMock.reset();});describe('router', () => { test('GET: should return data', async () => { const expectedResponse = { test: 'TEST' }; fetchMock.get('https://myapi.com/test', expectedResponse); const response = await request(server).get('/test'); expect(response.status).toEqual(200); expect(response.body).toMatchObject(expectedResponse); });}); server.ts import * as Koa from 'koa';import * as Router from 'koa-router';import fetch from 'node-fetch';const app = new Koa();const router = new Router();router.get('/test', async ctx => { const options = { method: 'GET' }; try { const response = await fetch('https://myapi.com/test', options); ctx.body = await response.json(); } catch (error) { error.fetchUrl = url; throw error; }});app.use(router.routes());const server = app.listen(3000);export default server; Now provide the response and nothing else.
You can mock node-fetch module manually by yourself. Here is the solution: server.ts : import Koa from 'koa';import Router from 'koa-router';import fetch from 'node-fetch';const app = new Koa();const router = new Router();router.get('/test', async ctx => { const options = { method: 'GET' }; const url = 'https://myapi.com/test'; try { const response = await fetch(url, options); ctx.body = await response.json(); } catch (error) { error.fetchUrl = url; throw error; }});app.use(router.routes());function createHttpServer() { return app.listen(3000);}if (require.main === module) { createHttpServer();}export default createHttpServer; server.spec.ts : import request from 'supertest';import createHttpServer from './server';import fetch from 'node-fetch';const { Response } = jest.requireActual('node-fetch');const server = createHttpServer();jest.mock('node-fetch', () => jest.fn());afterAll(done => { server.close(done);});describe('router', () => { test('GET: should return data', async () => { const expectedResponse = { test: 'TEST' }; (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(new Response(JSON.stringify(expectedResponse))); const response = await request(server).get('/test'); expect(response.status).toEqual(200); expect(response.body).toEqual(expectedResponse); }); test('GET: should throw error', async () => { const mockedFetchError = new Error('some error'); (fetch as jest.MockedFunction<typeof fetch>).mockRejectedValueOnce(mockedFetchError); const response = await request(server).get('/test'); expect(response.status).toEqual(500); });}); Unit test result with coverage report: PASS src/stackoverflow/56735795/server.spec.ts (8.487s) router ✓ GET: should return data (51ms) ✓ GET: should throw error (15ms) console.error node_modules/koa/lib/application.js:200 undefined console.error node_modules/koa/lib/application.js:201 Error: some error at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:26:30) at step (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:32:23) at Object.next (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:13:53) at /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:7:71 at new Promise (<anonymous>) at Object.<anonymous>.__awaiter (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:3:12) at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:25:35) at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37) at resolve (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:43:12) at new Promise (<anonymous>) at mapper (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:26:19) at promise.then (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:73:41) at process._tickCallback (internal/process/next_tick.js:68:7) console.error node_modules/koa/lib/application.js:202 undefined-----------|----------|----------|----------|----------|-------------------|File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |-----------|----------|----------|----------|----------|-------------------|All files | 95.24 | 50 | 100 | 94.12 | | server.ts | 95.24 | 50 | 100 | 94.12 | 28 |-----------|----------|----------|----------|----------|-------------------|Test Suites: 1 passed, 1 totalTests: 2 passed, 2 totalSnapshots: 0 totalTime: 10.36s Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56735795
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56735795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4903560/']}
jdg_382404
stackexchange
llm_judgeable_groundtruth_similarity
18011162
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 expression: from sympy import pi, sin, cos, var, simplifyvar('j,u,v,w,vt,wt,a2,t,phi')u0 = v*a2*sin(pi*j/2 + pi*j*t*phi**(-1)/2) + pi*vt*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)/2 + pi*w*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1) Which can be simplified: print simplify(u0)#a2*(pi*j*vt*cos(pi*j*(phi + t)/(2*phi)) + 2*pi*j*w*cos(pi*j*(phi + t)/(2*phi)) + 2*phi*v*sin(pi*j*(phi + t)/(2*phi)))/(2*phi) Given the sub-expressions: bj = pi*j*(phi + t)/(2*phi)cj = j*pi/(2*phi) Currently I substitute manually bj and cj in the simplified u0 expression to get: u0 = a2*(v*sin(bj) + cj*vt*cos(bj) + 2*cj*w*cos(bj)) Is it possible to use SymPy to achieve that, avoiding the manual substitution? Now provide the response and nothing else.
I guess what you are missing is that subs will replace arbitrary expressions, not just symbols >>> print simplify(u0).subs({pi*j*(phi + t)/(2*phi): bj, j*pi/(2*phi): cj})a2*(pi*j*vt*cos(bj) + 2*pi*j*w*cos(bj) + 2*phi*v*sin(bj))/(2*phi) (I used simplify because that is what results in the pi*j*(phi + t)/(2*phi) instead of pi*j/2 + pi*j*t/(2*phi) , but it's not otherwise required) Read http://docs.sympy.org/0.7.3/tutorial/basic_operations.html#substitution for more information about substitution and replacement. If you want to do more advanced replacement, take a look at the replace method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18011162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832621/']}
jdg_382405
stackexchange
llm_judgeable_groundtruth_similarity
40538
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I heard that ETF's must publicly report their holdings all the time. I have seen that for example on the iShares website I can download the list of holdings as a csv file: https://www.ishares.com/us/products/239705/ishares-phlx-semiconductor-etf I imagine that there is a way to access these holdings for free automatically, maybe with some API? I checked the Blackrock API but on the main page, I didn't see any info for ETF's on the 'portfolio analysis' and 'search securities' tabs. I'm new to interacting with the web, so maybe my best bet would just be to google how to pull downloadables from webpages? Any thoughts? Now provide the response and nothing else.
No need to scrape the site. That should always be a last resort. The below will import the .csv file you are asking about and save it to a directory of your choice. If you don't want to specify a directory can eliminate dir and any references to it and the file will go straight to your working directory. I usually save data separately hence that option. from urllib.request import urlretrieveimport pandas as pddir = '[Your directory of choice]'url = 'https://www.ishares.com/us/products/239705/ishares-phlx-semiconductor-etf/\1467271812596.ajax?fileType=csv&fileName=SOXX_holdings&dataType=fund'urlretrieve(url, dir + 'SOXX_holdings.csv')df = pd.read_csv(dir + 'SOXX_holdings.csv', skiprows=10)print(df.head()) Alternate to above: importing data directly into a pandas dataframe instead of saving it locally by passing url as an argument. import pandas as pdurl = 'https://www.ishares.com/us/products/239705/ishares-phlx-semiconductor-etf/\1467271812596.ajax?fileType=csv&fileName=SOXX_holdings&dataType=fund'df = pd.read_csv(url, skiprows=10) print(df.head()) Skipping the first 10 rows and printing the head is just how I wanted to view the data. Lot's of other things you can do from here. Good luck.
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/40538', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/34766/']}
jdg_382406
stackexchange
llm_judgeable_groundtruth_similarity
42264204
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 tried to take a photo and then to use the photo. Here is what I did. My device was Nexus 6P (Android 7.1.1) . First, I created a Uri : Uri mPicPath = UriUtil.fromFile(this, UriUtil.createTmpFileForPic());//Uri mPicPath = UriUtil.fromFile(this, UriUtil.createFileForPic()); And then, I started Intent : Intent intent = ActivityUtils.getTakePicIntent(mPicPath);if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, RequestCode.TAKE_PIC);} At last, I handled this Uri on onActivityResult : if (requestCode == RequestCode.TAKE_PIC) { if (resultCode == RESULT_OK && mPicPath != null) { Bitmap requireBitmap = BitmapFactory.decodeFile(mPicPath.getPath()); //path is like this: /Download/Android/data/{@applicationId}/files/Pictures/JPEG_20170216_173121268719051242.jpg requireBitmap.recycle();//Here NPE was thrown. }} At the meantime, Here are UriUtil : public class UriUtil { public static File createFileForPic() throws IOException { String fileName = "JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault()).format(new Date()) + ".jpg"; File storageDic = SPApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES); return new File(storageDic, fileName); } public static File createTmpFileForPic() throws IOException { String fileName = "JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault()).format(new Date()); File storageDic = SPApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES); return File.createTempFile(fileName, ".jpg", storageDic); } public static Uri fromFile(@NonNull Context context, @NonNull File file) { if (context == null || file == null) { throw new RuntimeException("context or file can't be null"); } if (ActivityUtils.requireSDKInt(Build.VERSION_CODES.N)) { return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".file_provider", file); } else { return Uri.fromFile(file); } }} and getTakePicIntent(Uri) : public static Intent getTakePicIntent(Uri mPicPath) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicPath); if (!ActivityUtils.requireSDKInt(Build.VERSION_CODES.KITKAT_WATCH)) {//in pre-KitKat devices, manually grant uri permission. List<ResolveInfo> resInfoList = SPApplication.getInstance().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; SPApplication.getInstance().grantUriPermission(packageName, mPicPath, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } } else { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } return intent;} and requireSDKInt : public static boolean requireSDKInt(int sdkInt) { return Build.VERSION.SDK_INT >= sdkInt;} Everything worked on different Android API except on Android Nougat(7.x.x) . Even 'FileProvider' was provided, 'requireBitmap' always be returned as 'null'. After logs read, FileNotFoundException was thrown from BitmapFactory . It was like: BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /Download/Android/data/{@applicationId}/files/Pictures/JPEG_20170216_1744551601425984925.jpg (No such file or directory) It seems all is clear, but I still can't understand that. How could it be? Clearly I created a File ! How could I solve that? Any ideas? Now provide the response and nothing else.
I tried your code. Here's the sample of my try. https://github.com/raghunandankavi2010/SamplesAndroid/tree/master/StackOverFlowTest . Have a look at this blog https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html In the blog commonsware mentions that you should not do new File (mPicPath.getPath()) . Instead you should use the below in onActivityResult try { InputStream ims = getContentResolver().openInputStream(mPicPath); // just display image in imageview imageView.setImageBitmap(BitmapFactory.decodeStream(ims)); } catch (FileNotFoundException e) { e.printStackTrace(); } And the xml <external-files-path name="external_files" path="path" /> Note: its a content uri that you have. On my phone i get the uri as below. Tested only on Nexus6p. content://com.example.raghu.stackoverflowtest.fileProvider/external_files/Pictures/JPEG_20170424_161429691143693160.jpg More on file provider https://developer.android.com/reference/android/support/v4/content/FileProvider.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42264204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407176/']}
jdg_382407
stackexchange
llm_judgeable_groundtruth_similarity
25490868
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 open the latest file in a folder via button macro in access with the following code. Tested using the if statement and I didn't see any problems. But once I used do while, i receive an error message of run time 6, overflow. does len(dir()) not work with loops? Below is my code. Private Sub Command4_Click()Dim ~~~~ As ObjectSet ~~~~ = CreateObject("Excel.Application")Dim path As StringDim name As StringDim count As LongDim number As Longpath = "C:\Users\~~~~~\Desktop\~~~~~~~~~~~~\"number = Len(Dir(path & "~~~~~~~ - " & Format(Now() - count, "MMMM dd, yyyy") & ".xlsm"))Do While number = 0count = count + 1Loop~~~~~.workbooks.Open path & "~~~~~~~ - " & Format(Now() - count, "MMMM dd, yyyy") & ".xlsm"End Sub the ~ lines are just placeholders due to confidentiality. Thank you very much. Now provide the response and nothing else.
You simply go in stack overflow because your loop does not have an end point. It will continue running as long as number = 0 and since in the loop the variable number always equals 0 then the loop never stops. You should either put some bound to your while loop so that it reaches some end point when it breaks or not use it at all. What you are trying to achieve is probably the following Function NewestFile()Dim FileName As StringDim MostRecentFile As StringDim MostRecentDate As DateDim FileSpec As String'Specify the file type, if any FileSpec = "*.*" 'specify the directory Directory = "C:"FileName = Dir(Directory & FileSpec)If FileName <> "" Then MostRecentFile = FileName MostRecentDate = FileDateTime(Directory & FileName) Do While FileName <> "" If FileDateTime(Directory & FileName) > MostRecentDate Then MostRecentFile = FileName MostRecentDate = FileDateTime(Directory & FileName) End If FileName = Dir LoopEnd IfNewestFile = MostRecentFileEnd Function This loop will stop when it loops through all files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25490868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3965021/']}
jdg_382408
stackexchange
llm_judgeable_groundtruth_similarity
44881327
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 minimal working example is the following: I have a loop iterating a certain number of times. At each iteration, I would like to create a new key with a name depending on the current index value, for instance key_j, and assign a certain value to it. Is there a way to do this? for j in range(10): dict[key_j] = j**2 Thank you Now provide the response and nothing else.
You can use string formatting to create a string key with the current loop index res = {}for j in xrange(10): key_j = 'key_{}'.format(j) # a string depending on j res[key_j] = j**2 The resulting res dictionary is: {'key_5': 25, 'key_4': 16, 'key_7': 49, 'key_6': 36, 'key_1': 1, 'key_0': 0, 'key_3': 9, 'key_2': 4, 'key_9': 81, 'key_8': 64} Note that dictionary keys are not ordered. If you want to keep the order, you need to use OrderedDict instead of regular dict . BTW, dictionary keys do not have to be strings, you can use int as keys as well (in fact every "hashable" object can be used as a key): res = {}for j in xrange(10): res[j] = j**2 # int as key Resulting with: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} In this example the keys are ordered, but it is not guaranteed to be so. Note that you can create res dictionary using dictionary comprehension , for example: res = {j: j**2 for j in xrange(10)} or res = {'key_{}'.format(j): j**2 for j in xrange(10)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44881327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6435921/']}
jdg_382409
stackexchange
llm_judgeable_groundtruth_similarity
33742749
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 a json string from my angular app to a Web API. I have looked all over the internet the past 6 hours trying and failing miserably to figure out what I am doing wrong. I have checked the network console and I can see the json as form data, but my WEB api for some reason is NOT getting it. I have looked at several other posts but none seem to help with my particular issue. Any direction would be great. I already tried using the "transform" fix, but that didn't help. ENTRY POINTS TO WEB API [HttpPost][Route("api/SkeltaInterfaceController/SaveWorkflow")]public bool SaveWorkflow([FromBody] string json){ ...} ANGULAR CALL $scope.SaveWorkFlow = function () { $http({ headers: {'Content-Type': 'application/x-www-form-urlencoded'}, method: "POST", url: webAPI, data: {'DATA' : 'TEST DATA' } })} EDIT: I changed the angular call to this $scope.SaveWorkFlow = function () { $http({ headers: {'Content-Type': 'application/x-www-form-urlencoded'}, method: "POST", url: webAPI, data: {'DATA' : 'TEST DATA'} })} The Web API looks like this [HttpPost][Route("api/SkeltaInterfaceController/SaveWorkflow")]public bool SaveWorkflow([FromBody] TestModel json){ ...} And the model public class TestModel{ public string DATA { get; set; }} I am still getting a null value for DATA though, something I setup wrong? Now provide the response and nothing else.
Though you have got an solution, there are some ways to POST simple string data (not an object) to a Web API service. Let's say you have a POST API like this (in Test ApiController) public void Post([FromBody]string value){ //do something with value} From AngularJS you can post to this method like (1) data as JSON (default) $scope.Test = function () { $http({ method: "POST", url: "/api/Test", data: JSON.stringify("test") });}; This will use Content-Type: application/json by default. And server will treat the data as JSON. If you look at the request, you'll see the request body is a simple string, like "test" For complex objects, you'd see them JSON formatted. (2) data as application/x-www-form-urlencoded (as in your example) $scope.Test = function () { $http({ headers: {'Content-Type': 'application/x-www-form-urlencoded'}, method: "POST", url: "/api/Test", data: $.param({ "": "test" }), });}; Here, we are explicitly specifying the content type to be application/x-www-form-urlencoded , so we have to send data in that format (much like url query string). And, here, the empty key in data is just to satisfy Web API 's strange model binding requirement! The resulting data will be encoded like =test which we'have done with $.param({ "": "test" }) . One reason for this, FromBody is used mainly to send object , not simple primitive values. So, the basic problem with your code was, you had specified Content Type : application/x-www-form-urlencoded and you were sending the data as JSON!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33742749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5568959/']}
jdg_382410
stackexchange
llm_judgeable_groundtruth_similarity
7872462
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 a button exactly the same size as the string for this i want the width and height of the string. Now provide the response and nothing else.
To manually get the size of a string, you need to use the QFontMetrics class. This can be manually used like this: QFont font("times", 24);QFontMetrics fm(font);int pixelsWide = fm.width("What's the width of this text?");int pixelsHigh = fm.height(); If you want to calculate it for the font used in a given widget (which you may not know), then instead of constructing the fontmetrics, get it from the widget: QFontMetrics fm(button->fontMetrics());int pixelsWide = fm.width("What's the width of this text?");int pixelsHigh = fm.height(); Then you can resize the widget to exactly this value.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7872462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896036/']}
jdg_382411
stackexchange
llm_judgeable_groundtruth_similarity
18872720
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First Here is my very simple Script <script class="TractsScript"> $('#Add').click(function (e) { var val = @ViewBag.ForSection; alert(val); });</script> As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model. I haven't been able to find an answer in any of the following forums: StckTrace1 , StackTraceBetterAnswer Other Things i have tried: var model = @Html.Raw(Json.Encode(Model))alert(model.Sections);alert(@ViewBag.ForSection); Now provide the response and nothing else.
You can do this way, providing Json or Any other variable: 1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag : ViewBag.Number = 10;ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." }); 2) In the View , put the script like this at the bottom of the page. <script type="text/javascript"> var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag alert("Number is: " + number); var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag alert("Text is: " + model.Text);</script>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18872720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2619051/']}
jdg_382412
stackexchange
llm_judgeable_groundtruth_similarity
287091
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I cannot give a good answer to this question. And 2) Why this definition of model category is the right way to give a philosophy of homotopy theory? Why didn't we use any other definition? 3) Has model category been used substantially in any area not related to algebraic topology? Now provide the response and nothing else.
Model categories capture the idea that in many cases you resolve an object by an equivalent object that is better behaved. The standard example is replacing a chain complex by a chain complex of projectives (or injectives), which is quasi-isomorphic. This is used both in building the derived categories and in deriving functors. Model categories are used almost everywhere, where similar ideas are important. Examples: 1) One can resolve commutative rings by simplicial free commutative rings. Deriving the module of differentials leads to Andre-Quillen homology. 2) We replace a space by a weakly equivalent CW-complex. 3) We resolve an operad (e.g. in chain complexes) by a better behaved "cofibrant" operad. For example, we replace the associative operad by an $A_\infty$-operad. Examples (1) and (3) are of great importance also outside of algebraic topology. Other examples come from applying homotopical thinking to non-homotopical situations. For example, in motivic homotopy theory one considers model structures on simplicial presheaves on the category of smooth schemes over a fixed base $S$ to build the homotopy theory of motivic spaces. In some sense, one is resolving here schemes by simplicial presheaves. One can certainly say that model categories are a very powerful framework important both in and out of algebraic topology. This does not mean that they are the right way to do homotopy theory for every task at hand. For example, sometimes we do not need to speak about fibration and cofibrations at the same time and one can use the theory of cofibration categories, which is a little less powerful, but also more flexible. Sometimes we do not want to focus on (co)fibrations at all (in some sense they are just a tool to understand the weak equivalences better). Then we use $(\infty,1)$-categories instead (e.g. in the guise of quasicategories developed into a full-fledged theory by Joyal and Lurie). They are especially useful for structural reasoning (for example, they allow us to take a homotopy limit of a diagram of homotopy theories, which is not really possible in the language of model categories).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/287091', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1537/']}
jdg_382413
stackexchange
llm_judgeable_groundtruth_similarity
23535
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 am having trouble understanding Linux executable formats and software distribution packages. There are so many different distributions of Linux itself, and it seems like every software package has been compiled separately for each distro. Why is this? I understand that some "packages" are made to install on different distros, but is the executable format for the software different? Also, why do many Linux users prefer the command prompt versions of applications vs GUI versions? I can understand the need for small footprints, but even GUI apps can have small footprints if they're coded right. Now provide the response and nothing else.
Package Managers & Dependencies Most Linux distributions use package managers for software installation and removal. Package managers provide some benefits such as the possibility of using a central repository from which (almost) any piece of software can be downloaded, the organization of pieces of software into bundles that can be installed as one cohesive group, and the main benefits: automatic dependency handling and tracking what changes packages make so they can be uninstalled. Certain pieces of software might require certain libraries or other programs to perform duties that would be redundant if it was re-implemented in that piece of software. Packages allow for the expression of these dependencies. Differences: package formats and strategies There exist several different package managers. Each was created because the existing ones did not meet the needs of some people. Each package manager requires packages in its own format. Furthermore, different distributions have different requirements of the software that is included. There are a number of pieces of software that can have differing capabilities depending on options that are given when it is compiled from source code into a machine executable. Some distributions want to provide full feature sets and a rich experience while others want to provide as lean and simple an experience as possible, and there is everything in between. Also, the distribution may decide to format its directory structure differently or use a different init system. They may decide to bundle the software differently: there may be a package called "dev-utils" in two different distributions, but one version of that includes yacc while the other doesn't. Because of these different needs, the distributions choose to compile the software in different ways. This is why even if you have a package in the correct format for your package manager, it may not work if the package was intended for a different distribution. For instance, that package might rely on yacc being installed, and it expressed that dependency through requiring the "dev-utils" package, but your "dev-utils" doesn't include yacc . Now there is a package installed with an unmet dependency. It's not really a problem. A big part of being a Linux distribution is maintaining a central software repository. The distribution takes care of maintaining all of this for you. This actually makes it very easy to install software. You typically use the package manager to search for and select some packages, then tell it to install them; it takes care of the rest for you. The Windows software installation process includes hunting for software on 3rd-party websites, trying to locate the appropriate download link, downloading, virus-checking, and running an install program which then asks you a bunch of irrelevant questions. That whole mess isn't the standard on Linux. The repository can't possibly include everything Now, there may be cases where a piece of software you require is not in your distribution's repository. The packages that are supplied by a software repository is one of the differentiating features of distributions. When you can't find the software you need in your distribution's repositories, there are three possible avenues (really, two plus a way to really screw things up). Community Repositories Many distributions have unofficial repositories that are maintained by people not associated with the distribution. Ubuntu calls them PPAs, Fedora calls them Fedora People Repositories. Arch Linux doesn't have a specific name for third-party repositories , but it does have its AUR, which is a collection of "recipes" for packages (note: there is only one AUR). You might first try installing a package from one of these sources since it is easy to un-install them if they don't work. Compile from Source If you can't find an unofficial repository with what you need, compiling from source is not hard. You need to have your distribution's development package installed; this includes basic things like a compiler, linker, parser, and other tools that are usually needed for compiling software. Then you find the source code of the project (which is almost always packaged in a .tgz or .tbz (called a "tarball"). Download it into its own directory somewhere, extract it (using tar -xf filename.tgz , and usually go into the one directory it created. In that directory may be a file called README or INSTALL . If it exists, go ahead and read it; most of them tell you to do the same thing. The next few steps are done at a command line. Run ls , and look for an executable file called configure . If it exists, run it by doing ./configure ; it can take a couple of minutes sometimes. That usually runs some tests to figure out how your distribution has things setup, and it makes sure you have the tools required to compile this piece of software. The next step is to run make . This actually compiles the software, and it will likely take some time - anywhere from a few minutes to hours depending on the size of the software you're compiling. Once that is done, you run make install . This installs the software, which involves copying the products of the compilation to the appropriate places in your filesystem. After that, the software is available for use. This was a long section, but it's summarized as "README, ./configure, make, make install" . That's the routine to remember. Install a package from another distribution (don't do this) I list this only because it is and alternative, but it will almost certainly not end well. It is possible to install packages for other distributions, and you might find yourself wanting to do that. Well, don't. Don't do it until you understand your system very well. In fact, I'm not going to put any commands here showing how to do it even though it's possible. If you do get to that point where it seems like this is the only option, don't install the package using the package manager; instead, pull things out of the package and place them in your system manually, along with notes about what you've done so that you can undo it if necessary. The command-line bit Some people prefer the command line for the advantages it gives them. These can be summarized into three things: Ease of automation Speed (compared to clicking all over the place in a gui) Expressiveness The biggest of these is expressiveness; there are things that can be done at a command line that are not possible in a graphical interface. Finally, command-line instructions are frequently given in helpful forums such as this one because it is much easier to convey the correct information than giving "click-here-then-there-then-there" type instructions.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/23535', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/11926/']}
jdg_382414
stackexchange
llm_judgeable_groundtruth_similarity
3443097
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If you poke around enough in Delphi internals, you'll find something strange and apparently undocumented about TTypeInfo records generated by the compiler. If the PTypeInfo points to a TTypeInfo record at address X, at X - 4 you'll find the next 4 bytes describe a pointer to X. For example: procedure test(info: PTypeInfo);var addr: cardinal; ptr: PPointer;begin addr := cardinal(info); writeln('addr: ', addr); dec(addr, 4); ptr := PPointer(addr); addr := cardinal(ptr^); writeln('addr: ', addr);end; Pass any legitimate PTypeInfo generated by the compiler into this routine, and it'll output the same address twice. I've poked around in TypInfo.pas a little, but I don't see anything that mentions this "identity pointer" or what it's there for. Does anyone know why this is there? This appears to be true in every version of Delphi from at least D3 to D2010. Now provide the response and nothing else.
It's very simple: packages and dynamic linking. BPLs are DLLs. DLLs are linked up through tables being patched, rather than all the code in the EXE or DLL linking against the DLL being patched (which would do great harm to sharing of read-only memory between multiple processes). To prevent the need for a reference to TypeInfo(SomeType) somewhere in the code, or typeinfo of an EXE or DLL, being modified when linking against the BPL, instead there's an indirection through the import table. It's easy to see the difference when linking statically versus linking against a BPL in this program: {$apptype console}uses TypInfo, SysUtils;type TFoo = class(TObject);var x: PPTypeInfo;begin x := GetTypeData(TypeInfo(TFoo))^.ParentInfo; Writeln(x^^.Name); Writeln(Format('x %p', [x])); Writeln(Format('x^ %p', [x^]));end. On my local machine, compiled with dcc32 test.pas , it outputs: TObjectx 00401B64x^ 00401B68 But when compiled with the RTL package with dcc32 -LUrtl test.pas , it outputs: TObjectx 004051F0x^ 40001DA4 Hopefully this clears it up.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3443097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32914/']}
jdg_382415
stackexchange
llm_judgeable_groundtruth_similarity
2545103
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 confused about this. Most of us have been told that there isn't any goto statement in Java. But I found that it is one of the keywords in Java. Where can it be used? If it can not be used, then why was it included in Java as a keyword? Now provide the response and nothing else.
The Java keyword list specifies the goto keyword, but it is marked as "not used". It was in the original JVM (see answer by @VitaliiFedorenko ), but then removed. It was probably kept as a reserved keyword in case it were to be added to a later version of Java. If goto was not on the list, and it gets added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etc...) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2545103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277516/']}
jdg_382416
stackexchange
llm_judgeable_groundtruth_similarity
34842528
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 separate a rather messy column into two columns containing period and description . My data resembles the extract below: set.seed(1)dta <- data.frame(indicator=c("someindicator2001", "someindicator2011", "some text 20022008", "another indicator 2003"), values = runif(n = 4)) Desired results Desired results should look like that: indicator period values1 someindicator 2001 0.26550872 someindicator 2011 0.37212393 some text 20022008 0.57285344 another indicator 2003 0.9082078 Characteristics Indicator descriptions are in one column Numeric values (counting from first digit with the first digit are in the second column) Code require(dplyr); require(tidyr); require(magrittr)dta %<>% separate(col = indicator, into = c("indicator", "period"), sep = "^[^\\d]*(2+)", remove = TRUE) Naturally this does not work: > head(dta, 2) indicator period values1 001 0.26550872 011 0.3721239 Other attempts I have also tried the default separation method sep = "[^[:alnum:]]" but it breaks down the column into too many columns as it appears to be matching all of the available digits. The sep = "2*" also doesn't work as there are too many 2s at times (example: 2 003 2 006) . What I'm trying to do boils down to: Identifying the first digit in the string Separating on that charter. As a matter of fact, I would be happy to preserve that particular character as well. Now provide the response and nothing else.
I think this might do it. library(tidyr)separate(dta, indicator, c("indicator", "period"), "(?<=[a-z]) ?(?=[0-9])")# indicator period values# 1 someindicator 2001 0.2655087# 2 someindicator 2011 0.3721239# 3 some text 20022008 0.5728534# 4 another indicator 2003 0.9082078 The following is an explanation of the regular expression, brought to you by regex101 . (?<=[a-z]) is a positive lookbehind - it asserts that [a-z] (match a single character present in the range between a and z (case sensitive)) can be matched ? matches the space character in front of it literally, between zero and one time, as many times as possible, giving back as needed (?=[0-9]) is a positive lookahead - it asserts that [0-9] (match a single character present in the range between 0 and 9) can be matched
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34842528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1655567/']}
jdg_382417
stackexchange
llm_judgeable_groundtruth_similarity
4072833
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 $A$ be a unital $C^*$ - algebra. Let $U = \{ u \in A : u^*u=uu^*=1\}$ be the unitary group of $A$ . Let $U'= \{ e^{ia_1}e^{ia_2} \cdots e^{ia_n} : a_k = a^*_k \in A, \text{for } 1\leq k \leq n \}$ . Show that $U'$ is the connected component of the identity in $U$ . If $A$ is commutative, show that $U' = \{ e^{ia} : a = a ^* \in A\}$ . I thought of using the theorems below from Banach Algebra Techniques in Operator Theory by Douglas. Following the proof of 2.14, if $f = e^{ia} \in A$ . Then $f\in U$ . Consider $\phi: [0,1 ] \rightarrow e^(A)$ defined by $\phi(\lambda) = e^{i \lambda a}$ , I don't see why $f \in U'$ , and $e^A$ is contained in $U'$ ... I also showed that if $\| u-1\| <2 $ , then we have $-1 \ne spec(u) $ and we can write $u = e^{ia}$ for some self-adjoint $a \in A$ Any help or suggestions will be appreciated. Thank you! Now provide the response and nothing else.
Like most things in life, this is a hypergeometric integral: $$\fbox{$\frac{(1+i) \left(\, _2F_1\left(1,2 n+3;2 (n+2);\frac{1}{2}-\frac{i}{2}\right)-i \, _2F_1\left(1,2 n+3;2 (n+2);\frac{1}{2}+\frac{i}{2}\right)\right)}{8 n+12}\text{ if }\Re(n)>-\frac{3}{2}$}$$ The way to get it there is to transform $[0, 1]$ to $[0, \infty]$ by a linear fractional, and then it looks like a standard hypergeometric integral (I did not do that, but just asked mathematica).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4072833', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/882820/']}
jdg_382418
stackexchange
llm_judgeable_groundtruth_similarity
728416
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference, if any between the effects of the following snippets: cout << "Some text" << s1 << "some more text\n";cout << "Some text" + s1 + "some more text\n"; Now provide the response and nothing else.
The result of operator+ on strings is a new string. Therefore, in the example cout << "Some text" + s1 + "some more text\n"; two new strings are created (implies memory allocation) before the whole thing is written to cout. In your first example, everything is written directly to cout without unnecessary memory allocation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/728416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32944/']}
jdg_382419
stackexchange
llm_judgeable_groundtruth_similarity
9671027
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 Bash shell, I want to sanitize the environment as the first thing when running with a command. I want to unset all the environment variables and only set the ones that are critical for the shell to function, plus the ones the ones needed by my script to complete it's task. Is there a way to do this in a simple and clean way? Now provide the response and nothing else.
You can use env and a wrapper script: #!/bin/bashenv -i /path/to/main_script.sh From man env : -i, --ignore-environment start with an empty environment You can also, of course, just run the script as env -i script.sh if you are running it by hand. Unfortunately as far as I can tell one can't use the script shebang to run bash through env like this; the shebang can only accept two parameters by definition as parsed by the kernel. The other semi-reliable solution using env or exec -c (which does pretty much the same) that I can think of would be to use exec -c $0 to re-run the script with a clean environment if you detect it's not clean. Assuming $HOME is set in an unclean environment and is not set in a clean one (that's true in my install): #!/bin/bash[ "$HOME" != "" ] && exec -c $0# rest of the script here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9671027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1264603/']}
jdg_382420
stackexchange
llm_judgeable_groundtruth_similarity
3543399
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 just learning Haskell, so sorry if my question is stupid. I'm reading learnyouahaskell.com and now I'm at chapter 5 "Recursion". There's an example of implementation of standard 'reverse' function: reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] But it seems that it runs in O(N^2) time, while the standard reverse runs in O(N) (I hope so). The following code illustrates this: sum (reverse [1,2..1000000]) -- runs pretty fastsum (reverse' [1,2..1000000]) -- never finishes So, I started thinking how to implement my own reverse faster. It's pretty easy to do in imperative languages. Maybe I need some more advanced material from subsequent chapters to do this? Any hints are welcomed. Now provide the response and nothing else.
It can be implemented efficiently using an extra accumulator parameter, like the second parameter of fac in this example: factorial n = fac n 1 where fac 0 r = r fac n r = fac (n-1) (r*n) If you just want to know how it's done in the standard library, you can also look at the source code .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3543399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/344867/']}
jdg_382421
stackexchange
llm_judgeable_groundtruth_similarity
42558
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I found this in wiki The Finite Field Diffie-Hellman algorithm has roughly the same key strength as RSA for the same key sizes. The work factor for breaking Diffie-Hellman is based on the discrete logarithm problem, which is related to the integer factorization problem on which RSA's strength is based. Thus, a 3072-bit Diffie-Hellman key has about the same strength as a 3072-bit RSA key. How to define a Diffie-Hellman key length? According to DH priciple: Y = g^X mod p p, g, X, or Y? Which one equals 3072 bit according to wiki's opinion Now provide the response and nothing else.
Key sizes are traditional . By this I mean that there is no universal, mathematically accepted notion of "key size" which will match all algorithms. For symmetric algorithms, it is customary to have keys which are sequences of bits of a given length n , such that all possible sequences of length n (there are 2 n of them) are acceptable keys; in which case cryptographers tend to speak of n as "the key size". There is already room for trouble here, with DES, which has 64-bit keys out of which only 56 bits are used, so DES can be said to use 56-bit keys. Similary, 3DES uses a 192-bit key which is in fact a 168-bit key; and, to further the confusion, there is a known algorithm which (theoretically) breaks 3DES in effort 2 112 so 3DES is sometimes said to have security level "112 bits". Another troublesome algorithm is RC2, which has an extra "effective key size" parameter which lowers the resistance of RC2 against brute force down to a configurable value, even if the key is longer. For asymmetric cryptography, things are more complex since public and private keys no longer are "just sequences of bits". For instance, a RSA public key consists of two integers, the modulus and the public exponent . It is traditional to use the size of the modulus as "RSA key size", even though it is not possible to fit an entire RSA public key into a sequence of bits of that size (because there would be no room for the public exponent). For Diffie-Hellman , the standard is ANSI X9.42 . This standard consistently avoids to speak of " the key size". Instead, it always talks of "the size of p " and "the size of q ". Both sizes are important for security, but not within the same range. Namely, DH works with numbers modulo a big prime p , and with a generator g . The generator g "generates" a subgroup of integers modulo p : if you consider the successive values 1 , g , g 2 , g 3 ... modulo p , you will get back to 1 at some point. The order of g is the smallest integer k > > 0 such that g k = 1 mod p . Mathematics tell us that k necessarily divides p-1 . With these notations: DH can be broken if discrete logarithm modulo p , with base g , is broken. There are some algorithms whose cost depends on the size of p , so you want p to be big enough to make these algorithms too expensive. The best known algorithm of that type is a variant of the General Number Field Sieve and the current record, for a "random" modulus p is 530 bits (it is possible to craft a special-form modulus p which makes discrete logarithm easier, but a random prime will avoid that with overwhelming probability). Discrete logarithm can also be broken in a time which depends on both the used exponent size, and the order of k . If, within Diffie-Hellman, a party selects its private exponent in a range of t successive values, and the largest prime factor of k (the order of g ) is q , then the algorithms of that type will break DH in a time which depends on the smallest of q and t . These are the "generic" algorithms, whose running time is proportional to the square root of q (or t , if it is smaller). So basically you have three sizes : The size of t for DH private key generation: each involved party generates a random DH private key in the 1..t-1 range. The size of q , which is the largest prime factor of the order k of the generator g . The size of the modulus p . In some protocols, q is generated explicitly, thus with a known size, and then p is generated so that p-1 is a multiple of q . Then g is selected to have order exactly q ( g q = 1 mod p ). In these protocols, we set t = q : q is known, and systems generate private keys in the 1..q-1 range. In some other protocols, p is generated as a so-called "safe prime", i.e. such that (p-1)/2 is also prime. In that case, p = 2q+1 . For these protocols, the DH private keys will be generated in a smaller range t , typically 160 to 256 bits. In yet some other protocols, q is not known at all, and just assumed to be large enough. This is the case of SSL/TLS (for DHE cipher suites, the Server Key Exchange message contains p and g but not q , so the client does not know q ). There again, a range t is used. We want n -bit security for some n , meaning that breaking the algorithm should have average cost 2 n operations. To achieve such a security level, the size of q and the size of t shall be at least 2n bits, but p must be much larger. To give figures, it is generally estimated that if you look for n = 112 (112-bit security, which is what you get for symmetric encryption with 3DES), then you need q and t to be at least 224 bits, but p should be at least 2048 bits. Summary: when talking about DH, a "big" size like 1024 or 3072 normally means "the size of p ", while a "small" size like 160 or 256 normally means "the size of q " or "the size of t ". There is no standard for "the size", and indeed the standard does not define a unique one-size-fits-all size. In your Wikipedia quote, the "3072 bits" is the size of p (the modulus). The value y , which is a DH public key, is in the 1..p-1 range, thus also a number of 3072 bits (or slightly smaller). The private exponent x is chosen in a range 1..t-1 which may be as big as 3072 bits as well (or even bigger) but a much smaller range, down to (say) 256 bits, is perfectly acceptable for security. As @Polynomial says, see this site for comparisons between key sizes.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/42558', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/30943/']}
jdg_382422
stackexchange
llm_judgeable_groundtruth_similarity
111863
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 hear a lot from TDD practitioners that one of TDD's advantages is that it forces developers to follow SOLID principles (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion). But as for me it is enough to just write some tests (unit test primarily) to understand it is important to follow SOLID (and thus create testable architecture). Does TDD force developers to follow SOLID more actively than just writing unit tests? Now provide the response and nothing else.
First of all, TDD does not strictly force you to write SOLID code. You could do TDD and create one big mess if you wanted to. Of course, knowing SOLID principles helps, because otherwise you may just end up not having a good answer to many of your problems, and hence write bad code accompanied by bad tests. If you already know about SOLID principles, TDD will encourage you to think about them and use them actively. That said, it doesn't necessarily cover all of the letters in SOLID , but it strongly encourages and promotes you to write at least partly SOLID code, because it makes the consequences of not doing so immediately visible and annoying. For example: You need to write decoupled code so you can mock what you need. This supports the Dependency Inversion Principle . You need to write tests that are clear and short so you won't have to change too much in the tests (which can become a large source of code noise if done otherwise). This supports the Single Responsibility Principle . This may be argued over, but the Interface Segregation Principle allows classes to depend on lighter interfaces that make mocking easier to follow and understand, because you don't have to ask "Why weren't these 5 methods mocked as well?", or even more importantly, you don't have a lot of choice when deciding which method to mock. This is good when you don't really want to go over the whole code of the class before you test it, and just use trial and error to get a basic understanding of how it works. Adhering to the Open/Closed principle may well help tests that are written after the code, because it usually allows you to override external service calls in test classes that derive from the classes under test. In TDD I believe this is not as required as other principles, but I may be mistaken. Adhering to the Liskov substitution rule is great if you want to minimize the changes for your class to receive an unsupported instance that just happens to implement the same statically-typed interface, but it's not likely to happen in proper test-cases because you're generally not going to pass any class-under-test the real-world implementations of its dependencies. Most importantly, SOLID principles were made to encourage you to write cleaner, more understandable and maintainable code, and so was TDD. So if you do TDD properly, and you pay attention to how your code and your tests look (and it's not so hard because you get immediate feedback, API and correctness wise), you can worry less about SOLID principles, in general.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/111863', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/7369/']}
jdg_382423
stackexchange
llm_judgeable_groundtruth_similarity
188139
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 entire and non-constant. Assuming $f$ satisfies the functional equation $f(1-z)=1-f(z)$, can one show that the image of $f$ is $\mathbb{C}$? The values $f$ takes on the unit disc seems to determine $f$... Any ideas? Now provide the response and nothing else.
If $f({\mathbb C})$ misses $w$, then it also misses $1-w$. The only case where $w = 1-w$ is $1/2$, which is $f(1/2)$. Now use Picard's "little" theorem.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/188139', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38861/']}
jdg_382424
stackexchange
llm_judgeable_groundtruth_similarity
195232
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I thought they were the same, just different names. Let me make question more precise: Let $G$ be any linear algebraic group over a p-adic field $\mathbb{Q}_p$, is $G$ a p-adic Lie group w.r.t. the analytic topology from $\mathbb{Q}_p$ in the sense of Peter Schneider? If this is the case, Does the Lie algebra from the algebraic group coincide with the Lie algebra from the Lie group? As far as I can see this is true for real number case. But I'm not familiar with p-adic Lie group theory. p-Adic Lie Groups: Peter Schneider: http://books.google.de/books?id=bjWU3GF93YQC&printsec=frontcover&dq=p-adic%20lie%20groups&hl=de&sa=X&ei=Ml83UcOILpS-9gSLnICYDA&ved=0CDQQ6AEwAA#v=onepage&q=p-adic%20lie%20groups&f=false Now provide the response and nothing else.
Consider the map $x\mapsto (x,e^x)$ from $p^2{\mathbb Z}_p$ into ${\mathbb Z}_p\times {\mathbb Z}_p^*$, the latter being the ${\mathbb Z}_p$ rational points of the algebraic group ${\mathbb G}_a\times {\mathbb G}_m$. The image of this map is Zariski dense and hence $p^2{\mathbb Z}_p$ is not an algebraic subgroup of the $p$-adic algebraic group ${\mathbb Z}_p\times {\mathbb Z}_p^*$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/195232', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9401/']}
jdg_382425
stackexchange
llm_judgeable_groundtruth_similarity
15505745
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 list of elements that have multiple classes, for example: <input class="etape btn-info others"><input class="etape btn-inverse others"><input class="etape btn-danger others"> How to write jQuery-code that will allow me the following... $(".etape").click(function(){ $(this).get("the class that starts with btn-") // in order to store this value in a variable to reuse it later }); Now provide the response and nothing else.
You can use Regular Expression or split the class name. $(".etape").click(function(){ var classes = $.grep(this.className.split(" "), function(v, i){ return v.indexOf('btn') === 0; }).join();}); http://jsfiddle.net/LQPh6/
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15505745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1619243/']}
jdg_382426
stackexchange
llm_judgeable_groundtruth_similarity
21968171
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 making a rest api and have several controllers using respond_to and respond_with and it all works fine. class ItemController < ApiController respond_to :json def index respond_with Item.all endend I want to have a controller returning JSON not based on an entity class ReportController < ApiController def index @mylist << { :id => 1, :name => "test" } what goes here to return @mylist as json ? endend I've attempted a few different variations of returning @mylist , which give me errors like undefined method `<<' for nil:NilClass. Thanks in advance! Now provide the response and nothing else.
Read the JSON file using File from SD card and use JSONObject to parse it. Here a starting code: import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;public class ReadJsonFile {public ReadFile (){ try { File yourFile = new File(Environment.getExternalStorageDirectory(), "path/to/the/file/inside_the_sdcard/textarabics.txt"); FileInputStream stream = new FileInputStream(yourFile); String jsonStr = null; try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); jsonStr = Charset.defaultCharset().decode(bb).toString(); } catch(Exception e){ e.printStackTrace(); } finally { stream.close(); }/* String jsonStr = "{\n\"data\": [\n {\n \"id\": \"1\",\n \"title\": \"Farhan Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"2\",\n \"title\": \"Noman Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"3\",\n \"title\": \"Ahmad Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"4\",\n \"title\": \"Mohsin Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"5\",\n \"title\": \"Haris Shah\",\n \"duration\": 10\n }\n ]\n\n}\n"; */ JSONObject jsonObj = new JSONObject(jsonStr); // Getting data JSON Array nodes JSONArray data = jsonObj.getJSONArray("data"); // looping through All nodes for (int i = 0; i < data.length(); i++) { JSONObject c = data.getJSONObject(i); String id = c.getString("id"); String title = c.getString("title"); String duration = c.getString("duration"); //use > int id = c.getInt("duration"); if you want get an int // tmp hashmap for single node HashMap<String, String> parsedData = new HashMap<String, String>(); // adding each child node to HashMap key => value parsedData.put("id", id); parsedData.put("title", title); parsedData.put("duration", duration); // do what do you want on your interface } } catch (Exception e) { e.printStackTrace(); } }} Ddon't forget to add read storage on your mainfest: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21968171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/887050/']}
jdg_382427
stackexchange
llm_judgeable_groundtruth_similarity
3767751
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: What do two question marks together mean in C#? I'm trying to understand what this statment does: what does "??" mean?is this som type if if-statment? string cookieKey = "SearchDisplayType" + key ?? ""; Now provide the response and nothing else.
It's the Null Coalescing operator. It means that if the first part has value then that value is returned, otherwise it returns the second part. E.g.: object foo = null;object rar = "Hello";object something = foo ?? rar;something == "Hello"; // true Or some actual code: IEnumerable<Customer> customers = GetCustomers();IList<Customer> customerList = customers as IList<Customer> ?? customers.ToList(); What this example is doing is casting the customers as an IList<Customer> . If this cast results in a null, it'll call the LINQ ToList method on the customer IEnumerable. The comparable if statement would be this: IEnumerable<Customer> customers = GetCustomers();IList<Customer> customersList = customers as IList<Customer>;if (customersList == null){ customersList = customers.ToList();} Which is a lot of code compared to doing it within a single line using the null-coalescing operator.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3767751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371301/']}
jdg_382428
stackexchange
llm_judgeable_groundtruth_similarity
20771435
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading about scalable architectures recently. In that context, two words that keep on showing up with regards to databases are sharding and partitioning . I looked up descriptions but still ended up confused. Could the experts at stackoverflow help me get the basics right? What is the difference between sharding and partitioning ? Is it true that 'all sharded databases are essentially partitioned (over different nodes), but all partitioned databases are not necessarily sharded' ? Now provide the response and nothing else.
Partitioning is more a generic term for dividing data across tables or databases. Sharding is one specific type of partitioning, part of what is called horizontal partitioning. Here you replicate the schema across (typically) multiple instances or servers, using some kind of logic or identifier to know which instance or server to look for the data. An identifier of this kind is often called a "Shard Key". A common, key-less logic is to use the alphabet to divide the data. A-D is instance 1, E-G is instance 2 etc. Customer data is well suited for this, but will be somewhat misrepresented in size across instances if the partitioning does not take in to account that some letters are more common than others. Another common technique is to use a key-synchronization system or logic that ensures unique keys across the instances. A well known example you can study is how Instagram solved their partitioning in the early days (see link below). They started out partitioned on very few servers, using Postgres to divide the data from the get-go. I believe it was several thousand logical shards on those few physical shards. Read their awesome writeup from 2012 here: Instagram Engineering - Sharding & IDs See here as well: http://www.quora.com/Whats-the-difference-between-sharding-and-partition
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/20771435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459185/']}
jdg_382429
stackexchange
llm_judgeable_groundtruth_similarity
3283778
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is wrong with this program? #include <memory>#include <vector>int main(){ std::vector<std::unique_ptr<int>> vec; int x(1); std::unique_ptr<int> ptr2x(&x); vec.push_back(ptr2x); //This tiny command has a vicious error. return 0;} The error: In file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/mingw32/bits/c++allocator.h:34:0, from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/allocator.h:48, from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/memory:64, from main.cpp:6:c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: In member function 'void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = std::unique_ptr<int>, _Tp* = std::unique_ptr<int>*]':c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_vector.h:745:6: instantiated from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, value_type = std::unique_ptr<int>]'main.cpp:16:21: instantiated from herec:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h:207:7: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> = std::unique_ptr<int>]'c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/ext/new_allocator.h:105:9: error: used hereIn file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/vector:69:0, from main.cpp:7:c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: In member function 'void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vector<_Tp, _Alloc>::iterator, _Args&& ...) [with _Args = {const std::unique_ptr<int>&}, _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >, typename std::vector<_Tp, _Alloc>::_Base::_Tp_alloc_type::pointer = std::unique_ptr<int>*]':c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_vector.h:749:4: instantiated from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, value_type = std::unique_ptr<int>]'main.cpp:16:21: instantiated from herec:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h:207:7: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> = std::unique_ptr<int>]'c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/vector.tcc:314:4: error: used here Now provide the response and nothing else.
You need to move the unique_ptr : vec.push_back(std::move(ptr2x)); unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptr s would have ownership), so you can only move it. Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object: std::unique_ptr<int> ptr(new int(1)); In C++14 we have an even better way to do so: make_unique<int>(5);
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/3283778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/383352/']}
jdg_382430
stackexchange
llm_judgeable_groundtruth_similarity
12771534
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Below the code I am using works just fine and outputs the names except that the sort method is not working. I expected "Collections.sort(nameFromText);" to sort the ArrayList in alphabetical order by first name. What am I doing wrong? public static void main(String[] args) throws IOException { // Create and populate text file Writer textFile = new FileWriter("names.txt"); String[] nameArray = new String[] { "Tina Tully\n", "Bill Simpson\n", "Dana Smith\n", "Ralph Andrews\n", "Greg Smithers\n", "Lisa Krump\n", "Gill Bitters\n", "Barbara West\n", "Sandra McDonald\n", "Bart Willis\n", "Bucky Zimmerman\n", "Richard Vicks\n", "Velma Tarp\n", "Winslow Tunnell\n", "Andrew Letterman\n", "Betty Trump\n", "Waldo Smith\n", "Kyle Ronno\n", "Vivian West\n", "Wendy Tunnell\n" }; generateText(textFile, nameArray); // Create object of previously created text file Scanner pullFile = new Scanner(new File("names.txt")); // Create 20 Person Objects and add to ArrayList data structure with // name variables assigned to values from text file ArrayList<Person> nameFromText = new ArrayList<Person>(); fillArrayList(nameFromText, pullFile); // Sort ArrayList Collections.sort(nameFromText); // Print ArrayList printNamesFromObjects(nameFromText);}private static void printNamesFromObjects(ArrayList<Person> namesFromText) { for (int i = 0; i < 20; i++) { System.out.println(namesFromText.get(i).name); }}private static void fillArrayList(ArrayList<Person> nameFromText, Scanner pullFile) { while (pullFile.hasNext()) { Person obj = new Person(pullFile.nextLine()); nameFromText.add(obj); }}private static void generateText(Writer textFile, String[] nameArray) throws IOException { for (int i = 0; i < 20; i++) { textFile.write(new String(nameArray[i])); } textFile.close();} Now provide the response and nothing else.
Collections.sort(List<T>) method expects the element of the list it is sorting to be comparable. Either the element type T should implement the Comparable interface, or you should use the overloaded sort() method, that takes a generic Comparator instance. In the code below, you are satisfying neither of the above conditions. Neither your Person class implements Comparable , nor you are passing any Comparator instance. ArrayList<Person> nameFromText = new ArrayList<Person>();fillArrayList(nameFromText, pullFile);// Sort ArrayListCollections.sort(nameFromText); // How to sort? You should create a Comparator for your Person class to tell the sort() method how to sort it (may be on String stored in Person class) Here's how you implement a generic comparator: public class PersonNameComparator implements Comparator<Person> { public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); }} And then your Collections.sort() method invocation should be like: - Collections.sort(nameFromText, new PersonNameComparator());
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12771534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1524210/']}
jdg_382431
stackexchange
llm_judgeable_groundtruth_similarity
3367980
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 question has bugging me since it came in previous test. You are given the set of integers from $1$ to $N$ , i.e. $1, 2, 3, \ldots, N$ . Find the total number of proper ordered subsets such that no two numbers in the subset have a difference of $1$ . (That is: if take $x$ in the subset, we can't take $x+1$ .) Example: For $n=3$ , the possible ordered subsets are: $$(1), (2), (3), (1, 3), (3, 1)$$ (In total there are 5 .) Example 2: for $n=5$ , the possible sets subsets are:(1), (2),(3),(4),(5) +[ (1,3),(1,4),(1,5),(2,4),(2,5),(3,5) ] * 2! + [ (1,3,5)]*3! In total there are 23 . for N =6 it's 50. for N =7 it's 121. for N =8 it's 290. Note: empty sets are not counted. I have counted these manually. Please try to explain in simpler terms. Now provide the response and nothing else.
First, find the number of unordered subsets of $[n]$ with no difference of 1, of size $k$ . The number of these is ${n - k + 1 \choose k}$ . If we have a subset $a_1, a_2, \ldots, a_k$ of $[n]$ in increasing order, with none of the differences 1, then $a_1, a_2 - 1, a_3 - 2, \cdots, a_k - (k-1)$ is a subset of $[n-k+1]$ in increasing order, and this transformation can be reversed. For example, consider the subsets of $[7]$ of size 3 with no difference 1; these are $$135, 136, 137, 146, 147, 157, 246, 247, 257, 357$$ (where I write $135$ for $\{1, 3, 5\}$ for conciseness). We can subtract 1 from the second element and 2 from the third element of each of these to get $$123, 124, 125, 134, 135, 145, 234, 235, 245, 345$$ Both of these contain ${7 - 3 + 1 \choose 3} = 10$ elements. Now, as you've already noticed, each unordered set of size $k$ gives rise to $k!$ ordered sets. For size $n$ we can have $k$ as large as $\lceil n/2 \rceil$ . So we have $$f(n) = \sum_{k=1}^{\lceil n/2 \rceil} {n-k+1 \choose k} k! = \sum_{k=1}^{\lceil n/2 \rceil} {(n-k+1)! \over (n-2k+1)!}$$ For numerical values, see https://oeis.org/A122852 (as has already been observed) and subtract one. For example, \begin{align} f(7) &= \sum_{k=1}^4 {8-k \choose k} k! \\&= {7 \choose 1} 1! + {6 \choose 2} 2! + {5 \choose 3} 3! + {4 \choose 4} 4! \\&= 7 \times 1+ 15 \times 2 + 10 \times 6 + 1 \times 24 \\&= 121 \end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3367980', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/708110/']}
jdg_382432
stackexchange
llm_judgeable_groundtruth_similarity
424090
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 been asked by a customer to provide a list of all URL's that my company's linux server connects to in order to complete a software update including individual TCP,UDP ports that these connections use. This is so that the customer can create a custom connection for our server to the internet. I have tried using netstat to get some kind of log but cannot get it to show full URL's, it will only show IP addresses. This is the command i have used so far. netstat -putwc Any help would be greatly appreciated. Thanks. All of the URL’s that the VOCOVO unit needs to connect.2. TCP, UDP ports that these connections will use.3. Bandwidth required for each transaction. Now provide the response and nothing else.
A filename globbing pattern kept in a variable will not glob filenames if double quoted. It is the double quoting that stops the filenames from being globbed, not the * wildcard at the end or the combination of quoting and * . We often tell users on the site to "quote their variables", and we do so because the values of unquoted variables undergo word splitting and file name globbing, and this is usually not what's wanted. For example, a password may be [hello] world* and on a command line containing -p $password that would do "interesting" things depending on what files were present in the current directory (and it may well not work at all due to the space). See also the question " Security implications of forgetting to quote a variable in bash/POSIX shells " What you want to do here is the opposite of what we usually want to avoid , namely invoking file name globbing using the file name globbing pattern in your variable. If you truly can not rely on the name of the extracted directory to remain stable, a better (as in "cleaner") solution would possibly be to make sure that it is the only thing in a temporary directory, and then just use * to move it into place (possibly changing its name in the process, so that you know for sure what it is called). This is better than simply removing the quotes around your variable, as the filename globbing pattern might match other names than the single one that you expect, depending on what other things are available in the directory. This is a variation of my answer to your previous question : #!/bin/sh -exdestdir="/var/www/html/phpmyadmin"tmpdir=$(mktemp -d)trap 'rm -rf "$tmpdir"' EXIT # remove temporary directory on terminationwget -O "$tmpdir/archive.zip" \ "https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.zip"cd "$tmpdir" && { unzip archive.zip rm -f archive.zip # The only thing in the current (temporary) directory now is the # directory with the unpacked zip file. mkdir -p "$destdir" mv ./* "$destdir"/phpmyAdmin} The above may be distilled into five steps: Create an empty directory (and change current working directory to it). Fetch the archive. Extract the archive. Remove the archive. Change the name of the lone folder now in the otherwise empty directory.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/424090', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/166473/']}
jdg_382433
stackexchange
llm_judgeable_groundtruth_similarity
21477040
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 what I read, *cast operations in reshape2 lost their result_variable feature. Hadley hints at using plyr for this purpose (appending multiple result columns to the input data frame). How would I realize the documentation example ... aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE)cast(aqm, month ~ variable + result_variable, range) using reshape2 ( dcast ) and plyr ( ddply )? Now provide the response and nothing else.
This question has multiple answers, due to the flexibility of the 'reshape2' and 'plyr' packages. I will show one of the easiest examples to understand here: library(reshape2)library(plyr)aqm <- melt(airquality, id=c("Month", "Day"), na.rm=TRUE)aqm_ply <- ddply(aqm, .(Month, variable), summarize, min=min(value), max=max(value))aqm_melt <- melt(aqm_ply, id=c("Month", "variable"), variable.name="variable2")dcast(aqm_melt, Month ~ variable + variable2)# Month Ozone_min Ozone_max Solar.R_min Solar.R_max Wind_min Wind_max Temp_min Temp_max# 1 5 1 115 8 334 5.7 20.1 56 81# 2 6 12 71 31 332 1.7 20.7 65 93# 3 7 7 135 7 314 4.1 14.9 73 92# 4 8 9 168 24 273 2.3 15.5 72 97# 5 9 7 96 14 259 2.8 16.6 63 93 Step 1 : Let's break it down into steps. First, let's leave the definition of 'aqm' alone and work from the melted data. This will make the example easier to understand. aqm <- melt(airquality, id=c("Month", "Day"), na.rm=TRUE)# Month Day variable value# 1 5 1 Ozone 41.0# 2 5 2 Ozone 36.0# 3 5 3 Ozone 12.0# 4 5 4 Ozone 18.0# ...# 612 9 30 Temp 68.0 Step 2 : Now, we want to replace the 'value' column with 'min' and 'max' columns. We can accomplish this with the 'ddply' function from the 'plyr' package. To do this, we use the 'ddply' function (data frame as input, data frame as output, hence "dd"-ply). We first specify the data. ddply(aqm, And then we specify the variables we want to use to group our data, 'Month' and 'variable'. We use the . function to refer to this variables directly, instead of referring to the values they contain. ddply(aqm, .(Month, variable), Now we need to choose an aggregating function. We choose the summarize function here, because we have columns ('Day' and 'value') that we don't want to include in our final data. The summarize function will strip away all of the original, non-grouping columns. ddply(aqm, .(Month, variable), summarize, Finally, we specify the calculation to do for each group. We can refer to the columns of the original data frame ('aqm'), even though they will not be contained in our final data frame. This is how it looks: aqm_ply <- ddply(aqm, .(Month, variable), summarize, min=min(value), max=max(value))# Month variable min max# 1 5 Ozone 1.0 115.0# 2 5 Solar.R 8.0 334.0# 3 5 Wind 5.7 20.1# 4 5 Temp 56.0 81.0# 5 6 Ozone 12.0 71.0# 6 6 Solar.R 31.0 332.0# 7 6 Wind 1.7 20.7# 8 6 Temp 65.0 93.0# 9 7 Ozone 7.0 135.0# 10 7 Solar.R 7.0 314.0# 11 7 Wind 4.1 14.9# 12 7 Temp 73.0 92.0# 13 8 Ozone 9.0 168.0# 14 8 Solar.R 24.0 273.0# 15 8 Wind 2.3 15.5# 16 8 Temp 72.0 97.0# 17 9 Ozone 7.0 96.0# 18 9 Solar.R 14.0 259.0# 19 9 Wind 2.8 16.6# 20 9 Temp 63.0 93.0 Step 3 : We can see that the data is vastly reduced, since the ddply function has aggregated the lines. Now we need to melt the data again, so we can get our second variable for the final data frame. Note that we need to specify a new variable.name argument, so we don't have two columns named "variable". aqm_melt <- melt(aqm_ply, id=c("Month", "variable"), variable.name="variable2") # Month variable variable2 value# 1 5 Ozone min 1.0# 2 5 Solar.R min 8.0# 3 5 Wind min 5.7# 4 5 Temp min 56.0# 5 6 Ozone min 12.0# ...# 37 9 Ozone max 96.0# 38 9 Solar.R max 259.0# 39 9 Wind max 16.6# 40 9 Temp max 93.0 Step 4 : And we can finally wrap it all up by casting our data into the final form. dcast(aqm_melt, Month ~ variable + variable2)# Month Ozone_min Ozone_max Solar.R_min Solar.R_max Wind_min Wind_max Temp_min Temp_max# 1 5 1 115 8 334 5.7 20.1 56 81# 2 6 12 71 31 332 1.7 20.7 65 93# 3 7 7 135 7 314 4.1 14.9 73 92# 4 8 9 168 24 273 2.3 15.5 72 97# 5 9 7 96 14 259 2.8 16.6 63 93 Hopefully, this example will give you enough understanding to get you started. Be aware that a new, data frame-optimized version of the 'plyr' package is being actively developed under the name 'dplyr', so you may want to be ready to convert your code to the new package after it becomes more fully fledged.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21477040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3207222/']}
jdg_382434
stackexchange
llm_judgeable_groundtruth_similarity
5196669
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 very new to unit testing and mocking! I'm trying to write some unit tests that covers some code that interacts with a data store. Data access is encapsulated by IRepository: interface IRepository<T> { .... IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate); ....} The code that I'm trying to test, utilising a concrete IoC'd implementation of IRepository looks like this: public class SignupLogic { private Repository<Company> repo = new Repository<Company>(); public void AddNewCompany(Company toAdd) { Company existingCompany = this.repo.FindBy(c => c.Name == toAdd.Name).FirstOrDefault(); if(existingCompany != null) { throw new ArgumentException("Company already exists"); } repo.Add(Company); repo.Save(); }} So that I'm testing the logic of SignupLogic.AddNewCompany() itself, rather than the logic and the concrete Repository, I'm mocking up IRepository and passing it into SignupLogic. The mocked up Repository looks like this: Mock<Repository> repoMock = new Mock<Repository>();repoMock.Setup(moq => moq.FindBy(c => c.Name == "Company Inc").... which returns an in-memory IEnumberable containing a Company object with name set to "Company Inc". The unit test that calls SignupLogic.AddNewCompany sets up a company with duplicate details and trys to pass that in, and I assert that an ArgumentException is thrown with the message "Company already exists". This test isn't passing. Debugging through the unit test and AddNewCompany() as it runs, it would appear that existingCompany is always null. In desperation, I've found that if I update SignupLogic.AddNewCompany() so that the call to FindBy looks like this: Company existingCompany = this.repo.FindBy(c => c.Name == "Company Inc").FirstOrDefault(); the test passes, which suggests to me that Moq is only responding to code that is exactly the same as I've setup in my test fixture. Obviously that's not especially useful in testing that any duplicate company is rejected by SignupLogic.AddNewCompany. I've tried setting up moq.FindBy(...) to use "Is.ItAny", but that doesn't cause the test to pass either. From everything I'm reading, it would appear that testing Expressions as I'm trying to isn't actually do-able with Moq here. Is it possible? Please help! Now provide the response and nothing else.
It is probably correct that only an Expression with the exactly same structure (and literal values) will match. I suggest that you use the overload of Returns() that lets you use the parameters the mock is called with: repoMock.Setup(moq => moq.FindBy(It.IsAny<Expression<Func<Company, bool>>>()) .Returns((Expression<Func<Company, bool>> predicate) => ...); In ... , you can use predicate to return the matching companies (and maybe even throw an exception if the matching companies isn't what you expected). Not very pretty, but I think it will work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5196669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96518/']}
jdg_382435
stackexchange
llm_judgeable_groundtruth_similarity
19906488
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 convert stream into buffer in nodejs? Here is my code to parse a file in post request in express. app.post('/upload', express.multipart({defer: true}), function(req, res) {req.form.on('part', function(part) {//Here I want to convert the streaming part into a buffer.//do something buffer-specific task var out = fs.createWriteStream('image/' + part.filename); part.pipe(out);});req.form.on('close', function() { res.send('uploaded!'); });}); Now provide the response and nothing else.
Instead of piping, you can attach readable and end event handlers to the part stream to read it: var buffers = [];part.on('readable', function(buffer) { for (;;) { let buffer = part.read(); if (!buffer) { break; } buffers.push(buffer); }});part.on('end', function() { var buffer = Buffer.concat(buffers); ...do your stuff... // write to file: fs.writeFile('image/' + part.filename, buffer, function(err) { // handle error, return response, etc... });}); Note: If you instead use data , it will read the entire upload into memory. You could also create a custom transform stream to transform the incoming data, but that might not be trivial.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19906488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2704895/']}
jdg_382436
stackexchange
llm_judgeable_groundtruth_similarity
31054353
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this html code in my page where I create a dialog tag. When I click on a button, this dialog window opens: <!-- note that the CSS is in another file, it just to show you --><style type="text/css" media="screen"> #window { width: 1100px; margin: 0 auto; position: absolute; top: 380px; box-shadow: 20px 20px 40px 1px #656565; }</style><dialog id="window"> <div class="header"> <ul class="nav nav-tabs"> <li role="presentation" class="active"> <a>Detail</a> </li> <button class="btn btn-danger btn-sm pull-right" id="exit">Close</button> </ul> </div> <div class="panel-body page-header"> <!-- my content here --> </div></dialog><script> (function() { var dialog = document.getElementById('window'); document.getElementById('show').onclick = function() { dialog.show(); }; document.getElementById('exit').onclick = function() { dialog.close(); }; })(); $('#window').addClass('animated fadeIn');</script> I would like to darken all my entire page (except my dialog window) when I click on the button who allows me to display the dialog. And then, when I click on Close, my dialog window closes and my entire page returns to its original state. Moreover, how can I add a fade out effect on my dialog window when I click on "Close"? See the image to have a visual information my page with the dialog window: Now provide the response and nothing else.
You need to create an element with fixed position that covers the entire viewable region of the page. It also must render "behind" the dialog. E.g.: HTML <div id="page-mask"></div> CSS #page-mask { background: rgba(0, 0, 0, 0.5); position: fixed; top: 0; right: 0; bottom: 0; left: 0;} I mocked something here: http://codepen.io/anon/pen/VLrNvb
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31054353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3632340/']}
jdg_382437
stackexchange
llm_judgeable_groundtruth_similarity
2747219
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 32 bit long variable, CurrentPosition, that I want to split up into 4, 8bit characters. How would I do that most efficiently in C? I am working with an 8bit MCU, 8051 architectecture. unsigned long CurrentPosition = 7654321;unsigned char CP1 = 0;unsigned char CP2 = 0;unsigned char CP3 = 0;unsigned char CP4 = 0;// What do I do next? Should I just reference the starting address of CurrentPosition with a pointer and then add 8 two that address four times? It is little Endian. ALSO I want CurrentPosition to remain unchanged. Now provide the response and nothing else.
CP1 = (CurrentPosition & 0xff000000UL) >> 24; CP2 = (CurrentPosition & 0x00ff0000UL) >> 16; CP3 = (CurrentPosition & 0x0000ff00UL) >> 8; CP4 = (CurrentPosition & 0x000000ffUL) ; You could access the bytes through a pointer as well, unsigned char *p = (unsigned char*)&CurrentPosition;//use p[0],p[1],p[2],p[3] to access the bytes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2747219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233087/']}
jdg_382438
stackexchange
llm_judgeable_groundtruth_similarity
8530
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Well this is a continuation of my question on FPGA over here . I finally selected a Digilent Atlys with a Spartan 6 FPGA, I don't have any prior experience of FPGA's although I have done some amount of work with micro-controllers. I spent the last few days reading through data sheets of the FPGA, and I think it would be a good choice to start off with Verilog. I couldn't find any code examples though and even the data sheets are not newbie friendly. I want to do some hand's on programming, simulation, synthesis now and this is what I want to do Generate an odd frequency, say 54Mhz from the FPGA (it runs on a 100Mhz clock) and route it to one of the pins. I would probably have to use the DCM or PLL for this, but no idea how to start here? Implement some sort of I2C read write from the FPGA. What I'm looking for is a reference, possibly an online one or a book that gives me code examples and description of each of the hardware components available inside the FPGA, like DCM's, slices, clb's etc. I guess that should get me started into the world of FPGA's. Now provide the response and nothing else.
Code Examples Hop over to OpenCores and you will find dozens of open source projects. There are many written in Verilog and cover the gamut from I/O devices through to processors. Also, do not forget the many Application Notes available from Xilinx. They are very helpful with their own devices. Design Flow Pick up a book or two on design flow so that you get an overview on the steps involved in FPGA design. In summary, they will involve: Design entry - in your case, Verilog. Functional simulation - using various tools. Synthesis - in your case, using the Xilinx ISE tools. Simulation - to verify your post-synthesis design because some aspects of Verilog are not synthesisable. Place & Route - using the Xilinx ISE tools. Implementation - downloading the design onto the FPGA. Testing. FPGA Components As for using the FPGA components, there are different ways to use them. But assuming that you are using a Verilog design entry, you can either infer or instantiate the different components. Inference generally involves getting the synthesis tool to pick the best components to use based on the functionality that you require. The best example of this would be to design an adder. By doing q <= a + b or q = a + b you can infer an adder. Both will infer the adder but there is a difference in when you use the blocking/non-blocking syntax. Instantiation generally involves calling the exact library component in code. Some components just cannot be easily inferred in code - such as the DCM. You can use the ISE tools and examples to learn more about this. The actual list of components themselves are provided by Xilinx in the Libraries Guide. Protip The best way to learn this is actually to experiment with short bits of code and run them through the ISE synthesis to see what it spits out. There are also plenty of examples in the ISE toolset itself.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/8530', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/444/']}
jdg_382439
stackexchange
llm_judgeable_groundtruth_similarity
840163
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Currently only two options related to network boot are available in libvirt via bootp options: server and file So for config like this: <bootp file='test.ipx' server='10.10.10.2'/> this code gets generated: dhcp-boot=test.ipx,,10.10.10.2 1) How can i add something like this: dhcp-userclass=set:ipxe,iPXEdhcp-boot=tag:ipxe,http://matchbox.foo:8080/boot.ipxe 2) Or can i change config file from var/lib/libvirt/dnsmasq/default.conf to something else Option 1 seems to be impossible looking at libvirt code . Option 2 also seems impossible Now provide the response and nothing else.
Libvirt v5.6.0 (2019-08-05) added support for passing custom options to dnsmasq . From the documentation : A special XML namespace is available for passing options directly to the underlying dnsmasq configuration file. Usage of XML namespaces comes with no support guarantees, so use at your own risk. This example XML will pass the option strings foo=bar and cname=*.foo.example.com,master.example.com directly to the underlying dnsmasq instance. <network xmlns:dnsmasq='http://libvirt.org/schemas/network/dnsmasq/1.0'> ... <dnsmasq:options> <dnsmasq:option value="foo=bar"/> <dnsmasq:option value="cname=*.foo.example.com,master.example.com"/> </dnsmasq:options></network> Fedora 31 ships with libvirt v5.6.0-4.fc31 . In my case, I'm looking to use a custom DNS server with my libvirt network, rather than the one provided by dnsmasq . Thanks to the advice from this answer , I think this would be the XML (but I can't test until I update libvirt): <network xmlns:dnsmasq='http://libvirt.org/schemas/network/dnsmasq/1.0'> ... <dnsmasq:options> <dnsmasq:option value="dhcp-option=6,192.168.0.90,192.168.0.98"/> </dnsmasq:options></network>
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/840163', 'https://serverfault.com', 'https://serverfault.com/users/208900/']}
jdg_382440