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
|
40172731
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new into rxJava and it's making my head spin. Basically I'm pulling data from youtube api with retrofit which gives back Observable and with youtubeDataMapper I'm mappng it into Youtube Pojo object which contains String videoID. So my question is, how to make this method return that string instead of Completable? This is my method: @Override public Completable downloadVideoUrl(String query) { addSubscription(youtubeApi.getYoutubeId(query, Constants.youtubeApi) .map(youtubeDataMapper::map) .subscribeOn(subscribeScheduler) .observeOn(observeScheduler) .subscribe()); return Completable.complete();}
Now provide the response and nothing else.
|
You have two choices: Make your downloadVideoUrl return Observable instead of Completable : Preferred way: @Overridepublic Completable downloadVideoUrl(String query) { return youtubeApi.getYoutubeId(query, Constants.youtubeApi) .map(youtubeDataMapper::map) .subscribeOn(subscribeScheduler) .observeOn(observeScheduler);} Notice lack of subscribe operator here. Then wherever you want to get videoId: downloadVideoUrl(query) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String videoId) { // do whatever you want with videoId } }); Use toBlocking().first() This is not preffered as you block current Thread until Observable finishes @Overridepublic String downloadVideoUrl(String query) { return youtubeApi.getYoutubeId(query, Constants.youtubeApi) .map(youtubeDataMapper::map) .subscribeOn(subscribeScheduler) .observeOn(observeScheduler) .toBlocking().first();}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40172731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5994596/']}
|
jdg_376841
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12590963
|
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 ASP.Net application that performs some database initialization during Application_Start in Global.asax. I'm using IIS Express to debug the application. I find that if I stop debugging, clear the database, and restart again, the Application_Start code does not get called and my database is not initialized properly, so my application fails. This is because the IIS Express instance is still running after debugging stops. Rather than restarting it, Visual Studio appears to be attaching to the existing process. Is there a way to change this behavior such that starting a new debugging session always restarts the application process in IIS Express (or resets the application pool in regular IIS)? Alternatively, is there a way to force IIS Express to shut down when the debugging session ends? I did find that if I check "Enable Edit and Continue" from the Web dialog in the project settings, that it has the side effect of stopping IIS Express when debugging ends. But I'm not sure I want to introduce the side-effects of Edit and Continue just for the purposes of stopping IIS Express. Surely there's a better way? Not sure if it matters, but this is VS2012.
Now provide the response and nothing else.
|
Unfortunately it's not achievable through configuration. I may propose you another trick, but it's up to you to decide whether it's better than yours or not :) You may create a post-build event which changes the timestamp of a web.config file. I used a touch.exe tool from http://www.stevemiller.net/apps/ . You also need to set the "Run the post-build event" to Always. So your "Build Events" configuration may look as follows: With this option set anytime you start the debugger, web.config timestamp is getting updated causing application restart (application appdomain reload) on the first request - but at this point you are already attached to this process so your Application_ event breakpoints should work.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12590963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634824/']}
|
jdg_376842
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
317335
|
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 understand that, if S is a child class of T , then a List<S> is not a child of List<T> . Fine. But interfaces have a different paradigm: if Foo implements IFoo , then why is a List<Foo> not (an example of) a List<IFoo> ? As there can be no actual class IFoo , does this mean that I would always have to cast each element of the list when exposing a List<IFoo> ? Or is this simply bad design and I have to define my own collection class ListOfIFoos to be able to work with them? Neither seem reasonable to me... What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my List<Foo> internally as a List<IFoo> .
Now provide the response and nothing else.
|
Your List<Foo> is not a subclass if List<IFoo> because you cannot store an MyOwnFoo object in it, which also happens to be an IFoo implementation. ( Liskov substitution principle ) The idea of storing a List<IFoo> instead of a dedicated List<Foo> is OK. If you need casting the list's contents to it's implementation type, this probably means your interface is not appropriate.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/317335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6091/']}
|
jdg_376843
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
72790
|
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:
There are three random variables, $x,y,z$. The three correlations between the three variables are the same. That is, $$\rho=\textrm{cor}(x,y)=\textrm{cor}(x,z)=\textrm{cor}(y,z)$$ What is the tightest bound you can give for $\rho$?
Now provide the response and nothing else.
|
The common correlation $\rho$ can have value $+1$ but not $-1$. If $\rho_{X,Y}= \rho_{X,Z}=-1$, then $\rho_{Y,Z}$ cannot equal $-1$ but is in fact $+1$.The smallest value of the common correlation of three random variablesis $-\frac{1}{2}$. More generally,the minimum common correlation of $n$ random variables is $-\frac{1}{n-1}$when, regarded as vectors, they are at the vertices of a simplex (of dimension $n-1$)in $n$-dimensional space. Consider the variance of the sum of$n$ unit variance random variables $X_i$. We have that$$\begin{align*}\operatorname{var}\left(\sum_{i=1}^n X_i\right)&= \sum_{i=1}^n \operatorname{var}(X_i) + \sum_{i=1}^n\sum_{j\neq i}^n \operatorname{cov}(X_i,X_j)\\&= n + \sum_{i=1}^n\sum_{j\neq i}^n \rho_{X_i,X_j}\\&= n + n(n-1)\bar{\rho} \tag{1}\end{align*}$$where $\bar{\rho}$ is the average value of the $\binom{n}{2}$correlation coefficients.But since $\operatorname{var}\left(\sum_i X_i\right) \geq 0$, we readily get from$(1)$ that $$\bar{\rho} \geq -\frac{1}{n-1}.$$ So, the average value of a correlation coefficient is at least $-\frac{1}{n-1}$. If all the correlation coefficientshave the same value $\rho$, then their average alsoequals $\rho$ and so we have that $$\rho \geq -\frac{1}{n-1}.$$Is it possible to have random variables for which the commoncorrelation value $\rho$ equals $-\frac{1}{n-1}$? Yes. Suppose that the $X_i$ are uncorrelated unit-variance random variables and set$Y_i = X_i - \frac{1}{n}\sum_{j=1}^n X_j = X_i -\bar{X}$. Then, $E[Y_i]=0$, while$$\displaystyle \operatorname{var}(Y_i) = \left(\frac{n-1}{n}\right)^2 + (n-1)\left(\frac{1}{n}\right)^2= \frac{n-1}{n}$$ and$$\operatorname{cov}(Y_i,Y_j) = -2\left(\frac{n-1}{n}\right)\left(\frac{1}{n}\right) +(n-2)\left(\frac{1}{n}\right)^2 = -\frac{1}{n}$$giving $$\rho_{Y_i,Y_j} = \frac{\operatorname{cov}(Y_i,Y_j)}{\sqrt{\operatorname{var}(Y_i)\operatorname{var}(Y_j)}}=\frac{-1/n}{(n-1)/n} = -\frac{1}{n-1}.$$Thus the $Y_i$ are random variables achieving the minimum commoncorrelation value of $-\frac{1}{n-1}$. Note, incidentally, that$\sum_i Y_i = 0$, and so, regarded as vectors, the random variableslie in a $(n-1)$-dimensional hyperplane of $n$-dimensional space.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/72790', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/31500/']}
|
jdg_376844
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
574503
|
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:
Recently, I encountered a problem about infinite series.So my question is how to know whether the infinite series $\sum _{n=2}^{\infty } \frac{1}{n \log (n)}$ is convergent?
Now provide the response and nothing else.
|
To see whether $\sum_2^\infty 1/(n \log n)$ converges, we can use the integral test. This series converges if and only if this integral does:$$\int_2^\infty \frac{1}{x \log x} dx = \left[\log(\log x)\right]_2^\infty$$and in fact the integral diverges. This is part of a family of examples worth remembering. Note that$$d/dx \log(\log(\log x)) = d/dx \log(\log x) \cdot \frac{1}{\log (\log x)} = \frac{1}{x \log x \log(\log x)}$$and $\log (\log (\log x)) \to \infty$ as $x \to \infty$ hence $\sum \frac{1}{n \log n \log (\log n)}$ diverges as well. Similarly, by induction we can put as many iterated $\log$s in the denominator as we want (i.e. $\sum \frac{1}{n \log n \log(\log n) \ldots \log (\ldots (\log n) \ldots )}$ where the $i$th log is iterated $i$ times), and it will still diverge. However, as you should check, $\sum \frac{1}{x \log^2x}$ converges, and in fact (again by induction) if you square any of the iterated logs in $\sum \frac{1}{n \log n \log(\log n) \ldots \log (\ldots (\log n) \ldots )}$ the sum will converge.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/574503', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/110169/']}
|
jdg_376845
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2085521
|
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:
Forgive my ignorance. The below seems 'inconsistent'. If canceling the $(x+1)$ is 'legal', how does the domain change? I realize it does, but would someone be so kind as to provide an explanation? $$ \frac{x^2 - 1}{x + 1} \mbox{ is undefined when } x = -1 $$ Its domain (the values that can go into the expression) does not include $ -1 $. Now, we can factor $ x^2 - 1 $ into $ (x - 1)(x + 1) $ so we get: $$ \frac{(x - 1)(x + 1)}{(x + 1)} $$ It is now tempting to cancel $ (x + 1) $ from top and bottom to produce: $$ x - 1 $$ $$ \mbox{Its domain now } \textbf{does} \mbox{ include } -1 \mbox{.} $$ But it is now a different function because it has a different domain. Thanks!
Now provide the response and nothing else.
|
A function is not just an expression . It is a special assignment (a formula, a table, a diagram, etc) together with a chosen domain and a chosen codomain. The choices must make sense however. If the domain is the same, the codomain is the same and $f(x)$ and $g(x)$ coincide for every member $x$ of the domain, only then do we say the functions are equal. For example, let $f(x) = \dfrac{x^2-1}{x+1}$ and $g(x) = x-1$. and let's choose the domain for both to be the set $\{1,2,3,4,...\}$ and lets choose the codomain to be the range (which is $\{0,1,2,...\}$). In this case, $f$ and $g$ are the same function. For every member $N$ of the domain, $f(N)$ is equal to $g(N)$. If we choose the domain instead to be $\mathbb R$ then we run into a problem. $g$ is happy with $-1$ which now belongs to the domain, it hands you back $g(-1)=-2$. but $f(-1)$ doesn't make sense, so the domain we chose for $f$ doesn't even work. We're broken from the get-go. They can't be the same if the function $f$ can't even exist. Now if we choose the domain for both of them to be everything except for $-1$ , sometimes written $\mathbb R \setminus \{-1\}$, and to have codomain $\mathbb R$, then $f$ and $g$ are again the same function.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2085521', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/401376/']}
|
jdg_376846
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2747376
|
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:
These two formulae were given in my circuit analysis textbook: Fourier Transform: $$F(\omega)=\int_{-\infty}^{\infty}f(t)e^{-i\omega t}dt$$ Inverse Fourier Transform: $$f(t)=\frac{1}{2\pi}\int_{-\infty}^{\infty}F(\omega)e^{i\omega t}d\omega$$ I have a bit of a doubt as to whether the second formula is true. I don't understand where the $2\pi$ factor is coming from in the second formula? If the above hold formulae true, is is the following provable? $$f(t)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\left(\int_{-\infty}^{\infty}f(t)e^{-i\omega t}dt\right)e^{i\omega t}d\omega$$
Now provide the response and nothing else.
|
The factor comes from the fact that $$\delta (x-\alpha )={\frac {1}{2\pi }}\int _{-\infty }^{\infty }e^{ip(x-\alpha )}\ dp \tag{1}$$ Consider your last integral \begin{eqnarray}\frac{1}{2\pi}\int_{-\infty}^{\infty}\left(\int_{-\infty}^{\infty}f(t')e^{-i\omega t'}dt'\right) e^{i\omega t} d\omega &=& \frac{1}{2\pi}\int_{-\infty}^{\infty}\left(\int_{-\infty}^{\infty}f(t')e^{-i\omega t'}e^{i\omega t} dt'\right) d\omega \\&=& \int_{-\infty}^{\infty}f(t')\left(\frac{1}{2\pi}\int_{-\infty}^{\infty}e^{i\omega (t - t')}d\omega \right) dt' \\&\stackrel{(1)}{=}& \int_{-\infty}^{\infty}f(t')\delta(t-t')dt' \\&=& f(t) \tag{2}\end{eqnarray}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2747376', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_376847
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
501285
|
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:
Starting at the beginning: I have a shunt that carries DC current, and the voltage drop is very slight. I want to amplify it in order to see it better on oscilloscope, and to have it scaled correctly for e.g. an Arduino ADC. This to measure the current. So one side of the shunt has voltage V (~12V), the other side has V minus epsilon. I have a pile of NPN and PNP transistors, capacitors, resistors, diodes, etc… It would be more obvious to me as a newbie if I were trying to scale up a signal around 0V, but since I'm trying to measure "epsilon". I would like to power the whole thing (transistors, arduino, etc…) off of the same circuit, so I'm guessing I'd need a common ground. This means I don't think I can use "V-epsilon" as ground. So, how do I amplify, and/or "re-base" this voltage drop across the shunt? Edit:Ideally not with a ready component dedicated for this (though thank you for the pointer to that), since this is also part for me to understand how to build circuits with transistors, and I have transistors on hand and stores are not exactly open and convenient at the moment. (oops, obviously buck converter also has access to grund. And "magic happens here" can also have access to both ground and 5V from buck converter)
Now provide the response and nothing else.
|
If you want a canned solution you can use a "current sense amplifier". This is the name of the category you should dig in at your favorite supplier. These amps are characterized by the usual parameters: offset, bandwidth, acceptable common mode range, etc. Make sure you check. But they have extra features on top of that. They work from a low impedance source (usually a current shunt) so the effects of source impedance imbalance on CMRR due to high source impedance on CMRR can be neglected. This allows a circuit that is simpler and cheaper than an instrumentation amplifier. An important bit is that usually a current sense amp is able to sense a tiny voltage on the high side (on a shunt in the power supply) at a voltage above its own power supply. Some can sense with large negative common mod too. Some sense current at one polarity only, others at both polarities. So, check the specs. For example if you have a 3.3V supply for your ADC you can power MAX4378 from +3V3 and sense current in a 24V supply. Here is one: MAX4376 but there are a lot. For a high side shunt you could also use an opamp wired as a difference amplifier , however if you want high gain the acceptable common mode range of this circuit means that this requires a rail to rail input opamp powered from the rail you want to sense. Also the output is referenced to the power rail, not ground, which is inconvenient, and it is unidirectional. A canned current sense amp chip is much simpler to use. Now if you want a discrete circuit (since you mention discrete transistors...) One could use a low offset discrete opamp to implement Spehro's circuit. This would need matched transistors like DMMT3904. Input common mode has to include the positive rail, which means a darlington to add a bit of voltage headroom to avoid saturating the BJTs in the current mirror and differential pair. This is an interesting circuit (gain is R6/R2) but quite complicated versus a SOT23 ready made amplifier. Another crude circuit could be this one. Its output is referenced to ground, but there is an inconvenient DC offset voltage at zero current. This could be an advantage, as it means it can sense current in both directions, but you got to calibrate the offset out somehow. This one has a differential output, with a common mode you can choose. If you need a single-ended ground-referenced output, an extra opamp is needed. Note the offset of all these circuits will depend on matching between transistors in the differential pair. You can always use a DMMT3904 which I think is specced for 1mV offset, but that is not as good as a decent current sense amp. Linearity should be good for the first one (it's an opamp with feedback). The others don't use feedback so they'll be a bit less linear, but they are much simpler. EDIT: The last two circuits exploit the fact that the signal to be amplified is presented at a very low impedance on the low value shunt resistor, which means instead of using transistor bases as input we can use the emitters... because as you know the emitter is an output, but it is also a low impedance input ! This isn't really an opamp, rather it's a simple feedback circuit with a differential input pair Q6,Q7 biased via Q5. Current mirror Q8,Q9 directs the output current of the diff pair into Q10. It tries to keep voltage on Q6,Q7 emitters equal by injecting a small adjustment current via Q10 which changes Q7 emitter voltage to make it the same as Q6 emitter voltage. So this current is proportional to the voltage being measured on the shunt, and since this current is created via R8, we get out amplified output voltage on R8. Again, don't expect miracles wrt accuracy or offset voltage, but it's a much simpler version of the first schematic and similar performance.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/501285', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/226196/']}
|
jdg_376848
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1035
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Grid to document a demo I have. i.e. I am writing the documentation of the demo as a help option, which will display information when clicked on. Everything is working well. I am using the following pattern to do that: help=Block[{a,b,c,.....}, (*Block is needed to prevent $nnn in symbols showing*) Style[TraditionalForm[Grid[{ {"some text here, all in string"}, {equation here using symbols a,b,c, as in a=b+c}, ... ]], FontFamily -> "Times"] ] Then later on, when I want to display information, I simply display the help symbol. The nice thing also about this, is that I typeset these all once, in the initialization section. So that it is fast to display before as the help is typeset once and stored in the symbol. The final result is really nice. The same as Latex. I see no difference at all. The only glitch, is when I have long text, I'd like it to be full justified. Using normal Grid Alignments does not help here, and so I have to use TextCell , with the TextJustification->1 for it to work. But the only problem is that some of the text I have might include subscript, like this one example: And you can see that the TextCell does not like that one part (I understand also why it is not happy). I am trying to see if I can use TextCell (as it seems the only way to have text justified in a grid) and at the same time use little bit of subscript and such in the string. If there is such a trick. For the actual math part of the documentation, I can split the math from the text like I show above in the rest of the grid. But there are some parts, where I need to write all the text in one place, and use little bit of subscript and such in there. But also be able to text justify everything so it looks nice. In a way, this is like I do in Latex, where the main equations go as centered form, and the description around them has very little math. I am trying to emulate this with the help of Grid. If I do not use textCell, this is the result: So it works now, but text is not justified inside the grid. It does not look as nice. Here is the code, if someone wants to try something. I tried many things, but so far, no luck. below is small example, left many things out. I have to keep the ContentSize fixed there since the overall size is fixed for display. Manipulate[ Style[TraditionalForm[Grid[{ {"let \!\(\*SubscriptBox[\(u\), \(n\)]\) be the outward normal \derivative on the boundary"} }, Frame -> All] ], FontFamily -> "Times"], ContentSize -> {300, 475} ] I do not want to use GraphisGrid and rasterize things and such. And this will be used for a demo that runs in CDF plugin, so the following symbols can't be used : SetOptions , ToExpression , Symbol , $Context , SetAttribute s, Clear , Unprotect , DownValues , UpValues , OwnValues and packages not allowed to be used or created also. Also, Manipulate[] has to be the most outside construct. Thank you, Note: TextJustification -> 1 does alignment on BOTH ends. Using LineIndent->0 only does it on one side. Below is an example of the difference.
Now provide the response and nothing else.
|
You can also supply a Row to the TextCell where the elements in the row can be a mix of strings and other expressions, so you could split the whole text into string fragments and bits of maths like this TextCell[Row[{"This is some text ", HoldForm[Subscript[a, b]], ". This is more text"}], TextJustification -> 1] To show that it works: Panel[Style[TraditionalForm[Grid[{ {"Boundary Conditions", SpanFromLeft}, {TextCell[ Row[{"This is some text, this is some text, this is some text ", HoldForm[Subscript[a, b]], " this is more text."}], TextJustification -> 1], SpanFromLeft}, {"West", HoldForm[u = \[Alpha][y]], HoldForm[Subscript[u, n] = \[Alpha][y]]}}, Frame -> All]], 15, FontFamily -> "Times"], ImageSize -> 250]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/1035', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/70/']}
|
jdg_376849
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
226309
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
is it possible to obtain a closed-form solution w.r.t. ${P_j:\forall j}$ (or in terms of special functions) for the following equations: $\alpha P_0=P_1$, $\alpha<1$ $\alpha P_j=P_{j+1}+P_{j+2}+\dots+P_{2j+1}$ for $j=1,2,....$ $\sum_{i=1}^\infty P_i=1$ $P_i\geq 0, \forall i$ OR let me put the very original equations below: $\lambda P_0=\mu P_1$ $\lambda P_{j-1} + \mu (P_{2j}+P_{2j+1})=(\lambda+\mu)P_j, \forall j>0$ $\sum_{i=1}^\infty P_i=1$ $P_i\geq 0, \forall i$
Now provide the response and nothing else.
|
In the fourth section of this paper http://www.staff.uni-bayreuth.de/~bt270951/quart9h.pdf they sketch the proof. The idea is that the orthogonal complement of the subspace generated by the sixteen $-2$ curves in $\mathrm{H}^2(Km(A),\mathbb{Z})$ is isomorphic to $\mathrm{H}^2(A,\mathbb{Z})$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/226309', 'https://mathoverflow.net', 'https://mathoverflow.net/users/42511/']}
|
jdg_376850
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33979732
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on Ipython and Spark and I have a RDD from which I form a list . Now from this list I want to form a dataframe which has multiple columns from parent list but these columns are not contiguous. I wrote this but it seems to be working wrong: list1 = rdd.collect()columns_num = [1,8,11,17,21,24]df2 = [list[i] for i in columns_num] The above code only selects 6 rows, with only column 1 data, from parent list and forms the new dataframe with those 6 columns 1 data. How can I form a new dataframe with multiple not contiguous columns from another list
Now provide the response and nothing else.
|
For example like this: rdd = sc.parallelize([("a", 1, 2, 4.0, "foo"), ("b", 3, 4, 5.0, "bar")])columns_num = [0, 3]df = rdd.toDF()df2 = df.select(*(df.columns[i] for i in columns_num))df2.show()## +---+---+## | _1| _4|## +---+---+## | a|4.0|## | b|5.0|## +---+---+ or like this: df = rdd.map(lambda row: [row[i] for i in columns_num]).toDF()df.show()## +---+---+## | _1| _4|## +---+---+## | a|4.0|## | b|5.0|## +---+---+ On a side not you should never collect data just to reshape. In the best case scenario it will be slow, in the worst case scenario it will simply crash.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33979732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3926499/']}
|
jdg_376851
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42453293
|
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 added mapClicked event of angular2-google-maps map. The code is as below: mapClicked($event: MouseEvent) {this.markers.push({ lat: $event.coords.lat, lng: $event.coords.lng, draggable: false}); } I am getting compile time error while serving my ionic 2 app with "ionic serve". Thanks in advance,AB
Now provide the response and nothing else.
|
This is just Typescript complaining since the default MouseEvent interface doesn't have the coords property, but since you're using angular2-google-maps you know the coords property will be there ( ng2 google maps MouseEvent interface ) so you can avoid that compile time error by just using any instead of MouseEvent like this: mapClicked($event: any) {this.markers.push({ lat: $event.coords.lat, lng: $event.coords.lng, draggable: false}); EDIT Just like @Bruno Garcia pointed out, a better way to solve this would be to import the proper interface from the AGM library. That way you could use typings and the autocomplete feature of the IDE for that MouseEvent event. But instead of importing the MouseEvent as he described in his answer, I'd prefer to use an alias, to avoid any confusion with the default MouseEvent interface : import { MouseEvent as AGMMouseEvent } from '@agm/core'; and then just use that alias: mapClicked($event: AGMMouseEvent) { ... }
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42453293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2885934/']}
|
jdg_376852
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
285642
|
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 given to understand that the Dirac delta function is strictly not a function in the conventional sense and it is a "functional or a distribution". The part which I can not understand why the Delta "function" makes sense only when it acts on another function and that too only inside an integral and how is a "functional" or "distribution" different from a function.
Now provide the response and nothing else.
|
First you should confront the question why should I think of the $\delta$-function as a function at all? If you are trying to imagine it as a real-valued function of real inputs, which just happens to be $0$ just about everywhere, then you are off to a bad (but very common) start. You can define $\delta$ as a symbol with certain properties relating to combining it with an actual function and some other symbols (e.g. $\int$), and this really suffices for most purposes, so why insist on trying to cram such an interesting object into a limited definition of "function?" So instead, let's take a different approach. Let $f : \mathbb{R} \to \mathbb{C}$ be a generic function from the reals to the complexes. Consider the set of all 1 such functions, and call it $L$ for lack of a better letter. $L$ is a set just like $\mathbb{R}$, and so we can define maps (read: functions) from it to $\mathbb{C}$ as well. The $\delta$-function is one such beast, defined by\begin{align}\delta : L & \to \mathbb{C} \\f & \mapsto f(0).\end{align}Thus it is a function, but not of real numbers. It is a function of functions of reals, which is sometimes called a functional . So what about the integrals? Well you can also approach this in a limiting fashion. One way is to note that$$ \lim_{\sigma\to0} \int\limits_\mathbb{R} f(x) \frac{1}{\sqrt{2\pi\sigma^2}} \mathrm{e}^{-x^2/2\sigma^2} \mathrm{d}x = f(0). $$Exchange the limit and the integral 2 , and you see that there is a "function" - or rather a limit of a sequence of functions from $L$ that is itself not a member of $L$ - whose values seem to be given by$$ \delta(x) = \lim_{\sigma\to0} \frac{1}{\sqrt{2\pi\sigma^2}} \mathrm{e}^{-x^2/2\sigma^2}. $$This is what a distribution is, with terminology suggestive of the probability distributions one so often integrates against (though I could be mistaken on the etymology). Note though that we really weren't allowed to switch that limit and integral while we still called that Gaussian-looking thing a member of $L$. After all, taking the pointwise limit first produces something that vanishes everywhere but a point, and such an object will cause the Lebesgue integral we were using to vanish as well. In any event, the integral was there from the very beginning. You can think of this as overbearing notation for what we really wanted to say: "Give the value that results when $\delta$ acts on $f$." The integral notation has another advantage, though, and that is in connection with inner product spaces . Secretly, we constructed $L$ to be a vector space over $\mathbb{R}$. Then the set of linear maps from $L$ to $\mathbb{C}$ form its dual space $L^*$. For every $g \in L$ there is a corresponding $g^* \in L^*$, which can conveniently be represented in this integral notation as the complex conjugate of $g$. 3 The inner product of $f$ and $g$ is$$ \langle f | \underbrace{g}_{g\in L} \rangle = \int\limits_\mathbb{R} f(x) \underbrace{g^*}_{g,g^*\in L}(x) \mathrm{d}x, $$and so you can identify\begin{align}\underbrace{g^*}_{g^*\in L^*} : L & \to \mathbb{C} \\f & \mapsto \int\limits_\mathbb{R} f\underbrace{g^*}_{g,g^*\in L}.\end{align} Now for every $g \in L$ there is a corresponding dual member that you can write as the complex conjugate of $g$ for the purposes of such integration, but the converse is not true. 4 $\delta$ is an example of a member of $L^*$ that has no actual function in $L$ we can complex conjugate and integrate against to replicate its behavior. 1 In practice this is often too much. It's better to restrict attention to, e.g., all square-integrable functions from $\mathbb{R}$ to $\mathbb{C}$. 2 Beware! A very dangerous thing to do! 3 Yes, we are about to thoroughly abuse the two meanings of $*$ - be on the lookout. 4 It won't be in general unless $L$ is finite-dimensional, but in that case you have Kronecker deltas and finite sums rather than Dirac deltas and integrals.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/285642', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54967/']}
|
jdg_376853
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12467354
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The goal of my query is to return the country name and its head of state if it's headofstate has a name starting with A, and the capital of the country has greater than 100,000 people utilizing a nested query. Here is my query: SELECT country.name as country, (SELECT country.headofstate from country where country.headofstate like 'A%') from country, city where city.population > 100000; I've tried reversing it, placing it in the where clause etc. I don't get nested queries. I'm just getting errors back, like "subquery returns more than one row" and such. If someone could help me out with how to order it, and explain why it needs to be a certain way, that'd be great.
Now provide the response and nothing else.
|
If it has to be "nested", this would be one way, to get your job done: SELECT o.name AS country, o.headofstate FROM country oWHERE o.headofstate like 'A%'AND ( SELECT i.population FROM city i WHERE i.id = o.capital ) > 100000 A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12467354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1658717/']}
|
jdg_376854
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
448657
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having a little trouble getting my head around the conceptual difference between an object and a class. I don't really understand the distinction between the two in any programming language, but currently I'm working with Perl, and Moose, so I'd prefer an explanation using those things. Cheers
Now provide the response and nothing else.
|
There are lots of "a class is a blueprint, an object is something built from that blueprint", but since you've asked for a specific example using Moose and Perl, I thought I'd provide one. In this following example, we're going have a class named 'Hacker'. The class (like a blueprint) describes what hackers are (their attributes) and what they can do (their methods): package Hacker; # Perl 5 spells 'class' as 'package'use Moose; # Also enables strict and warnings;# Attributes in Moose are declared with 'has'. So a hacker# 'has' a given_name, a surname, a login name (which they can't change)# and a list of languages they know.has 'given_name' => (is => 'rw', isa => 'Str');has 'surname' => (is => 'rw', isa => 'Str');has 'login' => (is => 'ro', isa => 'Str');has 'languages' => (is => 'rw', isa => 'ArrayRef[Str]');# Methods are what a hacker can *do*, and are declared in basic Moose# with subroutine declarations.# As a simple method, hackers can return their full name when asked.sub full_name { my ($self) = @_; # $self is my specific hacker. # Attributes in Moose are automatically given 'accessor' methods, so # it's easy to query what they are for a specific ($self) hacker. return join(" ", $self->given_name, $self->surname);}# Hackers can also say hello.sub say_hello { my ($self) = @_; print "Hello, my name is ", $self->full_name, "\n"; return;}# Hackers can say which languages they like best.sub praise_languages { my ($self) = @_; my $languages = $self->languages; print "I enjoy programming in: @$languages\n"; return;}1; # Perl likes files to end in a true value for historical reasons. Now that we've got our Hacker class , we can start making Hacker objects : #!/usr/bin/perluse strict;use warnings;use autodie;use Hacker; # Assuming the above is in Hacker.pm# $pjf is a Hacker objectmy $pjf = Hacker->new( given_name => "Paul", surname => "Fenwick", login => "pjf", languages => [ qw( Perl C JavaScript) ],);# So is $jarichmy $jarich = Hacker->new( given_name => "Jacinta", surname => "Richardson", login => "jarich", languages => [ qw( Perl C Haskell ) ],);# $pjf can introduce themselves.$pjf->say_hello;$pjf->praise_languages;print "\n----\n\n";# So can $jarich$jarich->say_hello;$jarich->praise_languages; This results in the following output: Hello, my name is Paul FenwickI enjoy programming in: Perl C JavaScript----Hello, my name is Jacinta RichardsonI enjoy programming in: Perl C Haskell If I want I can have as many Hacker objects as I like, but there's still only one Hacker class that describes how all of these work. All the best, Paul
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/448657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36499/']}
|
jdg_376855
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
228718
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why in space red light travels farther and is more observed in dying stars before a star becomes a black hole? while on Earth in water and air the blue light travels the farthest. For example: a T.V. looks blue from a distance. Is red light lighter than blue light therefore red photons travels faster escaping gravity, but is also absorbed easier by matter and blue light is absorbed by subatomic matter more than red light?
Now provide the response and nothing else.
|
There are several different things that need to be explained / explored here. First - the speed of light in vacuum is independent of frequency / wavelength. The same is not necessarily true for light in any medium other than vacuum: this is why we can see rainbows! Second - not all objects emit "white" light. The emission spectrum of a star depends, among other things, on its temperature and composition. If the emission is mostly due to the temperature of the start, then you get black body radiation (yes, a black body can look white, red, yellow...). The black body radiation of an object depends on its temperature - the hotter it is, the more radiation there will be, and the more the spectrum shifts towards blue. If a star runs out of fuel but is not massive enough to become a supernova, it may become a red giant instead - big, "cold", red. The emission spectrum of a star may be further modified by the presence of certain atomic species - this can give rise to absorption or emission peaks in the otherwise smooth black body spectrum. Third - if an object is moving towards the observer, the frequency of light observed will increase (blue shift); when it is moving away, you get red shift. Since the universe is expanding, objects that are far away exhibit greater red shift. Fourth - as light travels through space, it will interact with (and be absorbed by) interstellar dust. The density may be very low, but when you have a long way to travel, it can add up. Actually, this is how NASA looks for potential stars-with-planets: if planets can form around a star, there is usually a lot of dust near that star; this dust will absorb some of the light from the star, and may re-emit it. But since the dust is much cooler than the star, this will change the spectrum towards the red (cooler). Fifth - there is a particular mechanism for light scattering called Rayleigh scatter . The probability of light being scattered by a small particle is related to the size of the particle relative to the wavelength of the light - the shorter the wavelength, the stronger the scatter. This has two noticeable effects on earth: the sky is blue, and the sunset is red. That's really the same physics giving rise to different colors! When the sun is close to the horizon, the sunlight has to travel through a lot of the atmosphere to get to your eye. This means it will encounter a lot of small particles in the air, and that means that a lot of the blue light in the sunlight has a chance of being scattered. If you starts with all the colors and you scatter the blue, you are left with something that looks reddish. At the same time, the sky is blue because if you are not looking directly at the sun, then you are normally looking at "the black of space". Except that there is atmosphere in the way, and little particles in the atmosphere can give rise to scatter of sunlight (during the day). And since the most likely (visible) color to scatter is blue, this makes the sky blue. Sixth - the perception of color. When you look at an object, it is really hard to know what color it is. Instead, you tend to judge the color based on what is nearby. When you are indoors, and the incandescent (tungsten) light is on, a piece of white paper will look "white" to you. If you use a different light source (say the sun light), the paper will still look white. But in fact it will be a very different color! Digital cameras can really show you this - they use something called "White Balance" to try to correct for the color of the light, but if you don't do that, an indoor photo will look very yellow. In the "olden days" of color film, you would use a special "tungsten filter" on your camera to correct for the yellow color; otherwise your photos would look horrible. And this explains your TV. If you are close to a TV, it looks bright, and white is white. As you walk further away, you see other things that are more yellow (because they are illuminated with incandescent light). By comparison, the "white" from the TV will look blue. I wrote an earlier answer about the "color" of the moon; in that, I created a simple grayscale image that shows how our perception of one shade depends on what else we see. While it was not designed to demonstrate the "white is blue" thing, it might be instructive: It is reasonable to say that the little rectangle on the left looks white, while it looks gray on the right; and whether you consider it gray or white in the middle depends on your screen brightness, probably. But they are in fact all the exact same shade of gray.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/228718', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/148704/']}
|
jdg_376856
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
349410
|
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If you have told us (or privately thought) Documentation isn't working: You are correct. It isn't. Yet. Since early on in the private beta of Documentation, we’ve used a simple, rigid structure: Tags => Topics => Examples + optional sections At the time, users wondered if this was the right structure. Since Documentation is a grand experiment, we figured we’d wait to see how the structure gets used and adjust as needed. But rather than being a step in the right direction, tags and topics were just getting in the way. We didn’t address the problem partially because we focused on other broken features and partially because we hoped the current system would pan out. At long last, we’ve got the message: fundamentally the structure we provided isn’t working and the artifacts being created don't serve users particularly well. This isn’t something we can address by tweaking a few features; it’s the foundation of the entire product. Let’s work together to find a way of organizing and creating Documentation that’s better than what we have now and, perhaps, revolutionizes the entire genre of documentation! If you want to cut to the chase, read down to the “What happens next section?” below. How we got here I’m sure you’ve heard the ( misquoted ) saying “If you build it, they will come.” As many people over the years have pointed out, it ain’t necessarily so. Plenty of creative people have built stuff that never gets used by anyone not related to the creator. Typically, the moral is that if you want people to use your creation, you gotta build it and sell it . Ultimately people need to have some use for the thing you built or it’ll go unused. Documentation isn’t a Field of Dreams story. There was no mysterious voice telling us to build it. Instead, after a good deal of success in community-driven Q&A, we scouted out other ways for our community improve upon existing tooling so that developers everywhere can benefit. Having a product that works and that millions of developers depend on every day has one significant drawback: it’s tricky to make structural changes. As Shog9 wrote : So a few years back, some folks within the company decided to push in a different direction: if we can't experiment on the main Q&A system, let's build new systems, and test ideas that way. Let's throw a whole bunch of pasta against the wall & see what sticks. Will it be mentoring? Videos? Teams? Stories? International sites? Documentation? Dancing ? Kevin Montrose spent a good deal of time looking at what's missing in existing programmer documentation. He proposed the main thing developers struggle with is finding practical and immediately-useful examples. After quite a bit of internal debate, he pitched the idea on Meta . Folks seemed excited about the concept, so we built a system for people to contribute and maintain example-first documentation, and opened it to a private beta. After months of intense work and user testing, we finally were ready to launch. So we built it and my personal fear was that nobody would come. I need not have worried. In the first ten days, nineteen thousand people tried out Stack Overflow Documentation (beta). Some people got the concept and others didn’t. We fixed lots of (in retrospect) obvious problems and created new ones for ourselves. Despite the predictable drop in participation over the next few months, it felt like we were on the right track. After some initial hiccups, people were able to contribute new content and get it reviewed. Spot checking approved changes showed they measurably improved the quality of topics. Most of the topics were not to our community’s exacting standards, but we could see how they might get there. If this were a movie, the soundtrack would get ominous and there would be gathering clouds in the background. It’s as if we had a cornfield, purchased a bunch of tools and building materials, and invited all comers to make something. At first the sounds of labor are comforting as it means things are getting done. But what, exactly? And can it reasonably be called Documentation? And did we provide the right tools? We read feedback on Meta and conducted usability tests to find out. The results were . . . inconsistent. You see each tag is its own silo and it’s not easy to navigate from, say, Ruby to Ruby on Rails. And within each tag, topics are their own silos. So people who use tags or topics that are well written and informative will have a different impression than those who have mostly seen examples with glaring problems. The plan was that people would start seeing Documentation via Google searches and propose changes to fix problems. While we are starting to see that happen , it doesn’t seem like it will do enough to produce the exceptional artifacts we’d like to see. One concern we keep hearing is that the structure of Documentation isn’t working. Some users (both on meta and in interviews) told us our structure was too sterile and generic. Others told us it was too rigid and specific. Nobody's quite sure if we want API-level documentation or tutorials or cookbooks or something else entirely. The optional Syntax and Parameter sections made sense to some and were head-scratchers to others. By attempting to serve all sorts of technologies and all types of documentation and all levels of users, we managed to serve none particularly well. What happens next? So we are going to try something different. Instead of giving users a blank slate and a fist full of chalk, we’re going to sketch out (with your input) some documentation blueprints. Initially, we’ll prototype what a page of Documentation could potentially look like for just one technology. We’ll test it with Stack Overflow users, our employees, and outside technical writers to get critical feedback. Once we have one artifact that meets our expectations, we’ll see if we can extend the structure to a few more technologies. By starting from the ground up, we hope to find a rich and flexible way to structure Documentation . If this sounds a little vague and hand-wavy, it’s meant to be. It won’t help to fall into the same trap of completely creating the product and then soliciting feedback. Instead of developing incrementally, we’re shifting to a true iterative approach. To quote Jeff Patton’s Don’t Know What I Want, But I Know How to Get It : By incremental development, I mean to incrementally add software [over] time. Each increment adds more software—sorta like adding bricks to a wall. After lots of increments, you’ve got a big wall. By iterative development I mean that we build something, then evaluate whether it’ll work for us, then we make changes to it. [We're] building expecting to change it. We never expected it to be right. If it was, it’s a happy accident. Because we don’t expect it to be right, we often build the least we have to to then validate whether it was the right thing to build. I’ve used the two figures above for a number of years now to help illustrate the concept. Artists work iteratively. They often create sketches, decide to create a painting, create an under-painting showing colors and form, then eventually begin finishing the painting. In our first draft we’ll create some Internet pages documenting parts of Transact-SQL . There are several reasons for this: It’s a technology many of us in the company use on a daily basis and many others are interested in learning. This will give us the widest possible internal audience to test our artifact on. We identified shortcomings in existing T-SQL documentation (both official and from third parties). The Stack Exchange Data Explorer (SEDE) provides an obvious way to demonstrate T-SQL concepts. We also have a wonderful SEDE tutorial which was written by a community member for inspiration. After some debate we figured it didn't matter too much what we picked as long as we picked something . Part of the exercise is to figure out what sort of structure works for this particular technology. If we do it right, there’s a good chance the structure won’t work so well for, say, JavaScript, .NET, and Git. But hopefully there will be commonalities and broad categories of documentation we can extract and build on. Should I keep contributing to the Documentation beta? Yes, please. Since the next phase of development addresses structure, concentrate on writing effective examples. Even with the broken structure and missing elements, people are starting to take notice . One consistently positive thing we’ve heard about the existing system is that people like the focus on examples. It’s difficult to imagine a scenario where Documentation won’t emphasize examples. When we have a better way to arrange content, you’ll be able to move things around. How can I help? We’d like to continue hearing from you about what works and what doesn’t for documentation in general and our beta product in particular. I’m not sure we’ve properly expressed our appreciation for months of feedback in private beta, dozens of users we’ve interviewed, and 1500+ meta questions . It’s been immensely valuable, but also overwhelming. So we’re going to start asking for specific feedback that can help us with what we are working on at the moment. To start, please take a look at this companion meta question: What T-SQL documentation has helped you? Documentation is very much in beta and it could yet fail. But I gotta say, it’s exciting to be working on something new that has the potential to change how the next generation programmers learn their craft. We don’t know exactly where we are going or what we will find when we get there. No matter what, we’re going to learn something . Come join us on the adventure!
Now provide the response and nothing else.
|
I'm glad to see this new approach. Thank you. I'm also glad to see the first phase of understanding your users (the companion question). Documentation doesn't exist in a vacuum; it exists because there are real people with real needs, and also prior work. Regardless of subject, there are a few types of documentation, and when it comes to structure one size does not fit all. For example, there's tutorial-style documentation (like that SEDE tutorial), which introduces concepts as needed (just enough, not too detailed) while walking the reader through a progression of examples, which might have iterative cycles. Another type of documentation is the complete, documented example -- something that the reader can download and run himself, that has good comments and then some doc wrapped around it. (I don't necessarily mean one big <code> block; sometimes it's better to go method by method, for example.) Reference implementations are an advanced form of the complete, documented example. Then there's conceptual documentation , where you explain in more detail what's going on with the different kinds of JOIN, for instance. And -- perhaps less relevant here, but I'll include it anyway -- there's task-oriented documentation , where you provide step-by-step instructions for how to do something procedural like configure Kerberos. What distinguishes task documentation from documented examples is that there should be fewer decision points -- getting that DB web front end up and running might require 37 steps but they're pretty much always the same 37 steps. That's different from doc about how to optimize a query, where you might be teaching a skill instead of providing instructions . There's also reference documentation -- think API reference or language spec here -- where the focus is on being complete but comparatively terse, but where examples are also valuable. (This is probably not going to be where our best bang for the buck is.) My point in saying all that is: these different types of doc require different enabling structures. This doesn't need to be a ton of work, but it's something to think about. We probably want something more than "here's a textbox" and less than "here's the schema for our fancy XML representation" -- maybe we just need some templates? Maybe the question about what T-SQL doc has helped people will evoke answers that touch on structure and organization. One general point: being able to organize content is important. (Even better if it can be sketched out early on, before all the pieces exist!) In Documentation 1.0 examples on a topic were ordered by votes; there's no way to do a progression that way. A tutorial can involve several examples or example fragments, and they need to be orderable. It also won't make much sense for them to be evaluated (e.g. by reviewers) in isolation, away from their surrounding context. That's great for an initial code review, but you also need to be able to answer the question "is this a good example of that thing we just explained ?".
|
{}
|
{'log_upvote_score': 7, 'links': ['https://meta.stackoverflow.com/questions/349410', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/1438/']}
|
jdg_376857
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11623299
|
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 does Recalculate Layout Paint mean in chrome developer tool TimeLine records? and how to improve the page performance by reduce the page Recalculate,Layout and Paint's count? can give some suggestion?thanks
Now provide the response and nothing else.
|
Basically, they're your browser figuring out how to draw the changes that you made to the page. Don't worry about getting rid of them -- if you did that, your site would be static.However... ...if you want to do something that IS useful for performance, which does have to do with reflows and repaints, then batch your changes together. Lets say that you got a job at Twitter.And your job is to write the next version of the window that adds each twitter post to the screen. If a user gets 250 new tweets in their timeline, and you add each one in a loop, one after the other, the browser is going to slow way down, because every time you add one, it will have to reflow (move things around to make space for the thing you added) and repaint (style everything that was affected by the addition). A better way of doing it would be to build the list of new tweets together off-DOM (ie: with elements that aren't actually on the page right now), and then add them all at once.This cuts down on the number of times that a browser has to figure out where everything needs to go. @Fabricio -- Micro-optimizing might not be great, but appending hundreds of browser elements in a loop, versus putting all of them in at the same time can make a big difference.Just ask the Twitter guys, who weren't bothering to cache their jQuery objects.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11623299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572504/']}
|
jdg_376858
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
378495
|
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 want show that this improper integral convergence: $$\int_{0}^{+\infty}\frac{\sin x}{x+\sin x}dx$$ please help me.
Now provide the response and nothing else.
|
For $0\lt x\le\pi$, $0\le\dfrac{\sin(x)}{x+\sin(x)}=\dfrac{\sin(x)/x}{1+\sin(x)/x}\le\dfrac12$, so$$0\le\int_0^{\pi}\frac{\sin(x)}{x+\sin(x)}\,\mathrm{d}x\le\frac\pi2$$ Integrate by parts to get$$\begin{align}\int_\pi^\infty\frac{\sin(x)}{x+\sin(x)}\,\mathrm{d}x&=\left.-\frac{\cos(x)}{x+\sin(x)}\right]_\pi^\infty-\int_\pi^\infty\frac{\cos(x)(1+\cos(x))}{(x+\sin(x))^2}\,\mathrm{d}x\\[6pt]&=-\frac1\pi-\int_\pi^\infty\frac{\cos(x)(1+\cos(x))}{(x+\sin(x))^2}\,\mathrm{d}x\end{align}$$and the last integral converges since the absolute value of the numerator of the integrand is bounded by $2$ and the denominator is greater than $(x-1)^2$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/378495', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58772/']}
|
jdg_376859
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2573058
|
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:
Show that $$\int_{0}^{2e}{\ln{(x^2)}\ln{(4e-x)}\over \sqrt{x(4e-x)}} dx=\pi(1-\zeta(2)).$$ My try: let$u=\ln{x}$ then $x\mathrm du=\mathrm dx$ and$$2\int{ue^{u/2}\over \sqrt{4e-e^u}}\mathrm du$$What next?
Now provide the response and nothing else.
|
By letting $x=2e(1-\cos(t))$, we have that$$\begin{align}I:=\int_{0}^{2e}\frac{\ln(x^2)\ln(4e-x)}{\sqrt{x(4e-x)}}dx=2\int_{0}^{\pi/2}\ln(2e(1-\cos(t)))\ln(2e(1+\cos(t)))dt.\end{align}$$Now by using the Fourier series given by robjohn in this answer , we have that$$\ln(2e(1+\cos(t)))=\ln(2)+1+\ln(1+\cos(t))=1-2\sum_{k=1}^\infty(-1)^{k}\frac{\cos(kt)}{k}$$and $$\ln(2e(1-\cos(t)))=\ln(2)+1+\ln(1-\cos(t))=1-2\sum_{k=1}^\infty\frac{\cos(kt)}{k}.$$Hence, after taking the product and the integration over $(0,\pi/2]$, we get $$I=2\cdot\frac{\pi}{2}-8\cdot\frac{\pi}{4}\sum_{k=1}^\infty\frac{(-1)^k}{k^2}=\pi-2\pi\cdot\frac{\pi^2}{12}=\pi(1-\zeta(2)).$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2573058', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/343408/']}
|
jdg_376860
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23667208
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
@media screen and (max-width: calc(2000px-1px)) { .col { width: 200px; }} The value after subtraction should be 1999px , however it does not seem to be working. If I manually change it to 1999px it works fine, so I know it's not a problem with my CSS. Is calc not supported within media queries, or am I doing something wrong?
Now provide the response and nothing else.
|
ANSWER EDITED AGAIN 21.03.2022: In the current version of the spec, using calc (or var) in media queries is NOT supported by the spec (as TylerH pointed out below). Properties sometimes accept complex values, e.g., calculations that involve several other values. Media features * only accept single values: one keyword, one number, etc. * Media features include (max-width: ...) (or (... < width < ...) ). Old specs back to 2012 also explicitly mention no calc . The OP question would definitely have been broken because calc needs whitespace between operators calc(2000px - 1px) , but even with whitespace you shouldn't expect or trust it to work reliably. Browsers that support calc are not actually following the spec. ANSWER WAS EDITED 13.02.2018: Using calc in media queries is supported by the spec, but support was only implemented by browsers recently (February 2018). Currently, calc in media queries is supported by Safari Technology Preview 49+ , Chrome 66+ , and Firefox 59+ . See MDN's calc() page for the most up-to-date information.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23667208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3525422/']}
|
jdg_376861
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
729475
|
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:
EDIT: equivalent formulation by Hurkyl in comments: if $n$ is odd and $p^\nu \parallel n$ and $n > 2k,$ then$$ p^{(\nu + 2 + 2 k - n)} \; | \; \sum_j \left( \begin{array}{c} n \\ 2j \end{array} \right) \left( \begin{array}{c} j \\ k \end{array} \right), $$where the sum should be $k \leq j \leq (n-1)/2.$ Evidently one can expand this sum in some useful way...Hope I got this all arranged correctly. For $n-2k=1,$ the binomial coefficient sum is just $n$ itself. Hurkyl already did $n-2k=3,$ the sum is $n(n+1)(n-1)/6,$ so it works, and you only reach equality if the prime under consideration is $3.$ After an initial bunch of errors, I did $n-2k=5,$ the sum is $n(n+1)(n-1)(n+3)(n-3)/120,$ and it also works. This need not be an integer if $n$ is even but not divisible by $8.$ However, I am not at all worried about $n$ even for this problem. ORIGINAL: Let me post this and then look at related questions. I do suspect that this is all known. If everything I expect is actually true, this gives an answer to Divisors of Pell Equation Solutions which seems to have just been made up as convenient for a contest training problem. Anyway, take the sequence of polynomials in one variable $$ 1, \; x, \; 2 x^2 - 1, \; 4 x^3 - 3 x, \; 8 x^4 - 8 x^2 + 1, \; 16 x^5 - 20 x^3 + 5 x,$$$$ 32 x^6 - 48 x^4 + 18 x^2 - 1, \; 64 x^7 - 112 x^5 + 56 x^3 - 7 x, $$$$128 x^8 - 256 x^6 + 160 x^4 - 32 x^2 + 1, \; 256 x^9 - 576 x^7 + 432 x^5 - 120 x^3 + 9 x, $$$$ 512 x^{10} - 1280 x^8 + 1120 x^6 - 400 x^4 + 50 x^2 - 1, $$$$ 1024 x^{11} - 2816 x^9 + 2816 x^7 - 1232 x^5 + 220 x^3 - 11 x, $$$$ 2048 x^{12} - 6144 x^{10} + 6912 x^8 - 3584 x^6 + 840 x^4 - 72 x^2 + 1,$$ $$ 4096 x^{13} - 13312 x^{11} + 16640 x^9 - 9984 x^7 + 2912 x^5 - 364 x^3 + 13 x, $$$$ 8192 x^{14} - 28672 x^{12} + 39424 x^{10} - 26880 x^8 + 9408 x^6 - 1568 x^4 + 98 x^2 - 1,$$ $$ 16384 x^{15} - 61440 x^{13} + 92160 x^{11} - 70400 x^9 + 28800 x^7 - 6048 x^5 + 560 x^3 - 15 x, $$$$ 32768 x^{16} - 131072 x^{14} + 212992 x^{12} - 180224 x^{10} + 84480 x^8 - 21504 x^6 + 2688 x^4 - 128 x^2 + 1, $$ $$ 65536 x^{17} - 278528 x^{15} + 487424 x^{13} - 452608 x^{11} + 239360 x^9 - 71808 x^7 + 11424 x^5 - 816 x^3 + 17 x, \ldots $$If we call these $f_n,$ we have $f_0 = 1, f_1 = x, f_2 = 2 x^2 - 1,$ and$$ f_{n+2} = 2 x f_{n+1} - f_n. $$It would not be at all surprising if these had a name. Maybe that is why people are always asking for names of things on MSE, so that they can look up the names online... Anyway, if $n$ is odd, then the final term is $\pm n x.$ Conjectures are like this: for an odd prime $p,$ if $p^2 | n,$ then $p$ divides the cubic coefficient $a_3.$ If $p^3| n,$ then $p^2$ divides $a_3.$ If $p^4| n,$ then $p^3$ divides $a_3$ and $p$ divides $a_5.$ If $p^5| n,$ then $p^4$ divides $a_3$ and $p^2$ divides $a_5.$ If $p^6| n,$ then $p^5$ divides $a_3$ and $p^3$ divides $a_5$ and $p$ divides $a_7.$ Let's see; Question: Anyone know anything about this?
Now provide the response and nothing else.
|
Nate's hint does the trick. Let $G$ be an abelian connected Lie group with Lie algebra $\mathfrak g$. The exponential map $\exp:\mathfrak g\to G$ is actually a homomorphism of abelian groups. The image is open in $G$, so $\exp$ is surjective because $G$ is connected. The fact that $\mathfrak g\to G$ is a local homeomorphism means that $\ker(\exp)$ is a discrete subgroup of $\mathfrak g$. It is known that such groups are of the form $\Lambda=\mathbf Z x_1+\cdots + \mathbf Z x_n$, for $x_1,\dots,x_n\in \mathfrak g$ linearly independent over $\mathbf R$. We can extend $x_1,\dots,x_n$ to a basis of $\mathfrak g$ to see that $$ G \simeq (S^1)^r \times \mathbf R^s$$In other words, every connected abelian Lie group is a product of affine space and a torus . For example, $\mathbf C_{\ne 0} = \mathbf C^\times$ is the product $\mathbf R\times S^1$, via $(r,\theta)\mapsto r e^{i\theta}$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/729475', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10400/']}
|
jdg_376862
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
82746
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two problems with ladder operators . The first is that I feel they should somehow result in measurable things. The asymmetry of applying the plus operator versus the minus operator is very strange to me. Second, I don't understand why applying the raising operator and then the lowering operator is different from applying the lowering operator and then the raising operator. The two are explained in terms of moving up and down energy levels, so shouldn't going up then down, or down then up, be the same operation? What is asymmetric about harmonic oscillators that causes this asymmetry?
Now provide the response and nothing else.
|
The reason that creation and destruction operators don't commute is that, on top of 'moving a state up and down energy levels', they multiply it by a number in the process, and this number depends on where you are in the ladder. More specifically, $$\begin{cases}\hat{a}|n\rangle&=\sqrt{n}|n-1\rangle,\text{ while}\\\hat{a}^\dagger|n\rangle&=\sqrt{n+1}|n+1\rangle.\end{cases}$$ Thus, if you act on a number state $|m\rangle$ with a creation operator first, you will get the $\sqrt{n+1}$ factor with $m=n$, but the $\sqrt n$ factor with $n=m+1$, so you will get $\hat a \hat a^\dagger|m\rangle=(m+1)|m\rangle$. Conversely, if you act with the destruction operator first, you will get a factor with $\sqrt n$ at $n=m$, and then a factor of $\sqrt{n+1}$ at $n=m-1$, so the result will be $\hat a^\dagger \hat a|m\rangle=m|m\rangle$. Ultimately, though, there is a more fundamental reason why creation and annihilation operators can't commute, and it is the fact that energy levels are bounded from below: that is, there are no $|n\rangle$ with $n<0$. To see why this is the case, consider the creation and annihilation operators without the prefactors I just talked about, to get$$\begin{cases}\hat{E}\,|n\rangle&=|n-1\rangle\text{ and}\\\hat{E}^\dagger|n\rangle&=|n+1\rangle.\end{cases}$$ The argument above no longer holds, and both routes will return the same coefficient on $|m\rangle$ after applying $\hat E$ and $\hat E^\dagger$ in both orders. The problem, however, is what happens to the ground state? The formulas above are mostly fine, but they do not specify what $\hat E|0\rangle$ should be, and there is no $|-1\rangle$ state we can put it into. However, if we want both operators to be hermitian conjugates, then we have really no room to play with, because the identity$$\langle n|\hat E|0\rangle^\ast=\langle 0|\hat E^\dagger|n\rangle=\langle 0|n+1\rangle=0$$implies that $\hat E|0\rangle$ has zero component along $|n\rangle$ for all $n\geq0$; since that is a complete set, it implies that $\hat E|0\rangle=0$. Finally, then, if you compute $\hat E\hat E^\dagger |0\rangle$ as above, you will get $|1\rangle$ as normal, but $\hat E^\dagger \hat E|0\rangle$ returns 0, which is different, and the operators don't commute:$$\hat E\hat E^\dagger =1\text{ but }\hat E^\dagger \hat E=1-|0\rangle\langle 0|.$$ The only way around this is to allow for an infinite ladder of negative-energy eigenstates, which are completely unphysical, but do allow for commuting ladder operators. While these states have indeed appeared in the literature they are unwieldy to use as they defy all intuition and they have not caught on. So, to answer your final question: the asymmetry in the harmonic oscillator that ultimately causes this behaviour is the fact that the ladder of energy eigenstates is bounded from below but not from above, which makes going up and down the ladder not completely equivalent.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/82746', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
|
jdg_376863
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4866043
|
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 a mixed C/C++ project, we need to make a call from C to a C++ function. The function to be called is overloaded as three separate functions, but we can ignore that from the C-side, we just pick the one most suitable and stick to that one. There's two ways to do this: (1) write a small C++ wrapper with a extern "C" function that forwards the call to the chosen overloaded function, or (2) the hackish way to just declare the one function we want to call from C as extern "C". The question is, is there any disadvantages (apart from nightmares and bad karma) to go for the second variant? In other words, given three overloaded function, where one is declared as exern "C", should we expect trouble with the C++ side, or is this well defined according to the standard?
Now provide the response and nothing else.
|
I believe the language in the standard is specifically written to allow exactly one function with "C" linkage, and an arbitrary number of other functions with "C++" linkage that overload the same name (§[dcl.link]/6): At most one function with a particular name can have C language linkage. Two declarations for a function with C language linkage with the same function name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same function. Two declarations for an object with C language linkage with the same name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same object. The standard shows the following example: complex sqrt(complex); // C + + linkage by defaultextern "C" { double sqrt(double); // C linkage}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4866043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270280/']}
|
jdg_376864
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4055022
|
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 mark a test as an expected failure in JUnit 4? In this case I want to continue to run this test until something is patched upstream. Ignoring the test goes a little too far, as then I might forget about it. I may be able to add an @expected annotation and catch the exception thrown by assertThat , but that also seems to lie about the expected behavior. Here's what my current test looks like: @Testpublic void unmarshalledDocumentHasExpectedValue() { doc = unmarshaller.unmarshal(getResourceAsStream("mydoc.xml")); final ST title = doc.getTitle(); assertThat(doc.getTitle().toStringContent(), equalTo("Expected"));} That assert should succeed, but because of an upstream bug it doesn't. Yet, that test is correct; it should succeed. Virtually all the alternatives that I've found are misleading. Right now I think @Ignore("This test should pass once fixed upstream") is my best bet, but I still have to remember to come back to it. I'd prefer that the test run. In Python I can use the expectedFailure decorator: class ExpectedFailureTestCase(unittest.TestCase): @unittest.expectedFailure def test_fail(self): self.assertEqual(1, 0, "broken") With Qt's QTestLib in C++, you can use QEXPECT_FAIL : QEXPECT_FAIL("", "Will be fixed next version", Continue);QCOMPARE(i, 42); In both cases above, the unit test runs which is what I'm hoping to have happen. Am I missing something in JUnit?
Now provide the response and nothing else.
|
I'm not quite getting the specifics of your scenario, but here's how I generally test for expected failure: The slick new way: @Test(expected=NullPointerException.class)public void expectedFailure() { Object o = null; o.toString();} for older versions of JUnit: public void testExpectedFailure() { try { Object o = null; o.toString(); fail("shouldn't get here"); } catch (NullPointerException e) { // expected }} If you have a bunch of things that you want to ensure throw an exception, you may also want to use this second technique inside a loop rather than creating a separate test method for each case. If you were just to loop through a bunch of cases in a single method using expected , the first one to throw an exception would end the test, and the subsequent cases wouldn't get checked.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4055022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103842/']}
|
jdg_376865
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29886852
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been learning Haskell from Learn You A Haskell and just came across the following statement : Doing (+) <$> [1,2] <*> [4,5,6] results in a non-deterministic computation x + y where x takes on every value from [1,2] and y takes on every value from [4,5,6] . I don't think I understand what is non-deterministic about this. Is it just that the order of the results or the order of computation is not guaranteed to be the same every time?
Now provide the response and nothing else.
|
In this context, what's nondeterministic isn't the computation that Haskell is performing , but instead the computation that is being represented . When viewed as a monad (or applicative functor), lists represent nondeterministic computation: just as a Maybe a is a computation of an a that might have failed, or an IO a is computation of an a that did some I/O, a [a] is a nondeterministic computation of an a . Thus the list [1,2] , under this interpretation, represents a computation that nondeterministically returns 1 or 2 , and similarly for [4,5,6] . Or again, by way of analogy: computing Nothing in Haskell succeeds, even though that value represents failure; computing [1,2] in Haskell is deterministic (and pretty boring), but that value encodes a form of nondeterminism. Thus, (+) <$> [1,2] <*> [4,5,6] computes x + y nondeterministically. Again, that's not what's written in the code – that's what the code represents . The code itself deterministically computes the representation of a nondeterministic computation! The way this works is that <$> and <*> functions lift computations inside an applicative functor, so that snippet says to compute (+) inside the list applicative functor, which means it computes (+) nondeterministically: [1,2] represents a computation that could return either 1 or 2 . Call its result x . [4,5,6] represents a computation that could return any of 4 , 5 , or 6 . Call its result y . Thus, adding the results of those computations together – computing x + y – could evaluate to the sum of any of the possible values for x and y . This is what the quote is saying, just in slightly more and different words :-) In fact, (+) <$> [1,2] <*> [4,5,6] is exactly equivalent to [x + y | x <- [1,2], y <- [4,5,6]] , where the "nondeterminism" is instead x and y each iterating over their respective lists. This is all that's meant by nondeterminism, in the end! As for how you were thinking about understanding this: remember, Haskell code is guaranteed to be deterministic in its results, thanks to Haskell's purely functional nature. The order of computation, however, doesn't affect this, so is left fairly unconstrained, as long as functions don't fail too early (e.g., const () undefined must evaluate to () ). We only get nondeterminism by representing it as an effect; lists are one encoding of this (and IO can be another, for a very different kind of nondeterminism).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29886852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1852230/']}
|
jdg_376866
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1578869
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In a problem of classical mechanics, I encounter the following equation: $$\mu \sin^4 \theta + \cos \theta = 0 \qquad \mu > 0 \qquad \frac{\pi}{2} < \theta < \pi,$$ where $\mu$ is some constant containing things like mass $m$ and angular momentum $L$. I would like to find the roots in $\theta$ for it being in the interval $\left(\frac{\pi}{2},\pi \right)$, which is a condition I know for sure to be true. Mathematica gives me an extremely blown up solution for this equation. Is there any (nice) way to find the roots of this equation by hand?
Now provide the response and nothing else.
|
Let $x=-\cos(\theta)$ so that $$\mu(1-x^2)^2-x=0$$ This polynomial indeed has a single root in the range $[0,1]$ for all positive $\mu$. We can rewrite the above equation as $$\mu=\frac x{(1-x^2)^2}.$$ For small $x$, $x\approx\mu$. For $x$ close to $1$, let $1-\epsilon$, we have $$\mu=\frac{1-\epsilon}{(1-(1-\epsilon)^2)^2}\approx\frac1{4\epsilon^2}.$$ This gives us the approximation $$x=1-\frac1{2\sqrt\mu}.$$ You can refine the root numerically in the range $$[\mu,1-\frac1{2\sqrt\mu}].$$ For a "manual" method, you can plot the relation $\mu=f(x)$ as accurately as possible. Then for a given value of $\mu$, find the corresponding $x$ on the plot and use it for a starting value of Newton's iterations. Update : The $\mu$ curve has a vertical asymptote at $x=1$, which makes it more difficult to handle. We can discard it by considering the function $$\frac\mu{\mu+1}=\frac x{(1-x^2)^2\left(\frac x{(1-x^2)^2}+1\right)}=\frac x{(1-x^2)^2+x}.$$ It turns out that the function is fairly well approximated by $x$ in the range of interest, so that a good initial approximation is simply $$x=\frac\mu{\mu+1} !$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1578869', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/264845/']}
|
jdg_376867
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
841024
|
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:
Showing $A \subset B \iff A\cap B=A$ How would I show this? My proof Assume i. $A \cap B \subset A$ ii.$A \subset A \cap B$ Let $x$ be any element. Assume $x \in A \cap B$. Then $x \in A$ and $ x \in B$. By hypthesis $x \in A \rightarrow x \in B$ Thus $x \in A$ ii. Let $ x \in A$ By hypthesis $x \in A \rightarrow x \in B$ thus $x \in A \cap B$. Part 2 $ A\cap B=A \rightarrow A \subset B$ But I find myself stuck here.
Now provide the response and nothing else.
|
I think there is a cleaner way to write it. We want to prove $A \subset B \iff A \cap B = A$ i) $A \subset B \implies A \cap B = A$ Here, we have to prove a set equality, so we have to prove both inclusions, assuming that $A \subset B$. First, let's prove that $A \cap B \subset A$. Let $x \in A \cap B$. Then $x \in A$ and $x \in B$. Well, $x \in A$, and we have $A \cap B \subset A$. Now, we must get the other inclusion, $A \subset A \cap B$. Let $x \in A$. Since $A \subset B$, we have $x \in B$. But $x \in A$ and $x \in B$ means that $x \in A \cap B$, hence $A \subset A \cap B$. Both inclusions give $A = A \cap B$. ii) $A \cap B = A \implies A \subset B$ Now, forget everything we've done until now. Assume that $A \cap B = A$, and we will prove that $A \subset B$. Let $x \in A$. That means, by hypothesis, that $x \in A \cap B$. So, $x \in B$, also, and we got $A \subset B \qquad\square$. Notice where exactly I used every hypothesis, and the structure of the proof. If you still have any doubts, please say.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/841024', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37244/']}
|
jdg_376868
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
424095
|
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 looking for suitable capacitors for a sound amplifier I have designed.The speaker power should be at least 7 watt (for the sound to be loud enough).(I attach a figure of the design) So, I think I need capacitors which are suitable for these level of power. But, in the datasheets, i don't see any specification for the power capability of the capacitors.. Any idea how can I know I have chosen capacitors with high enough power resum capabilities? Thanks!
Now provide the response and nothing else.
|
Capacitors don't have power ratings because, ideally, they don't dissipate any power. They store energy unlike resistors which consume energy, giving it off as heat. Instead, you need to consider the following: The voltage rating needs to be at least that of the maximum voltage they will see in service. For power regulation and loudspeaker connection electrolytics are suitable. Observe polarity. The impedance of the loudspeaker decoupling capacitor needs to be low in relation to the speaker impedance. You can calculate the impedance at any frequency from the formula \$ Z = \frac {1}{2 \pi f C} \$ where Z is the impedance (ohms), f the frequency (hertz) and C the capacitor value (farads). Choose this for a reasonable bass frequency cut-off point. (Remember that frequencies below this will fall off gradually rather than a sharp cut-off.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/424095', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/81644/']}
|
jdg_376869
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6190482
|
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 got a map that loads.I want to add a marker that gets it's lat and long from text boxes, and I can't fathom it. Nothing happens when I click on the updatemap button. Here's my code so far: $(document).ready(function () { alert("Dom, dom dom dom dom");var map;var marker;function initialize() { var myLatlng = new google.maps.LatLng(40.65, -74); var myOptions = { zoom: 2, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, } var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);}$("#updateMap").click(function(){ var newLatLng = new google.maps.LatLng(lat, lng); marker.setPosition(newLatLng); var lat = parseFloat(document.getElementById('markerLat').value); var lng = parseFloat(document.getElementById('markerLng').value); var newLatLng = new google.maps.LatLng(lat, lng); marker = new google.maps.Marker({ position: newLatLng, map: map, draggable: true });});});// Onload handler to fire off the app.google.maps.event.addDomListener(window, 'load', initialize);});
Now provide the response and nothing else.
|
Update Also, your global map reference is never set to the actual map instance since you shadow it with a local var same name. var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); This should be just map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); You're using lat and lng for the marker position before they're initialized (unless they're globally set somewhere): var newLatLng = new google.maps.LatLng(lat, lng);marker.setPosition(newLatLng); If you want to update the position of the same marker and not create a new one, you should simply be doing this: $("#updateMap").click(function(){ var lat = parseFloat(document.getElementById('markerLat').value); var lng = parseFloat(document.getElementById('markerLng').value); var newLatLng = new google.maps.LatLng(lat, lng); marker.setPosition(newLatLng);});
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6190482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/351170/']}
|
jdg_376870
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5155764
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
can anybody explain to me, how to proceed in following scenario ? receiving documents (MS docs, ODS, PDF) Dublic core metadata extraction via Apache Tika + content extraction via jackrabbit-content-extractors using Jackrabbit to store documents (content) into repository together with their metadata ? retrieving documents + metadata I'm interested in points 3 and 4 ... DETAILS:The application is processing documents interactively (some analysis - language detection, word count etc. + gather as many details possible - Dublin core + parsing the content/events handling) so that it returns results of the processing to the user and then the extracted content and metadata(extracted and custom user metadata) stores into JCR repository Appreciate any helps, thank you
Now provide the response and nothing else.
|
Uploading files is basically the same for JCR 2.0 as it is for JCR 1.0. However, JCR 2.0 adds a few additional built-in property definitions that are useful. The "nt:file" node type is intended to represent a file and has two built-in property definitions in JCR 2.0 (both of which are auto-created by the repository when nodes are created): jcr:created (DATE) jcr:createdBy (STRING) and defines a single child named "jcr:content". This "jcr:content" node can be of any node type, but generally speaking all information pertaining to the content itself is stored on this child node. The de facto standard is to use the "nt:resource" node type, which has these properties defined: jcr:data (BINARY) mandatory jcr:lastModified (DATE) autocreated jcr:lastModifiedBy (STRING) autocreated jcr:mimeType (STRING) protected? jcr:encoding (STRING) protected? Note that "jcr:mimeType" and "jcr:encoding" were added in JCR 2.0. In particular, the purpose of the "jcr:mimeType" property was to do exactly what you're asking for - capture the "type" of the content. However, the "jcr:mimeType" and "jcr:encoding" property definitions can be defined (by the JCR implementation) as protected (meaning the JCR implementation automatically sets them) - if this is the case, you would not be allowed to manually set these properties. I believe that Jackrabbit and ModeShape do not treat these as protected. Here is some code that shows how to upload a file into a JCR 2.0 repository using these built-in node types: // Get an input stream for the file ...File file = ...InputStream stream = new BufferedInputStream(new FileInputStream(file));Node folder = session.getNode("/absolute/path/to/folder/node");Node file = folder.addNode("Article.pdf","nt:file");Node content = file.addNode("jcr:content","nt:resource");Binary binary = session.getValueFactory().createBinary(stream);content.setProperty("jcr:data",binary); And if the JCR implementation does not treat the "jcr:mimeType" property as protected (i.e., Jackrabbit and ModeShape), you'd have to set this property manually: content.setProperty("jcr:mimeType","application/pdf"); Metadata can very easily be stored on the "nt:file" and "jcr:content" nodes, but out-of-the-box the "nt:file" and "nt:resource" node types don't allow for extra properties. So before you can add other properties, you first need to add a mixin (or multiple mixins) that have property definitions for the kinds of properties you want to store. You can even define a mixin that would allow any property. Here is a CND file defining such a mixin: <custom = 'http://example.com/mydomain'>[custom:extensible] mixin- * (undefined) multiple - * (undefined) After registering this node type definition, you can then use this on your nodes: content.addMixin("custom:extensible");content.setProperty("anyProp","some value");content.setProperty("custom:otherProp","some other value"); You could also define and use a mixin that allowed for any Dublin Core element : <dc = 'http://purl.org/dc/elements/1.1/'>[dc:metadata] mixin- dc:contributor (STRING)- dc:coverage (STRING)- dc:creator (STRING)- dc:date (DATE)- dc:description (STRING)- dc:format (STRING)- dc:identifier (STRING)- dc:language (STRING)- dc:publisher (STRING)- dc:relation (STRING)- dc:right (STRING)- dc:source (STRING)- dc:subject (STRING)- dc:title (STRING)- dc:type (STRING) All of these properties are optional, and this mixin doesn't allow for properties of any name or type. I've also not really addressed with this 'dc:metadata' mixin the fact that some of these are already represented with the built-in properties (e.g., "jcr:createBy", "jcr:lastModifiedBy", "jcr:created", "jcr:lastModified", "jcr:mimeType") and that some of them may be more related to content while others more related to the file. You could of course define other mixins that better suit your metadata needs, using inheritance where needed. But be careful using inheritance with mixins - since JCR allows a node to multiple mixins, it's often best to design your mixins to be tightly scoped and facet-oriented (e.g., "ex:taggable", "ex:describable", etc.) and then simply apply the appropriate mixins to a node as needed. (It's even possible, though much more complicated, to define a mixin that allows more children under the "nt:file" nodes, and to store some metadata there.) Mixins are fantastic and give a tremendous amount of flexibility and power to your JCR content. Oh, and when you've created all of the nodes you want, be sure to save the session: session.save();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5155764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306488/']}
|
jdg_376871
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
74472
|
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 must confess a priori that I haven't read the proof of Taniyama-Shimura, and that my familiarity with Langlands is at best tangential. As I understand it Langlands for $n=1$ is class field theory. Not an easy theory, but one that was known for a long time. Langlands for $n=2$ is the Taniyama-Shimura conjecture, proven recently by Andrew Wiles and others (some of whom participate in this forum). Clearly Taniyama-Shimura required new ideas. What special property of the $n=2$ case made the proof of Taniyama-Shimura possible, that doesn't exist for Langlands with $n\geq 3$?
Now provide the response and nothing else.
|
"Langlands for $n = 2$", to the extent that such a notion is defined, is more than just Shimura--Taniyama, and for even Galois representations/Maass forms, it is still very much open. (See here for more on this.) For odd Galois representations of dimension $2$, though, it is completely (or almost completely, depending on exactly what you mean by "Langlands") resolved at this point, with the proof of Serre's conjecture (by Khare, Wintenberger, and Kisin) playing a pivotal role. Much is known for $n > 2$ (see the web-pages of e.g. Michael Harris, Richard Taylor, and Toby Gee). A key point is that it is hard to say anything outside the essentially self-dual case (and this is a condition which is automatic for $n = 2$). A second is that Serre's conjecture is not known in general. If one restricts to the regular (corresponding to weight $k \geq 2$ when $n = 2$), essentially self-dual case (automatic when $n = 2$), then basically everything for $n = 2$ carries over to $n > 2$, with the exception of Serre's conjecture. (See e.g. the recent preprint of Barnet-Lamb--Gee--Geraghty--Taylor.) So really, what is special for $n = 2$ is that Serre's conjecture was able to be resolved.And the reason that this has (so far) been possible only for $n = 2$ is that the proofdepends on certain special facts about $2$-dimensional Galois representations. More specifially: In the particular case of Shimura--Taniyama, the Langlands--Tunnell theorem allowed Wiles to resolve a particular case of Serre's conjecture (for $p = 3$). To then get all the necessary cases of Serre's conjecture, Wiles introduced the $3$-$5$ switch. The general proof of Serre's conjecture uses a massive generalization of the $3$-$5$ switch (along with many other techniques), and although (unlike with Wiles's argument) it doesn't build specifically on Langlands--Tunnell, it does build on a result of Tate which is a special fact about $2$-dimensional representations of $G_{\mathbb Q}$ over a finite field of characteristic $2$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/74472', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17577/']}
|
jdg_376872
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24348184
|
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 function that iterates through all fields of an interface passed as parameter. In order to achieve this is I am using reflection. The issue is that I do not know how to obtain the address of a non-pointer field. Here is an example: type Z struct { Id int}type V struct { Id int F Z}type T struct { Id int F V} The above code represents my test structures. Now here is the actual function which traverses a specified structure and lists details about it: func InspectStruct(o interface{}) { val := reflect.ValueOf(o) if val.Kind() == reflect.Interface && !val.IsNil() { elm := val.Elem() if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr { val = elm } } if val.Kind() == reflect.Ptr { val = val.Elem() } for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) address := "not-addressable" if valueField.Kind() == reflect.Interface && !valueField.IsNil() { elm := valueField.Elem() if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr { valueField = elm } } if valueField.Kind() == reflect.Ptr { valueField = valueField.Elem() } if valueField.CanAddr() { address = fmt.Sprint(valueField.Addr().Pointer()) } fmt.Printf("Field Name: %s,\t Field Value: %v,\t Address: %v\t, Field type: %v\t, Field kind: %v\n", typeField.Name, valueField.Interface(), address, typeField.Type, valueField.Kind()) if valueField.Kind() == reflect.Struct { InspectStruct(valueField.Interface()) } }} And here is the actual test after structure instantiation/initialization: t := new(T)t.Id = 1t.F = *new(V)t.F.Id = 2t.F.F = *new(Z)t.F.F.Id = 3InspectStruct(t) And finally the output of InspectStruct call: Field Name: Id, Field Value: 1, Address: 408125440 , Field type: int , Field kind: intField Name: F, Field Value: {2 {3}}, Address: 408125444 , Field type: main.V , Field kind: structField Name: Id, Field Value: 2, Address: not-addressable , Field type: int , Field kind: intField Name: F, Field Value: {3}, Address: not-addressable , Field type: main.Z , Field kind: structField Name: Id, Field Value: 3, Address: not-addressable , Field type: int , Field kind: int As you can see I am using recursion, so if one of the fields is a struct kind then I call InspectStruct for it. My issue is that though all fields have been initialized for the entire structure "t" hierarchy, I am not able to get the address for any field located at a higher depth than "t". I would really appreciate any help.
Now provide the response and nothing else.
|
Passing reflect.Value instead of interface{} seems to fix the problem, however I don't know why valueField.Interface() doesn't work. Working example : http://play.golang.org/p/nleA2YWMj8 func InspectStructV(val reflect.Value) { if val.Kind() == reflect.Interface && !val.IsNil() { elm := val.Elem() if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr { val = elm } } if val.Kind() == reflect.Ptr { val = val.Elem() } for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) address := "not-addressable" if valueField.Kind() == reflect.Interface && !valueField.IsNil() { elm := valueField.Elem() if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr { valueField = elm } } if valueField.Kind() == reflect.Ptr { valueField = valueField.Elem() } if valueField.CanAddr() { address = fmt.Sprintf("0x%X", valueField.Addr().Pointer()) } fmt.Printf("Field Name: %s,\t Field Value: %v,\t Address: %v\t, Field type: %v\t, Field kind: %v\n", typeField.Name, valueField.Interface(), address, typeField.Type, valueField.Kind()) if valueField.Kind() == reflect.Struct { InspectStructV(valueField) } }}func InspectStruct(v interface{}) { InspectStructV(reflect.ValueOf(v))}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24348184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1483118/']}
|
jdg_376873
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6641836
|
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 XML layout in my android application, using ScrollView: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="fill_parent"><TextView.../><LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1"> <CheckBox ...> <requestFocus></requestFocus> </CheckBox> <CheckBox ..></CheckBox></LinearLayout><ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" ><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"><TextView android:text="Block Type:" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView><RadioGroup android:orientation="horizontal" android:id="@+id/inputType" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/btCall" android:paddingRight="10px" android:text="Call" android:layout_height="wrap_content" android:layout_width="wrap_content" android:checked="true"></RadioButton> <RadioButton android:id="@+id/btSMS" android:paddingRight="10px" android:text="SMS" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton> <RadioButton android:id="@+id/btBoth" android:paddingRight="10px" android:text="Call + SMS" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton></RadioGroup><Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/chooseContactButton" android:text="Choose from contacts..."></Button><TextView android:text="Name:" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView><EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:id="@+id/inputName">d</EditText><TextView android:text="Number:" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView><EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:id="@+id/inputNumber"></EditText><TextView android:text="SMS to send:" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView><EditText android:text="I'm busy right now." android:inputType="textMultiLine" android:layout_width="match_parent" android:layout_height="wrap_content" android:minLines="3" android:enabled="false" android:id="@+id/inputMsg"></EditText></LinearLayout></ScrollView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_gravity="bottom"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/okButton" android:text="Save" android:width="150px" android:visibility="gone"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/updateButton" android:text="Update" android:width="150px" android:visibility="gone"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/removeButton" android:text="Remove" android:width="150px" android:visibility="gone"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cancelButton" android:text="Cancel" android:width="150px"></Button></LinearLayout></LinearLayout> The Views above ScrollView freeze fine & the view scrolls good enough.The problem is that the LinearLayout containing Buttons is thrown off the view. It cannot be seen. Any help is greatly appreciated.Thanks.
Now provide the response and nothing else.
|
On the ScrollView, try changing android:layout_height to "fill_parent" adding android:layout_weight="1" . This should make the ScrollView set its height to the gap between your set of buttons and the other views above it. Also, try not to set the height of the ScrollView to "wrap_content", it doesn't make sense as the whole point of it is to scroll through content (within a fixed height).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6641836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565715/']}
|
jdg_376874
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2044645
|
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 got some free-response text fields and I'm not sure how to scrub them to prevent SQL injection. Any ideas?
Now provide the response and nothing else.
|
Create a parameterized query instead of concatenating the user's input into the query. Here is how to do this in classic asp: http://blog.binarybooyah.com/blog/post/Classic-ASP-data-access-using-parameterized-SQL.aspx It's also important to note that the only way you can be 100% safe from sql injection is to parameterize any sql statement that uses user input, even once it's in the database. Example: Say you take user input via a parameterized query or stored procedure. You will be safe on the insert, however you need to make sure that anything down the road that uses that input also uses a parameter. Directly concatenating user input is a bad idea anywhere, including inside the db.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2044645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335036/']}
|
jdg_376875
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9436776
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using LESSCSS . I'm trying to create a method for opacity: .opacity (@opacity) { opacity: @opacity; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=(@opacity * 100))"; filter: alpha(opacity = (@opacity * 100));} So, If I call it using: h1 { .opacity(.5);} I want it to output: h1 { opacity: .5; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=50)"; filter: alpha(opacity = 50);} But instead, LESS throws the error: Expected '}' on line 30 in file '/Content/styles/style.less.css': [29]: -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=(@opacity * 100))"; [30]: filter: alpha(opacity = (@opacity * 100)); ----^ [31]: } What am I doing wrong?
Now provide the response and nothing else.
|
In dotless, do this. (I would NOT recommend script tags - they are ugly, language specific and not supported by dotless). .opacity (@opacity) { @opacityPercentage: @opacity * 100; opacity: @opacity; -ms-filter: ~"progid:DXImageTransform.Microsoft.Alpha(opacity=(@{opacityPercentage}))"; filter: ~"alpha(opacity = (@{opacityPercentage}))";} in dotless 1.2.3 (when it is released in a couple of weeks, or github head, you should be able to do this... .opacity (@opacity) { @opacityPercentage: @opacity * 100; opacity: @opacity; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=(@opacityPercentage)); filter: alpha(opacity = (@opacityPercentage));} and re: the comment from Mathletics, dotless is not "the worst compiler".. It matches less.js up to 1.1.5, soon to be 1.2.2 and many of the 600 bugs against less.js are fixed in dotless. You may have used dotless over 8 months ago, but things change and bugs are fixed... dotless also has better support for comments and variable scoping.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9436776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/224125/']}
|
jdg_376876
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40987580
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was previously using angular from a CDN, as follows. <script src="//code.angularjs.org/1.4.0/angular.js"></script> Loading the app index from node as follows. app.use(function (req, res) { res.sendFile(__dirname + '/client/index.html');}); However, in hope of trying to bundle everything using something like browserify... I have just npm installed angular, and included the angular from node_modules instead of the CDN as follows. <script src="/node_modules/angular/angular.js"></script> But, now it seems that my angular is not being recognised, as I am getting the following error. Uncaught SyntaxError: Unexpected token < angular.js:1 How can I get my angular app to load, now that I am using the npm verison?
Now provide the response and nothing else.
|
Have a Spring Rest controller SseController.java import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.List;@RestControllerpublic class SSEController { public static final List<SseEmitter> emitters = Collections.synchronizedList( new ArrayList<>()); @RequestMapping(path = "/stream", method = RequestMethod.GET) public SseEmitter stream() throws IOException { SseEmitter emitter = new SseEmitter(); emitters.add(emitter); emitter.onCompletion(() -> emitters.remove(emitter)); return emitter; }} ServiceClass.java public void sendSseEventsToUI(Notification notification) { //your model class List<SseEmitter> sseEmitterListToRemove = new ArrayList<>(); SSEController.emitters.forEach((SseEmitter emitter) -> { try { emitter.send(notification, MediaType.APPLICATION_JSON); } catch (IOException e) { emitter.complete(); sseEmitterListToRemove.add(emitter); e.printStackTrace(); } }); SSEController.emitters.removeAll(sseEmitterListToRemove); } finally in Angular2 component do this notification.component.ts import {Component, OnInit} from '@angular/core';declare let EventSource:any;@Component({ selector: 'notification-cmp', templateUrl: 'notification.component.html' })export class NotificationComponent implements OnInit { connect(): void { let source = new EventSource('http://localhost:8080/stream'); source.addEventListener('message', message => { let n: Notification; //need to have this Notification model class in angular2 n = JSON.parse(message.data); console.log(message.data); }); }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40987580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3534132/']}
|
jdg_376877
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
77086
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm still seeing system administrators using the old rule of thumb that swap should be double the memory, even in servers with 32GB of memory. These systems have relatively expensive disks (shipping with 200GB drives) and allocating 64GB of that to swap seems a bit excessive. I was wondering how much swap do you allocate for your Solaris servers, and why? I saw there were other similar questions, but mostly focused on Linux. For Solaris there is another consideration deciding on your swap space because the /tmp filesystem is usually shared with swap.
Now provide the response and nothing else.
|
The swap = 2 * memory is coming from the old days when during a kernel crash the kernel dumped the memory to the swap device and you were able to check what happened after you rebooted your system. Nowadays for example linux is skipping this at all, and I don't run my system with enabled dump file setup. So, this double the size of the memory to get the swap is not valid anymore, because there is not unusual that you have 16/32/64GB of ram and then you obviously wasting disk space following this old story when the disk was much much bigger then the RAM. So long story short, if you don't want to dump and analyze kernel crashes in production there is no logical reason to keep this principle and just give your system couple of G swap, usually i give 2/4 G, because i want to avoid huge IO load caused by swapping.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/77086', 'https://serverfault.com', 'https://serverfault.com/users/5339/']}
|
jdg_376878
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
112117
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A partially ordered set $(X, \leq)$ is called a lattice if for every pair of elements $x,y \in X$ both the infimum and suprememum of the set $\{x,y\}$ exists. I'm trying to get an intuition for how a partially ordered set can fail to be a lattice. In $\mathbb{R}$, for example, once two elements are selected the completeness of the real numbers guarantees the existence of both the infimum and supremum. Now, if we restrict our attention to a nondegenerate interval $(a,b)$ it is clear that no two points in $(a,b)$ have either a suprememum or infimum in $(a,b)$. Is this the right way to think of a poset that is not a lattice? Is there perhaps a more fundamental example that would yield further clarity?
Now provide the response and nothing else.
|
The set $\{x,y\}$ in which $x$ and $y$ are incomparable is a poset that is not a lattice, since $x$ and $y$ have neither a common lower nor common upper bound. (In fact, this is the simplest such example.) If you want a slightly less silly example, take the collection $\{\emptyset, \{0\}, \{1\}\}$ ordered by inclusion. This is a poset, but not a lattice since $\{0\}$ and $\{1\}$ have no common upper bound.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/112117', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9450/']}
|
jdg_376879
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18202398
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My problem is the following. I start several operations asynchronously, and I want to continue until all of them are finished. Using Boost Asio, the most straightforward way to do this is the following. Suppose tasks is some kind of container of objects that support some asynchronous operation. tasksToGo = tasks.size();for (auto task: tasks) { task.async_do_something([](const boost::system::error_code& ec) { if (ec) { // handle error } else { if (--taslsToGo == 0) { tasksFinished(); } } });} The problem with this solution is that it feels like a workaround. In Boost 1.54 I can do it with futures but I can only wait synchronously, which is only possible from a thread separate from where run() is called. for (auto task: tasks) { futures.push_back(task.async_do_something(boost::asio::use_future));}for (auto future: futures) { future.wait();} This code is much clearer than the previous one, but I need a separate thread which I don't want. I want something that can be used like this: for (auto task: tasks) { futures.push_back(task.async_do_something(boost::asio::use_future));}boost::asio::spawn(ioService, [](boost::asio::yield_context yield){ for (auto future: futures) { future.async_wait(yield); } tasksFinished();} Is there anything that can be used similarly?
Now provide the response and nothing else.
|
As far as I know, there is currently no first-class support for this. However, given the direction of the library, I would be surprised if this functionality was not available in the future. A few papers have been proposed to add support for this type of functionality: N3558 - A Standardized Representation of Asynchronous Operations is particularly interesting. It proposes when_all(futures) and future.next() . If it is implemented, then it would be possible to represent the asynchronous chain as: for (auto task: tasks) { futures.push_back(task.async_do_something(boost::asio::use_future));}when_all(futures).then(&tasksFinished); N3562 - Executors and schedulers introduces executors. Which can be used to provided finer control as to the context in which an async can execute. For Boost.Asio, this would likely require providing some type of executor that defers to the io_service . While these papers are still ongoing, it may be worthwhile to periodically check Boost.Thread's Conformance and Extension page and Boost.Asio's github for early adaptations of these proposals. I had the need for this functionality a year ago with a much earlier version of Boost so worked on my own solution. There are still some rough areas with regards to the semantics, but it may be helpful as a reference material until something official is adopted. Before I provide the code, here is an example application based on your question: #include <iostream>#include <boost/asio.hpp>#include <boost/bind.hpp>#include "async_ops.hpp"void handle_timer(const boost::system::error_code& error, int x){ std::cout << "in handle timer: " << x << " : " << error.message() << std::endl;}void a() { std::cout << "a" << std::endl; }void b() { std::cout << "b" << std::endl; }void c() { std::cout << "c" << std::endl; }int main(){ boost::asio::io_service io_service; boost::asio::deadline_timer timer1(io_service); boost::asio::deadline_timer timer2(io_service); // Create a chain that will continue once 2 handlers have been executed. chain all_expired = when_all(io_service, 2); all_expired.then(&a) // Once 2 handlers finish, run a within io_service. .then(&b) // Once a has finished, run b within io_service. .then(&c); // Once b has finished, run c within io_service. // Set expiration times for timers. timer1.expires_from_now(boost::posix_time::seconds(2)); timer2.expires_from_now(boost::posix_time::seconds(5)); // Asynchrnously wait for the timers, wrapping the handlers with the chain. timer1.async_wait(all_expired.wrap( boost::bind(&handle_timer, boost::asio::placeholders::error, 1))); timer2.async_wait(all_expired.wrap( boost::bind(&handle_timer, boost::asio::placeholders::error, 2))); // Run the io_service. io_service.run();} Which produces the following output: in handle timer: 1 : Successin handle timer: 2 : Successabc And here is async_ops.hpp : #include <vector>#include <boost/asio.hpp>#include <boost/bind.hpp>#include <boost/bind/protect.hpp>#include <boost/enable_shared_from_this.hpp>#include <boost/foreach.hpp>#include <boost/function.hpp>#include <boost/make_shared.hpp>#include <boost/range/iterator_range.hpp>#include <boost/shared_ptr.hpp>#include <boost/thread/locks.hpp>#include <boost/thread/mutex.hpp>#include <boost/type_traits/is_integral.hpp>#include <boost/type_traits/remove_reference.hpp>#include <boost/utility/enable_if.hpp>class chain;namespace detail {/// @brief Chained handler connects two handlers together that will/// be called sequentially.////// @note Type erasure is not performed on Handler1 to allow resolving/// to the correct asio_handler_invoke via ADL.template <typename Handler1> class chained_handler{public: template <typename Handler2> chained_handler(Handler1 handler1, Handler2 handler2) : handler1_(handler1), handler2_(handler2) {} void operator()() { handler1_(); handler2_(); } template <typename Arg1> void operator()(const Arg1& a1) { handler1_(a1); handler2_(); } template <typename Arg1, typename Arg2> void operator()(const Arg1& a1, const Arg2& a2) { handler1_(a1, a2); handler2_(); }//private: Handler1 handler1_; boost::function<void()> handler2_;};/// @brief Hook that allows the sequential_handler to be invoked/// within specific context based on the hander's type.template <typename Function, typename Handler>void asio_handler_invoke( Function function, chained_handler<Handler>* handler){ boost_asio_handler_invoke_helpers::invoke( function, handler->handler1_);}/// @brief No operation.void noop() {}/// @brief io_service_executor is used to wrap handlers, providing a/// deferred posting to an io_service. This allows for chains/// to inherit io_services from other chains.class io_service_executor : public boost::enable_shared_from_this<io_service_executor>{public: /// @brief Constructor. explicit io_service_executor(boost::asio::io_service* io_service) : io_service_(io_service) {} /// @brief Wrap a handler, returning a functor that will post the /// provided handler into the io_service. /// /// @param handler Handler to be wrapped for deferred posting. /// @return Functor that will post handler into io_service. template <typename Handler> boost::function<void()> wrap(Handler handler) { // By binding to the io_service_exectuer's post, the io_service // into which the handler can be posted can be specified at a later // point in time. return boost::bind(&io_service_executor::post<Handler>, shared_from_this(), handler); } /// @brief Set the io_service. void io_service(boost::asio::io_service* io_service) { io_service_ = io_service; } /// @brief Get the io_service. boost::asio::io_service* io_service() { return io_service_; }private: /// @brief Post handler into the io_service. /// /// @param handler The handler to post. template <typename Handler> void post(Handler handler) { io_service_->post(handler); }private: boost::asio::io_service* io_service_;};/// @brief chain_impl is an implementation for a chain. It is responsible/// for lifetime management, tracking posting and wrapped functions,/// as well as determining when run criteria has been satisfied.class chain_impl : public boost::enable_shared_from_this<chain_impl>{public: /// @brief Constructor. chain_impl(boost::shared_ptr<io_service_executor> executor, std::size_t required) : executor_(executor), required_(required) {} /// @brief Destructor will invoke all posted handlers. ~chain_impl() { run(); } /// @brief Post a handler that will be posted into the executor /// after run criteria has been satisfied. template <typename Handler> void post(const Handler& handler) { deferred_handlers_.push_back(executor_->wrap(handler)); } /// @brief Wrap a handler, returning a chained_handler. The returned /// handler will notify the impl when it has been invoked. template <typename Handler> chained_handler<Handler> wrap(const Handler& handler) { return chained_handler<Handler>( handler, // handler1 boost::bind(&chain_impl::complete, shared_from_this())); // handler2 } /// @brief Force run of posted handlers. void run() { boost::unique_lock<boost::mutex> guard(mutex_); run(guard); } /// @brief Get the executor. boost::shared_ptr<io_service_executor> executor() { return executor_; }private: /// @brief Completion handler invoked when a wrapped handler has been /// invoked. void complete() { boost::unique_lock<boost::mutex> guard(mutex_); // Update tracking. if (required_) --required_; // If criteria has not been met, then return early. if (required_) return; // Otherwise, run the handlers. run(guard); } /// @brief Run handlers. void run(boost::unique_lock<boost::mutex>& guard) { // While locked, swap handlers into a temporary. std::vector<boost::function<void()> > handlers; using std::swap; swap(handlers, deferred_handlers_); // Run handlers without mutex. guard.unlock(); BOOST_FOREACH(boost::function<void()>& handler, handlers) handler(); guard.lock(); }private: boost::shared_ptr<io_service_executor> executor_; boost::mutex mutex_; std::size_t required_; std::vector<boost::function<void()> > deferred_handlers_;};/// @brief Functor used to wrap and post handlers or chains between two/// implementations.struct wrap_and_post{ wrap_and_post( boost::shared_ptr<detail::chain_impl> current, boost::shared_ptr<detail::chain_impl> next ) : current_(current), next_(next) {} /// @brief Wrap a handler with next, then post into current. template <typename Handler> void operator()(Handler handler) { // Wrap the handler with the next implementation, then post into the // current. The wrapped handler will keep next alive, and posting into // current will cause next::complete to be invoked when current is ran. current_->post(next_->wrap(handler)); } /// @brief Wrap an entire chain, posting into the current. void operator()(chain chain);private: boost::shared_ptr<detail::chain_impl> current_; boost::shared_ptr<detail::chain_impl> next_;};} // namespace detail/// @brief Used to indicate that the a chain will inherit its service from an/// outer chain.class inherit_service_type {};inherit_service_type inherit_service;/// @brief Chain represents an asynchronous call chain, allowing the overall/// chain to be constructed in a verbose and explicit manner.class chain{public: /// @brief Constructor. /// /// @param io_service The io_service in which the chain will run. explicit chain(boost::asio::io_service& io_service) : impl_(boost::make_shared<detail::chain_impl>( boost::make_shared<detail::io_service_executor>(&io_service), 0)), root_impl_(impl_) {} /// @brief Constructor. The chain will inherit its io_service from an /// outer chain. explicit chain(inherit_service_type) : impl_(boost::make_shared<detail::chain_impl>( boost::make_shared<detail::io_service_executor>( static_cast<boost::asio::io_service*>(NULL)), 0)), root_impl_(impl_) {} /// @brief Force run posted handlers. void run() { root_impl_->run(); } /// @brief Chain link that will complete when the amount of wrapped /// handlers is equal to required. /// /// @param required The amount of handlers required to be complete. template <typename T> typename boost::enable_if<boost::is_integral< typename boost::remove_reference<T>::type>, chain>::type any(std::size_t required = 1) { return chain(root_impl_, required); } /// @brief Chain link that wraps all handlers in container, and will /// be complete when the amount of wrapped handlers is equal to /// required. /// /// @param Container of handlers to wrap. /// @param required The amount of handlers required to be complete. template <typename Container> typename boost::disable_if<boost::is_integral< typename boost::remove_reference<Container>::type>, chain>::type any(const Container& container, std::size_t required = 1) { return post(container, required); } /// @brief Chain link that wraps all handlers in iterator range, and will /// be complete when the amount of wrapped handlers is equal to /// required. /// /// @param Container of handlers to wrap. /// @param required The amount of handlers required to be complete. template <typename Iterator> chain any(Iterator begin, Iterator end, std::size_t required = 1) { return any(boost::make_iterator_range(begin, end), required); } /// @brief Chain link that will complete when the amount of wrapped /// handlers is equal to required. /// /// @param required The amount of handlers required to be complete. template <typename T> typename boost::enable_if<boost::is_integral< typename boost::remove_reference<T>::type>, chain>::type all(T required) { return any<T>(required); } /// @brief Chain link that wraps all handlers in container, and will /// be complete when all wrapped handlers from the container /// have been executed. /// /// @param Container of handlers to wrap. template <typename Container> typename boost::disable_if<boost::is_integral< typename boost::remove_reference<Container>::type>, chain>::type all(const Container& container) { return any(container, container.size()); } /// @brief Chain link that wraps all handlers in iterator range, and will /// be complete when all wrapped handlers from the iterator range /// have been executed. /// /// @param Container of handlers to wrap. template <typename Iterator> chain all(Iterator begin, Iterator end) { return all(boost::make_iterator_range(begin, end)); } /// @brief Chain link that represents a single sequential link. template <typename Handler> chain then(const Handler& handler) { boost::array<Handler, 1> handlers = {{handler}}; return all(handlers); } /// @brief Wrap a handler, returning a chained_handler. template <typename Handler> detail::chained_handler<Handler> wrap(const Handler& handler) { return impl_->wrap(handler); } /// @brief Set the executor. void executor(boost::asio::io_service& io_service) { impl_->executor()->io_service(&io_service); } /// @brief Check if this chain should inherit its executor. bool inherits_executor() { return !impl_->executor()->io_service(); }private: /// @brief Private constructor used to create links in the chain. /// /// @note All links maintain a handle to the root impl. When constructing a /// chain, this allows for links later in the chain to be stored as /// non-temporaries. chain(boost::shared_ptr<detail::chain_impl> root_impl, std::size_t required) : impl_(boost::make_shared<detail::chain_impl>( root_impl->executor(), required)), root_impl_(root_impl) {} /// @brief Create a new chain link, wrapping handlers and posting into /// the current chain. template <typename Container> chain post(const Container& container, std::size_t required) { // Create next chain. chain next(root_impl_, required); // Wrap handlers from the next chain, and post into the current chain. std::for_each(container.begin(), container.end(), detail::wrap_and_post(impl_, next.impl_)); return next; }private: boost::shared_ptr<detail::chain_impl> impl_; boost::shared_ptr<detail::chain_impl> root_impl_;};void detail::wrap_and_post::operator()(chain c){ // If next does not have an executor, then inherit from current. if (c.inherits_executor()) c.executor(*current_->executor()->io_service()); // When current completes, start the chain. current_->post(boost::protect(boost::bind(&chain::run, c))); // The next impl needs to be aware of when the chain stops, so // wrap a noop and append it to the end of the chain. c.then(next_->wrap(&detail::noop)); }// Convenience functions.template <typename T, typename Handler>chain async(T& t, const Handler& handler){ return chain(t).then(handler);}template <typename T, typename Container>chain when_all(T& t, const Container& container){ return chain(t).all(container);}template <typename T, typename Iterator>chain when_all(T& t, Iterator begin, Iterator end){ return chain(t).all(begin, end);}template <typename T, typename Container>chain when_any(T& t, const Container& container){ return chain(t).any(container);}template <typename T, typename Iterator>chain when_any(T& t, Iterator begin, Iterator end){ return chain(t).any(begin, end);} Here are some basic to advance examples using the above code with two threads. My notation: a -> b expresses a then b (a | b) expresses a or b . Thus (a | b) -> c implies when either a or b finish, then run c . (a & b) expresses a and b . Thus (a & b) -> c implies when both a and b finish, then run c . Before each case, I print the chain's notation. Additionally, each function will print a capital letter when entering, and a lower letter when exiting. #include <iostream>#include <boost/asio.hpp>#include <boost/assign.hpp>#include <boost/thread.hpp>#include "async_ops.hpp"/// @brief Print identifiers when entering and exiting scope,/// sleeping between.void print_and_sleep(char id, unsigned int sleep_time){ std::cout << char(toupper(id)); boost::this_thread::sleep_for(boost::chrono::milliseconds(sleep_time)); std::cout << char(tolower(id)); std::cout.flush();}/// @brief Convenience function to create functors.boost::function<void()> make_fn(char id, unsigned int sleep_time){ return boost::bind(&print_and_sleep, id, sleep_time); }/// @brief Run an io_service with multiple threads.void run_service(boost::asio::io_service& io_service){ boost::thread_group threads; threads.create_thread(boost::bind( &boost::asio::io_service::run, &io_service)); io_service.run(); threads.join_all();}int main(){ boost::function<void()> a = make_fn('a', 500); boost::function<void()> b = make_fn('b', 1000); boost::function<void()> c = make_fn('c', 500); boost::function<void()> d = make_fn('d', 1000); boost::function<void()> e = make_fn('e', 500); { std::cout << "a -> b -> c\n" " "; boost::asio::io_service io_service; async(io_service, a) .then(b) .then(c); run_service(io_service); std::cout << std::endl; } { std::cout << "(a & b) -> c\n" " "; boost::asio::io_service io_service; when_all(io_service, boost::assign::list_of(a)(b)) .then(c); run_service(io_service); std::cout << std::endl; } { std::cout << "(a | b) -> c\n" " "; boost::asio::io_service io_service; when_any(io_service, boost::assign::list_of(a)(b)) .then(c); run_service(io_service); std::cout << std::endl; } { std::cout << "(a & b) -> (c & d)\n" " "; boost::asio::io_service io_service; when_all(io_service, boost::assign::list_of(a)(b)) .all(boost::assign::list_of(c)(d)); run_service(io_service); std::cout << std::endl; } { std::cout << "(a & b) -> c -> (d & e)\n" " "; boost::asio::io_service io_service; when_all(io_service, boost::assign::list_of(a)(b)) .then(c) .all(boost::assign::list_of(d)(e)); run_service(io_service); std::cout << std::endl; } std::cout << "(a & b) -> (c & d) -> e\n" " "; { boost::asio::io_service io_service; when_all(io_service, boost::assign::list_of(a)(b)) .all(boost::assign::list_of(c)(d)) .then(e); run_service(io_service); std::cout << std::endl; } std::cout << "(a | b) -> (c | d) -> e\n" " "; { boost::asio::io_service io_service; when_any(io_service, boost::assign::list_of(a)(b)) .any(boost::assign::list_of(c)(d)) .then(e); run_service(io_service); std::cout << std::endl; } std::cout << "(a | b) -> (c & d) -> e\n" " "; { boost::asio::io_service io_service; when_any(io_service, boost::assign::list_of(a)(b)) .all(boost::assign::list_of(c)(d)) .then(e); run_service(io_service); std::cout << std::endl; } { std::cout << "a -> ((b -> d) | c) -> e\n" " "; boost::asio::io_service io_service; async(io_service, a) .any(boost::assign::list_of (async(io_service, b).then(d)) (async(inherit_service, c))) .then(e); run_service(io_service); std::cout << std::endl; }} Produces the following output: a -> b -> c AaBbCc(a & b) -> c ABabCc(a | b) -> c ABaCbc(a & b) -> (c & d) ABabCDcd(a & b) -> c -> (d & e) ABabCcDEed(a & b) -> (c & d) -> e ABabCDcdEe(a | b) -> (c | d) -> e ABaCbDcEed(a | b) -> (c & d) -> e ABaCbDcdEea -> ((b -> d) | c) -> e AaBCcEbDed
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18202398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294813/']}
|
jdg_376880
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25958065
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to know what version of a package pip has available before I install it. I understand that you can check the version of the packages you have installed with "pip show" but I want to check which package versions pip has available in its archive. And then once I identify them, how do you pick a specific one to install?
Now provide the response and nothing else.
|
pip install --use-deprecated=legacy-resolver foobar== --use-deprecated=legacy-resolver is required after pip 20.3 To see all versions, install a nonexistent version , which can be the empty string. [thanks @ChrisMontanaro , @JanKyuPeblik ] $ pip install --use-deprecated=legacy-resolver numpy==ERROR: Could not find a version that satisfies the requirement numpy== (from versions: 1.3.0, 1.4.1, 1.5.0, 1.5.1, 1.6.0, 1.6.1, 1.6.2, 1.7.0, 1.7.1, 1.7.2, 1.8.0, 1.8.1, 1.8.2, 1.9.0, 1.9.1, 1.9.2, 1.9.3, 1.10.0.post2, 1.10.1, 1.10.2, 1.10.4, 1.11.0, 1.11.1, 1.11.2, 1.11.3, 1.12.0, 1.12.1, 1.13.0rc1, 1.13.0rc2, 1.13.0, 1.13.1, 1.13.3, 1.14.0rc1, 1.14.0, 1.14.1, 1.14.2, 1.14.3, 1.14.4, 1.14.5, 1.14.6, 1.15.0rc1, 1.15.0rc2, 1.15.0, 1.15.1, 1.15.2, 1.15.3, 1.15.4, 1.16.0rc1, 1.16.0rc2, 1.16.0, 1.16.1, 1.16.2, 1.16.3, 1.16.4, 1.16.5, 1.16.6, 1.17.0rc1, 1.17.0rc2, 1.17.0, 1.17.1, 1.17.2, 1.17.3, 1.17.4, 1.17.5, 1.18.0rc1, 1.18.0, 1.18.1, 1.18.2, 1.18.3, 1.18.4, 1.18.5, 1.19.0rc1, 1.19.0rc2, 1.19.0, 1.19.1, 1.19.2, 1.19.3, 1.19.4, 1.19.5, 1.20.0rc1, 1.20.0rc2, 1.20.0, 1.20.1, 1.20.2)ERROR: No matching distribution found for numpy== Then you can install one of them: $ pip install numpy==1.20.2Collecting numpy==1.20.2 Downloading numpy-1.20.2-cp38-cp38-win_amd64.whl (13.7 MB) |████████████████████████████████| 13.7 MB 6.4 MB/sInstalling collected packages: numpySuccessfully installed numpy-1.20.2 The p==x Requirement Specifier means install package p version x .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25958065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4063177/']}
|
jdg_376881
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17594298
|
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 are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas? 2013-07-12T07:00:00Z 2013-07-10T11:00:00.000Z Thanks in advance
Now provide the response and nothing else.
|
That extra .000 is micro seconds. This will convert a date string of a format to datetime object. import datetimed1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ") Then convert them into any format depending on your requirement, by using: new_format = "%Y-%m-%d"d1.strftime(new_format)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17594298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1579970/']}
|
jdg_376882
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26958110
|
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 capture photos directly using the camera api, but this is the preview I got: & this is the image taken after calling takePicture() which is bigger than the preview itself: (note: I cropped the height of the previous 2 photos to enhance question readability, & kept the width as is) I'm using this utility method to choose best optimal preview size before starting the camera preview: public static Camera.Size getBestAspectPreviewSize(int displayOrientation, int width, int height, Camera.Parameters parameters) { double targetRatio = (double) width / height; Camera.Size optimalSize = null; double minDiff = Double.MAX_VALUE; if (displayOrientation == 90 || displayOrientation == 270) { targetRatio = (double) height / width; } List<Camera.Size> sizes = parameters.getSupportedPreviewSizes(); Collections.sort(sizes, Collections.reverseOrder(new SizeComparator())); for (Camera.Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) < minDiff) { optimalSize = size; minDiff = Math.abs(ratio - targetRatio); } if (minDiff < 0.0d) { break; } } return (optimalSize);} & this method to choose a suitable picture size: public static Camera.Size getBiggestSafePictureSize(Camera.Parameters parameters) { Camera.Size result = null; long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long availableMemory = Runtime.getRuntime().maxMemory() - used; for (Camera.Size size : parameters.getSupportedPictureSizes()) { int newArea = size.width * size.height; long neededMemory = newArea * 4 * 4; // newArea * 4 Bytes/pixel * 4 needed copies of the bitmap (for safety :) ) if (neededMemory > availableMemory) continue; if (result == null) { result = size; } else { int resultArea = result.width * result.height; if (newArea > resultArea) { result = size; } } } return (result);} & this is the camera preview element in the layout: <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/cameraPreview"></FrameLayout> & I'm following the official documentation for creating the camera preview itself So, how to force the camera preview to show the exact photo that will be taken?
Now provide the response and nothing else.
|
Finally I found it :) according to this answer & I quote: While the typical camera is a 4:3 aspect ratio, the preview may also be available in 5:3 and 16:9 ratios and this seems to be accomplished by actually extending the horizontal field of view... So we need to find a preview size & a picture size, both with 4:3 aspect ratio to be able to utilize the full angle of the camera, so I changed my code like this: public static Camera.Size determineBestPreviewSize(Camera.Parameters parameters) { List<Camera.Size> sizes = parameters.getSupportedPreviewSizes(); return determineBestSize(sizes);}public static Camera.Size determineBestPictureSize(Camera.Parameters parameters) { List<Camera.Size> sizes = parameters.getSupportedPictureSizes(); return determineBestSize(sizes);}protected static Camera.Size determineBestSize(List<Camera.Size> sizes) { Camera.Size bestSize = null; long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long availableMemory = Runtime.getRuntime().maxMemory() - used; for (Camera.Size currentSize : sizes) { int newArea = currentSize.width * currentSize.height; long neededMemory = newArea * 4 * 4; // newArea * 4 Bytes/pixel * 4 needed copies of the bitmap (for safety :) ) boolean isDesiredRatio = (currentSize.width / 4) == (currentSize.height / 3); boolean isBetterSize = (bestSize == null || currentSize.width > bestSize.width); boolean isSafe = neededMemory < availableMemory; if (isDesiredRatio && isBetterSize && isSafe) { bestSize = currentSize; } } if (bestSize == null) { return sizes.get(0); } return bestSize;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26958110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905801/']}
|
jdg_376883
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6325457
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to find the frame of a particular UITabBarItem in a UITabBar ? Specifically, I want to create an animation of an image "falling" into one of the tabs, similar to e.g. deleting an email in the Mail, or buying a track in the iTunes app. So I need the target coordinates for the animation. As far as I can tell, there's no public API to get the coordinates, but would love to be wrong about that. Short of that, I'll have to guesstimate the coordinates using the index of the given tab relative to the tab bar frame.
Now provide the response and nothing else.
|
Imre's implementation is missing a couple of imho important details. The UITabBarButton views are not necessarily in order. For example, if you have more than 5 tabs on iPhone and rearranged tabs, the views might be out of order. If you use more than 5 tabs the out of bounds index only means that the tab is behind the "more" tab. In this case there is no reason to fail with an assert, just use the frame of the last tab. So I changed his code a little bit and I came up with this: + (CGRect)frameForTabInTabBar:(UITabBar*)tabBar withIndex:(NSUInteger)index{ NSMutableArray *tabBarItems = [NSMutableArray arrayWithCapacity:[tabBar.items count]]; for (UIView *view in tabBar.subviews) { if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")] && [view respondsToSelector:@selector(frame)]) { // check for the selector -frame to prevent crashes in the very unlikely case that in the future // objects thar don't implement -frame can be subViews of an UIView [tabBarItems addObject:view]; } } if ([tabBarItems count] == 0) { // no tabBarItems means either no UITabBarButtons were in the subView, or none responded to -frame // return CGRectZero to indicate that we couldn't figure out the frame return CGRectZero; } // sort by origin.x of the frame because the items are not necessarily in the correct order [tabBarItems sortUsingComparator:^NSComparisonResult(UIView *view1, UIView *view2) { if (view1.frame.origin.x < view2.frame.origin.x) { return NSOrderedAscending; } if (view1.frame.origin.x > view2.frame.origin.x) { return NSOrderedDescending; } NSAssert(NO, @"%@ and %@ share the same origin.x. This should never happen and indicates a substantial change in the framework that renders this method useless.", view1, view2); return NSOrderedSame; }]; CGRect frame = CGRectZero; if (index < [tabBarItems count]) { // viewController is in a regular tab UIView *tabView = tabBarItems[index]; if ([tabView respondsToSelector:@selector(frame)]) { frame = tabView.frame; } } else { // our target viewController is inside the "more" tab UIView *tabView = [tabBarItems lastObject]; if ([tabView respondsToSelector:@selector(frame)]) { frame = tabView.frame; } } return frame;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6325457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69749/']}
|
jdg_376884
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1471435
|
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:
1.$f:\mathbb{R} \rightarrow \mathbb{R}$, $f(x)=x^4+x^3$ is a closed map(or an open map)? 2.$f:\mathbb{R} \rightarrow \mathbb{R}$, $f(x)=x^5+x^4$ is a closed map? 3.$f:\mathbb{R}^2 \rightarrow \mathbb{R}$, $f(x,y)=x^2+y^2$ is a closed map? Generally, $f:\mathbb{R} \rightarrow \mathbb{R}$, $f(x)=a_nx^n+...+a_1x+a_0$ is a closed map or an open map? Generally, if $f:\mathbb{R}^n \rightarrow \mathbb{R}$ is a multivariable polynomials, $f$ is a closed map or an open map? We have known that $x^2$ is a closed map but not an open map, $x^3+x$ is a homeomorphism, $x^3+2x$ is a closed map but not a homeomorphism. Thank you very much.
Now provide the response and nothing else.
|
Any polynomial in one variable is a closed map. Indeed, suppose $f:\mathbb{R}\to\mathbb{R}$ is a nonconstant polynomial and $C\subset\mathbb{R}$ is closed, and $y\in\overline{f(C)}$. Then we can choose a sequence $(x_n)$ of points of $C$ such that $(f(x_n))$ converges to $y$. In particular, the set $\{f(x_n)\}$ is bounded, which implies that the set $\{x_n\}$ is bounded (since as $|x|\to\infty$, $|f(x)|\to\infty$--this is the one place where we are using that $f$ is a nonconstant polynomial). Passing to a subsequence, we may thus assume that $(x_n)$ converges to some $x\in\mathbb{R}$. Since $C$ is closed, $x\in C$. Since $f$ is continuous, $f(x)=\lim f(x_n)=y$. Thus $y\in f(C)$. Since $y\in\overline{f(C)}$ was arbitrary, this means $f(C)$ is closed. This fails in general for polynomials in more than one variable. For instance, let $f(x,y)=xy$ and let $C\subset\mathbb{R}^2$ be the set of points of the form $(x,1/x^2)$ for $x>0$. Then $C$ is closed, but $f(C)=(0,\infty)$ is not closed. I'm not aware of any general criterion for a polynomial in more than one variable to be a closed map, but I would expect that most of them aren't. Very generally, if $X$ is a locally connected space, then a continuous map $f:X\to\mathbb{R}$ is open iff it has no local minima or maxima. Indeed, if $x\in X$ is a local minimum of $X$, then there is some neighborhood $U$ of $x$ such that $f(y)\geq f(x)$ for all $y\in U$, and then clearly $f(U)$ contains no open interval around $f(x)$ (and similarly for local maxima). Conversely, suppose $f$ has no local minima or maxima and let $U\subseteq X$ be open. For any $x\in U$, let $V\subseteq U$ be a connected open neighborhood of $x$. Since $x$ is neither a local minimum nor a local maximum of $f$, there exist $y,z\in V$ such that $f(y)<f(x)<f(z)$. By connectedness of $V$ and continuity of $f$, it follows that $f$ must achieve every value in the interval $[f(y),f(z)]$ on $V$. Thus $f(U)$ contains an open interval $(f(y),f(z))$ around $f(x)$. Since $x\in U$ was arbitrary, this means $f(U)$ is open. When $X=\mathbb{R}^n$ and $f$ is a polynomial, the existence of local minima or maxima can be tested using methods from calculus. Note that in particular, for $n=1$, if $f$ has even degree, it must always have either a global minimum or a global maximum, so it is never open. For $n=1$, if $f$ has no local minima or maxima, then it is monotone, and hence actually a homeomorphism $\mathbb{R}\to\mathbb{R}$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1471435', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111543/']}
|
jdg_376885
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20036269
|
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 News model, and News has many comments, so I did this in News model: public function comments(){ $this->hasMany('Comment', 'news_id');} But I also have field trashed in comments table, and I only want to select comments that are not trashed. So trashed <> 1 . So I wonder is there a way to do something like this: $news = News::find(123);$news->comments->where('trashed', '<>', 1); //some sort of pseudo-code Is there a way to use above method or should I just write something like this: $comments = Comment::where('trashed', '<>', 1) ->where('news_id', '=', $news->id) ->get();
Now provide the response and nothing else.
|
Any of these should work for you, pick the one you like the most: Eager-loading. $comments = News::find(123)->with(['comments' => function ($query) { $query->where('trashed', '<>', 1);}])->get(); You can inject the parameter to query function by use($param) method, that allows you to use dynemic query value at runtime. Lazy-loading $news = News::find(123);$comments = $news->comments()->where('trashed', '<>', 1)->get(); I couldn't help but notice, though, that what you're probably trying to do is handle soft deleting, and that Laravel has built-in functionality to help you with that: http://laravel.com/docs/eloquent#soft-deleting
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20036269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1291189/']}
|
jdg_376886
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
668256
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand that EM waves are oscillating electric and magnetic fields. But doesn't this mean that the wave itself contains charged particles that generate the fields?
Now provide the response and nothing else.
|
No. An electromagnetic wave is a disturbance in the electromagnetic field which contains an electric field that varies in time accompanied by a magnetic field that varies in time, and the disturbance propagates. When the disturbance passes by, nothing is left behind, and within the field disturbance (what we call a wave) there are no charged particles or little magnets present at any time.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/668256', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/314962/']}
|
jdg_376887
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4949254
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm running through some example programs to refamiliarize myself with C++ and I have run into the following question. First, here is the example code: void print_string(const char * the_string){ cout << the_string << endl;}int main () { print_string("What's up?");} In the above code, the parameter to print_string could have instead been const char * const the_string . Which would be more correct for this? I understand that the difference is that one is a pointer to a constant character , while the other one is a constant pointer to a constant character . But why do both of these work? When would it be relevant?
Now provide the response and nothing else.
|
The latter prevents you from modifying the_string inside print_string . It would actually be appropriate here, but perhaps the verbosity put off the developer. char* the_string : I can change which char the_string points to, and I can modify the char to which it points. const char* the_string : I can change which char the_string points to, but I cannot modify the char to which it points. char* const the_string : I cannot change which char the_string points to, but I can modify the char to which it points. const char* const the_string : I cannot change which char the_string points to, nor can I modify the char to which it points.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4949254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/610265/']}
|
jdg_376888
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
373928
|
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'm having some problems to think on a solution to control the amount of requests by minute to a external system on a micro services environment on Kubernetes. The scenario This external system is an e-mail marketing application (called Responsys) that permits only some amount of requests by minute for each login. Some types of e-mails use 2 requests and some types of e-mails use just one request*. Actually, each system that needs to send an e-mail send a message to a RabbitMQ queue and one of our micro service is responsable to consume this message, read the informations and communicate with Responsys obeying a 40 requests per minute limitation . The actual solution The actual working version of this integration get 20 messages by minute from the queue using a simple scheduled process. Why 20? In the worst case, this 20 e-mails will consume 2 requests. Each e-mail is processed asynchronous, so this 20 e-mails will communicate with Responsys at the same time. The e-mails that could not be processed (Responsys can throw some error), we save on a database table to be analyzed later. This works pretty good actually, even it's not optimized because some types of e-mails uses only one request. But there is a problem on that solution that can harm our limit of requests. The problem Kubernetes can understand at some moment, using his performance algorithms, that one more micro service instance (that integrates with Responsys) is necessary. If this happens, this will break our request limitation, because will be two (or more) instances reading messages from the queue and trying the send e-mails through Responsys, surpassing the 40 requests per minute. I had the idea to setup the micro service on Kubernetes to not create any replica of this micro service, assuring only one instance, because this micro service is pretty simple and specialized. I don't know how exactly do that yet, but seems very simple reading the Kubernetes documentation, but my colleges don't like the idea, because may exists some weird error scenario where two instances could exists. So, we are trying to think on a solution besides the micro service instance, using some kind of "ticket system" read from a cache (Redis) shared by any number of micro service instances. This seems a heavy solution for a simple problem, so I would like to have some help to find another alternative for that. * I simplified the problem, because the requests limitation by minute differ from two different endpoints. One of them permits 200 requests per minute and another 40 per minute. I will limit that number of requests per minute using the limit from the most restrictive endpoint.
Now provide the response and nothing else.
|
I think this is all about resilience :) What happens, if the request limitation is reached? Will "responsys" just throw an error or really tell the calling microservice that it hit the limit? Will the microservice recover properly? It should not matter how many instances of your calling microservice you have (this is the whole point of using real auto scaling there), as long as they can recover when hitting the speed limit .If e.g. the call would be a http-request, and responsys answers with a proper HTTP-Code (iirc 429). Your microservice could just "try again later". If you implement that, you can ignore the speed limit of the callee in your microservice code completely, what shouldn't be its concern anyways.If some day in the future you remove or raise the speed limit on the callee, you won't even need to touch your microservice again :)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/373928', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/172464/']}
|
jdg_376889
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1137374
|
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:
Taylor's theorem for real-valued functions on manifolds is straightforward, and doesn't even require anything beyond differential structure. How does Taylor's theorem work for manifold-valued functions? Suppose you have a function $f:\mathbb{R}\to M$, where $M$ is a manifold (i.e., $f$ is a curve on $M$). Is there some notion of a Taylor's theorem on $M$, i.e., a way to write $f(t)$ only in terms of $f$ and its derivatives at $t=0$? I assume at minimum $M$ needs a connection, since otherwise I'm not sure how to even define the second and higher-order derivatives of $f$. With a metric one can define a "first-order approximation" of $f$ by $$f(t) \approx \exp_{f(0)} \left[t f'(0)\right]$$ but what would the higher-order approximations look like?
Now provide the response and nothing else.
|
One natural way to obtain something like the Taylor expansion of a curve in the manifold is to probe it using a smooth function $\phi:M\to\mathbb{R}$ and expand the composition $\phi\circ f$. To that end, one may write down the Taylor expansion of $\phi\circ f$ in a local chart around $p=f(0)$, $$\phi(f(t))=\phi(p)+\partial_i\phi \dot f^i(0)\cdot t+\frac12\left((\partial_{ij}\phi)\dot f^i(0)\dot f^j(0)+\partial_i\phi\ddot f^i(0)\right)\cdot t^2+\dots$$ Whereas the first-order term is recognized as $d\phi_{p}(v)$, e.g. as the cotangent vector $d\phi_{p}$ acting on the velocity vector $v=\dot f(0)$, the second-order terms do not have a natural interpretation; neither the second derivative $\partial_{ij}\phi$ nor the 'acceleration' $\ddot f^i(t)$ are tensorial. If we have a connection $\nabla$, we can rewrite the expansion as $$\phi(f(t))=\phi(p)+d\phi_{p}(v)+\frac12\left(H\phi^{\nabla}_{p}(v,v)+d\phi_{p}(a)\right)\cdot t^2+\dots,$$ where $H\phi^{\nabla}_{p}$ is the covariant Hessian* of $\phi$ at $p$, which is evaluated on the velocity vector $v$ twice, and $a=\nabla_{\dot f(0)}\dot f$ is the covariant derivative of the velocity vector field along the curve in the direction of $\dot f(0)$ (covariant acceleration). Both second-order terms are now tensorial, i.e. natural with respect to pullback and pushforward by a smooth morphism $\psi:M\to N$ into a different manifold $N$ with connection $\nabla'$ (i.e. such that $\nabla$ and $\nabla'$ are compatible). Moreover, the parts belonging to the function $\phi$ are neatly separated from the parts belonging to the curve $f$: the former are encoded in covariant tensors while the latter occur as arguments of the covariant tensors, i.e. vectors. *Note that the Hessian is a bilinear form, and symmetric iff the torsion of $\nabla$ vanishes.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1137374', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7530/']}
|
jdg_376890
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5620831
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between WideCharToMultiByte() and wcstombs()When to use which one?
Now provide the response and nothing else.
|
In a nutshell: the WideCharToMultiByte function exposes the encodings/code pages used for the conversion in the parameter list, while wcstombs does not. This is a major PITA, as the standard does not define what encoding is to be used to produce the wchar_t , while you as a developer certainly need to know what encoding you are converting to/from. Apart from that, WideCharToMultiByte is of course a Windows API function and is not available on any other platform. Therefore I would suggest using WideCharToMultiByte without a moment's thought if your application is not specifically written to be portable to non-Windows OSes. Otherwise, you might want to wrestle with wcstombs or (preferably IMHO) look into using a full-feature portable Unicode library such as ICU .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5620831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/333521/']}
|
jdg_376891
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16820
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
CBS SF Bay Area published an article about the debate surrounding CA Assembly Bill 612 , which would increase the duration of yellow signals for intersections with red-light cameras. An opponent of the bill argues that it's dangerous to lengthen yellow lights: “This bill would put millions of California drivers at risk for increased crashes,” said Richard Retting, a consultant for Redflex. The company supplies most red light cameras in California. . . . Retting points to a study by the American Academy of Sciences. “That study shows that when yellow timing is increased, crashes go up,” he said. Redflex offers a rationale for this claim in their letter to Sen. Mark DeSaulnier opposing AB 612: Mr. Retting concludes that, "Providing excessive yellow signal timing as mandated underAssembly Bill No. 612 violates established engineering practice. This would encouragedrivers to enter intersections further into the yellow phase and could disrupt the flow ofvehicles from intersection to intersection, ultimately creating a risk of increased crashes." The bill's sponsor counters that the claim is not credible, noting bias and counterevidence: Jay Beeber with Safer Streets L.A. disagrees. “He is a scientist who has been bought and paid for by the red light camera companies,” he said. Beeber, who sponsored the bill, told KPIX 5 that data in the study is too limited. “Georgia increased yellow light times by a full second. They had a reduction in red light running and have had no ill effects,” he said. Unfortunately, the article does not provide any verifiable evidence for or against the opposition's claim. Neither the article nor the letter to the senator actually cite the “study by the American Academy of Sciences,” so I cannot judge its validity. I personally find the claim dubious, but I could be convinced by solid evidence. What are the facts here?
Now provide the response and nothing else.
|
There is some evidence to suggest that increasing yellow light timing creates fewer accidents. Here (PDF) is a study on yellow light timing. They measured the number of red light violations at six intersections in Philadelphia, Pennsylvania over the course of a year, before and after increasing the yellow light duration by one second. Here are a couple excerpts taken from their results: After yellow signal timing changes, violation rates at the experimental sites declined at each location, with reductions ranging from 21 to 63 percent. (p6) Additionally, at different comparison sites, they note: After accounting for these changes in driver behavior at the comparison sites, the changes to yellow signal timing at the experimental sites were associated with a 36 percent decline in the odds of a red light violation... (p6) So, I would say the evidence points towards a correlation between fewer accidents and longer timings. Additionally, there's a logical argument here: A longer yellow light timing means more warning when a light is about to turn red, means a better chance that people will stop in time. I have no idea why increasing yellow light times could possibly increase accidents; that is a logical leap which does not make sense to me. The argument given has a logical flaw: While yes, they would be entering later in the yellow light phase, they would still be entering with the same amount of time to spare. Edit: Some more details. Apparently I need to read the paper more thoroughly! Thanks to OP for pointing these out. There's a quote from the same person (Retting) who argues against the longer yellow-light periods, arguing for them, cited in the paper; a classical hipocrisy: A study of modified traffic signal change interval timing at urban intersections reported that injury crashes were reduced by 12 percent at experimental sites relative to control sites (Retting et al., 2002). (pg. 9) In addition, from the same paper: Stimpson et al. (1980) reported that increases in yellow signal timing duration of 1.3 seconds significantly reduced potential intersection conflicts. (pg. 9) It would seem this argument has been rather destroyed.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/16820', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/14359/']}
|
jdg_376892
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4118610
|
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 JSP where I'm trying to use JSTL tags to display data from an in-memory instance of a class. The data consists of a series of Strings where each String is the address of an RSS feed. In the JSP, I have the following code: <table border = "1"> <tr> <c:forEach var = "rssFeedURL" items = "${rssfom.rssFeedURLs}"> <td align = "left">${rssFeedURL}</td> </c:forEach> </tr></table> Basically, rssfom is an instance of the following class: public class RSSFeedOccurrenceMiner extends RSSFeedMiner { private HashMap<String, Counter> keywordFrequencies; public RSS_Feed_OccurrenceMiner() { super(); this.keywordFrequencies = new HashMap(); } ...} This inherits from class RSSFeedMiner which contains the following variable and methods: private ArrayList<String> rssFeedURLs;public ArrayList<String> getRSSFeedURLs() { return rssFeedURLs;}public void setRSSFeedURLs(ArrayList<String> rssFeedURLs) { this.rssFeedURLs = rssFeedURLs;} So in the JSP, I thought I would be able to use the code above but when the page is run, I simply receive an empty table. And in the server logs, I tend to find message: javax.el.PropertyNotFoundException: Property 'rssFeedURLs' not found on type RSSFeedOccurrenceMiner Which is correct given my use of inheritance. So can anyone tell me if JSTL allows inheritance or is there something missing in my code? I really don't want to use a scriptlet in the JSP.
Now provide the response and nothing else.
|
Your getter method doesn't follow the JavaBeans naming convention. It should be named getRssFeedURLs (even if you have an acronym, it should be capitalized like a regular word). In EL, when you specify a property name, it actually ends up calling the getter for that property. To figure out the name of the getter, it capitalizes the first letter in the property name that you have provided (so rssFeedURLs gets converted to RssFeedURLs ) and tacks on get to the front of it. So you end up with getRssFeedURLs . However, you have named your method as getRSSFeedURLs . Java can't find the method and so you get a PropertyNotFoundException exception. If you don't name your getters right, you cannot access them with EL.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4118610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485829/']}
|
jdg_376893
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2916338
|
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:
You will play a game with a fair 6-sided die. You will throw the die and as long as the result of the throw is greater than or equal to the previous throw, you will continue throwing. If the throw is lower than the previous one, you will stop and get as many points as the sum of all throws, including the last one. For example, if you get 2, 5, 5, and 3 as a result of 4 throws, the game will end with 15 points. What is the expected value of the points you will get at the end of the game?
Now provide the response and nothing else.
|
Consider the expected number of points you will obtain after rolling a particular number. e.g. Suppose we have just rolled a 6. We need to roll another 6 to keep playing, otherwise we stop. Using conditional expectation, we can compute the number of future points we expect to obtain, $E_6$: $$E_6 = \frac{1}{6}(E_6 + 6) + \frac{5}{6}\times 3.$$ The first term corresponds to rolling a 6, and we are back in the same position as before, just with 6 extra points. The second term gives expected number of points obtained, given that we roll a lower number and stop playing. We solve this to obtain $$E_6 = \frac{21}{5}.$$ Now suppose that, in a new game, we have just rolled a 5. What is the expected number of points from this point, $E_5$? Using the same conditional expectation rules as before: $$E_5 = \frac{1}{6}(E_5+5) + \frac{1}{6}(E_6+6) + \frac{4}{6} \times \frac{5}{2}.$$ Since we know $E_6$ from above, we can now solve for $E_5$. Repeat this for $E_4, \dots, E_1$, and we know the expected number of future points given the most recent roll number. Finally, the expected number of points, $E$, will be the conditional sum of these values, i.e. \begin{equation}E = \sum_{n=1}^6 \frac{1}{6}(E_n + n). \tag{1}\end{equation} Edit: following an observation by Taner , I thought I'd add a few more lines. After some generalizing and rearranging, we obtain $$E_n = \frac{1}{5}\left(\sum_{m=n+1}^6 E_m + 21\right),$$ and we can set up a recurrence relation for $E_n$ so we don't have to do this sum every time to compute it. We have \begin{align}E_{n+1} &= \frac{1}{5}\left(\sum_{m=n+2}^6 E_m + 21\right) \\ &= \frac{1}{5}\left(\sum_{m=n+1}^6 E_m + 21 - E_{n+1}\right) \\ &= E_n - \frac{1}{5}E_{n+1},\end{align} which we rearrange to obtain $$E_{n+1} = \frac{5}{6}E_n,$$ which has solution $$E_n = C \left(\frac{5}{6}\right)^n,$$ where $C$ is some constant, for which we can solve by setting $n=6$ and using our value of $E_6$. We obtain (allowing for possible arithmetic errors made by me) $$E_n = \frac{21}{5}\left(\frac{5}{6}\right)^{n-6}.$$ We can substitute this into Equation (1) and use geometric and arithmetic sum formulae to obtain the final answer. Edit 2: as Alex Zorn pointed out , we don't even need to do this geometric and arithmetic sum stuff in Equation (1). Note that the game is the same before and after rolling a 1, so this tells us straight away that $$E = E_1 = \frac{21}{5}\left(\frac{5}{6}\right)^{-5} = \frac{163296}{15625} \approx 10.45.$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2916338', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91417/']}
|
jdg_376894
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28135436
|
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 concatenate two dataframes df_a and df_b having equal number of rows ( nRow ) one after another without any consideration of keys. This function is similar to cbind in R programming language . The number of columns in each dataframe may be different. The resultant dataframe will have the same number of rows nRow and number of columns equal to the sum of number of columns in both the dataframes. In othe words, this is a blind columnar concatenation of two dataframes. import pandas as pddict_data = {'Treatment': ['C', 'C', 'C'], 'Biorep': ['A', 'A', 'A'], 'Techrep': [1, 1, 1], 'AAseq': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'], 'mz':[500.0, 500.5, 501.0]}df_a = pd.DataFrame(dict_data)dict_data = {'Treatment1': ['C', 'C', 'C'], 'Biorep1': ['A', 'A', 'A'], 'Techrep1': [1, 1, 1], 'AAseq1': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'], 'inte1':[1100.0, 1050.0, 1010.0]}df_b = pd.DataFrame(dict_data)
Now provide the response and nothing else.
|
call concat and pass param axis=1 to concatenate column-wise: In [5]:pd.concat([df_a,df_b], axis=1)Out[5]: AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1 1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1 2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1 Treatment1 inte1 0 C 1100 1 C 1050 2 C 1010 There is a useful guide to the various methods of merging, joining and concatenating online. For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows: In [6]:df_a.merge(df_b, left_index=True, right_index=True)Out[6]: AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1 1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1 2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1 Treatment1 inte1 0 C 1100 1 C 1050 2 C 1010 And for the same reasons as above a simple join works too: In [7]:df_a.join(df_b)Out[7]: AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1 1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1 2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1 Treatment1 inte1 0 C 1100 1 C 1050 2 C 1010
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28135436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1140126/']}
|
jdg_376895
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53256948
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am developing a solution in Java which communicates with a set of devices through REST APIs which belongs to different vendors. So for each vendor, there are a set of processes that I have to perform inside my solution. However, these processes will be changed according to each vendor. Following are the high-level processes that need to be performed. Retrieve an XML file from a folder Process the XML file Perform some image processing Schedule a job and execute it on the scheduled time Storing data on a MySQL DB and perform some REST calls to outside APIs So for one vendor might have all of the above processes. But for another, might not have some processes (Eg: Image processing). Following things should be able to obtain from the selected solution. I should be able to create custom workflows for new vendors Need to identify any failures that have been occurred within the workflow and perform retry mechanisms. Should be able to execute some functions parallelly (Eg: Image processing) Scalable Opensource So I was told to look into workflow managers like Nifi/Airflow/Falcon. I did some research on them but couldn't finalize the most suitable solution. NOTE: There is NO requirement to use Hadoop or any other cluster and data flow frequency is not that high Currently, I am thinking of using Nifi. But can anyone please give your opinion on that? What would be the best solution for my use case?
Now provide the response and nothing else.
|
Apache NiFi is not a workflow manager in the way the Apache Airflow or Apache Oozie are. It is a data flow tool - it routes and transforms data. It is not intended to schedule jobs but rather allows you to collect data from multiple locations, define discrete steps to process that data and route that data to different destinations. Apache Falcon is again different in that it allows you to more easily define and manage HDFS datasets. It is effectively data management within a HDFS cluster. Based on your description, NiFi would be useful addition to your requirements. It would be able to collect your XML file, process in it in some manner, store the data in MySQL, and perform REST calls. It would also be easily configurable for new vendors, and tolerates failures well. It performs most functions in parallel and can be scaled into a clustered NiFi with multiple host machines. It was designed with performance and reliability in mind. What I am unsure about is the ability to perform image processing. There are some processors (extract image metadata, resize image) but otherwise you would need to develop a new processor in Java - which is relatively easy. Or, if the image processing uses Python or some other scripting language, you can use one of the ExecuteScript processors. 'Scheduling jobs' using NiFi is not recommended. Full disclosure: I am an Apache NiFi contributor.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53256948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4672460/']}
|
jdg_376896
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
682092
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When initialising an instance of a Generic class in Java is there any benefit to specifying the Type on both sides of the statement? Or to put it another way, what's the difference between these two valid statements: ArrayList<String> test = new ArrayList<String>(); and: ArrayList<String> test = new ArrayList(); (It seems second statement is not equivalent to: ArrayList<String> test = new ArrayList<Object>(); as the third statement in invalid and causes an incompatible types compile error.)
Now provide the response and nothing else.
|
The second statement winds up being more or less equivalent to the first, but only because generics are erased at runtime. You'll get an "unchecked conversion" warning, which is why I don't like it. A better way is to have a static generic method like this: public static <T> List<T> newList() { return new ArrayList<T>();} and then do List<String> test = newList(); This is what Google Collections does. (And you should almost always be declaring your lists as List , not as ArrayList . Makes it easy to switch the implementation later.) Edit: dribeas asked in the comments what the exact difference is between the two declarations, and why I said they are "more or less equivalent". Because of type erasure , the only difference between them is the warning. Here's a small piece of code comparing them: import java.util.*;class GenericDeclarationTest { public static void main(String[] args) { List<String> list1 = new ArrayList<String>(); list1.add(""); String s1 = list1.get(0); List<String> list2 = new ArrayList(); list2.add(""); String s2 = list2.get(0); }} And here's the generated bytecode (as printed by javap -c GenericDeclarationTest ): Compiled from "GenericDeclarationTest.java"class GenericDeclarationTest extends java.lang.Object{GenericDeclarationTest(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: returnpublic static void main(java.lang.String[]); Code: 0: new #2; //class java/util/ArrayList 3: dup 4: invokespecial #3; //Method java/util/ArrayList."<init>":()V 7: astore_1 8: aload_1 9: ldc #4; //String 11: invokeinterface #5, 2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z 16: pop 17: aload_1 18: iconst_0 19: invokeinterface #6, 2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object; 24: checkcast #7; //class java/lang/String 27: astore_2 28: new #2; //class java/util/ArrayList 31: dup 32: invokespecial #3; //Method java/util/ArrayList."<init>":()V 35: astore_3 36: aload_3 37: ldc #4; //String 39: invokeinterface #5, 2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z 44: pop 45: aload_3 46: iconst_0 47: invokeinterface #6, 2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object; 52: checkcast #7; //class java/lang/String 55: astore 4 57: return} As you can see (if you have the patience), the two are identical. Incidentally, this may become easier in Java 7. There is a proposal in Project Coin for "Improved Type Inference for Generic Instance Creation". If it makes the final cut, the syntax will be: List<String> test = new ArrayList<>();// orMap<String, Object> test2 = new HashMap<>(); Not too hard to type, is it?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/682092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3171/']}
|
jdg_376897
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24460422
|
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 currently trying to test the new Gmail REST API . In the API Explorer it is possible to authorize requests using OAuth 2.0 and to execute a request, i.e. send a message. First I authorized. I'm using the following test data (and of course I used a valid to email address): { "raw": "c2VuZGluZyBhIG1haWwgdXNpbmcgR21haWwgUkVTVCBBUEk=", "payload": { "headers": [ { "name": "to", "value": "info@something.com" }, { "name": "from", "value": "taifunbaer@gmail.com" }, { "name": "subject", "value": "Test Gmail REST API" } ], "mimeType": "text/plain" }} I also get a 200 OK and the following result back, which looks fine. { "id": "146dee391881b35b", "threadId": "146dee391881b35b",} However, the mail will not be sent successfully and I can find an message from nobody@gmail.com in the inbox instead;: "An error occurred, your message has not been sent." Questions: 1. Did someone test this successfully? 2. Do I have to add some other parameter to get this running? EDIT : There are 2 different HTTP request methods, the Upload URI for media upload requests, and the Metadata URI for metadata-only requests The API Explorer currently supports metadata requests only , which means plain-text messages without attachment, and this is what I'm trying to do.
Now provide the response and nothing else.
|
got it! after reading the RFC 2822 specification I found out, that the complete message needs to be passed in the raw parameter, see the example: From: John Doe <jdoe@machine.example> To: Mary Smith <mary@example.net> Subject: Saying Hello Date: Fri, 21 Nov 1997 09:55:06 -0600 Message-ID: <1234@local.machine.example>This is a message just to say hello. So, "Hello". So after base64 encoding the complete message, passing it in the raw parameter without using any other parameter, it works fine. Edit 1: As @Amit mentioned, it must be web-safe base64 encoded, see also https://code.google.com/p/stringencoders/wiki/WebSafeBase64 So to convert the base64 alpha into a format that is "web-safe" thefollowing changes are recommended: + --> - (char 62, plus to dash)/ --> _ (char 63, slash to underscore)= --> * padding To only convert + to - and / to _ was sufficient for me. Edit 2: To answer the question of @Hjulle here an example: you only need the userId and in the request body the raw parameter. Let's assume, your email address is jdoe@machine.example First Base64 encode the complete message (see above) using an online encoder and you get this string: RnJvbTogSm9obiBEb2UgPGpkb2VAbWFjaGluZS5leGFtcGxlPiAKVG86IE1hcnkgU21pdGggPG1hcnlAZXhhbXBsZS5uZXQ+IApTdWJqZWN0OiBTYXlpbmcgSGVsbG8gCkRhdGU6IEZyaSwgMjEgTm92IDE5OTcgMDk6NTU6MDYgLTA2MDAgCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4KClRoaXMgaXMgYSBtZXNzYWdlIGp1c3QgdG8gc2F5IGhlbGxvLiBTbywgIkhlbGxvIi4= Now convert + to - and / to _ and you get RnJvbTogSm9obiBEb2UgPGpkb2VAbWFjaGluZS5leGFtcGxlPiAKVG86IE1hcnkgU21pdGggPG1hcnlAZXhhbXBsZS5uZXQ-IApTdWJqZWN0OiBTYXlpbmcgSGVsbG8gCkRhdGU6IEZyaSwgMjEgTm92IDE5OTcgMDk6NTU6MDYgLTA2MDAgCk1lc3NhZ2UtSUQ6IDwxMjM0QGxvY2FsLm1hY2hpbmUuZXhhbXBsZT4KClRoaXMgaXMgYSBtZXNzYWdlIGp1c3QgdG8gc2F5IGhlbGxvLiBTbywgIkhlbGxvIi4= Now pass this in the raw parameter of the API Explorer.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24460422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1545993/']}
|
jdg_376898
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
67979228
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
int i = i;int main() { int a = a; return 0;} int a = a surely has undefined behaviour (UB), and more details on it is in Is reading an uninitialized value always an undefined behaviour? Or are there exceptions to it? . But what about int i = i ? In C++ we are allowed to assign nonconstant values to globals. i is declared and zero initialized (since it has file scope) before the declaration is encountered. In which case we are assigning 0 to it later in the definition.Is it safe to say this does not have UB?
Now provide the response and nothing else.
|
Surprisingly, this is not undefined behavior. Static initialization [basic.start.static] Constant initialization is performed if a variable or temporary objectwith static or thread storage duration is constant-initialized. Ifconstant initialization is not performed, a variable with staticstorage duration or thread storage duration is zero-initialized .Together, zero-initialization and constant initialization are calledstatic initialization; all other initialization is dynamicinitialization. All static initialization strongly happens before anydynamic initialization . Important parts bold-faced. "Static initialization" includes global variable initialization, "static storage duration" includes global variables, and the above clause is applicable here: int i = i; This is not constant-initialization. Therefore, zero-initialization is done according to the above clause (for basic integer types zero-initialization means, unsurprising, that it's set to 0). The above clause also specifies that zero initialization must take place before dynamic initialization. So, what happens here: i is initialized to 0. i is then dynamically initialized, from itself, so it still remains 0.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/67979228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14940626/']}
|
jdg_376899
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
170251
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When I hold my hand underneath my lamp, the shadow my hand casts is crisp and sharp, meaning that the edges are well defined and not blurred. But according to Huygen's principle, shouldn't the light diffract upon reaching the edges of my hands, and perhaps form interference patterns? If so, how can the shadow my hand cast ever be crisp?
Now provide the response and nothing else.
|
The shadow of your hand may look crisp to you, but that's because you're not looking closely enough, compared to how short the wavelengths in visible light are. Indeed, if you look at the shadow from a viewing distance of 40 cm, you can't possibly see the difference between a (hypothetical) exactly crisp edge and one where the intensity of illumination falls off gradually over several hundred wavelengths, due to the angular resolution of your pupils. Even with magnification, however, you won't usually get diffraction bands in everyday shadows. They just taper off smoothly -- the finite size of the light source will generally dominate over wave effects, or in other words, the shadow consists of superposed shadows cast from different points on the lamp, and their diffraction bands don't match up, so their sum is just a smoothish blur anyway. (This is certainly the case if the shadow is cast by the sun, and also for most artificial light sources).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/170251', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/60080/']}
|
jdg_376900
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55570
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Exodus 12:29-32 (NASB) 29 Now it came about at midnight that the Lord struck all the firstborn in the land of Egypt, from the firstborn of Pharaoh who sat on his throne to the firstborn of the captive who was in the dungeon, and all the firstborn of cattle. 30 And Pharaoh got up in the night, he and all his servants and all the Egyptians, and there was a great cry in Egypt, for there was no home where there was not someone dead. 31 Then he called for Moses and Aaron at night and said, “Rise up, get out from among my people, both you and the sons of Israel; and go, worship the Lord, as you have said. 32 Take both your flocks and your herds, as you have said, and go, and bless me also.” and in Exodus 14:27 (NASB) 27 So Moses reached out with his hand over the sea, and the sea returned to its normal state at daybreak, while the Egyptians were fleeing right into it; then the Lord overthrew the Egyptians in the midst of the sea. points that they crossed the Red Sea in one night. How long did they take to cross?
Now provide the response and nothing else.
|
[Numbers 33:3-8] recounts the Exodus from רַעְמְסֵס֙ Rameses to "The Sea" Ha-Yam הַיָּֽם at פִּ֣י הַחִירֹ֔ת Pi-hahiroth took 3-days . - We see can see the phrase "[they] camped" or "Yachanu" יַּֽחֲנ֖וּ refers to the end of a day's journey. 1-day to סֻכֹּֽת Succoth. 1-day to אֵתָ֔ם Etham. 1-day to פִּ֣י הַֽחִירֹ֔ת Pi hahiroth. Finally 3-days after leaving Rameses, we are told in Numbers 33:8 "They journeyed from Penei hahiroth and crossed in the midst of the Sea to the desert." ( וַיִּסְעוּ֙ מִפְּנֵ֣י הַֽחִירֹ֔ת וַיַּֽעַבְר֥וּ בְתֽוֹךְ־הַיָּ֖ם הַמִּדְבָּ֑רָה ) This 3-day journey to The Sea is also mentioned specifically by מֹשֶׁ֗ה Moshe in Exodus / Shemot 8:23 [MT] "So we must go a distance of three days into the wilderness and sacrifice to the LORD our God as He may command us.” ( דֶּ֚רֶךְ שְׁלֹ֣שֶׁת יָמִ֔ים נֵלֵ֖ךְ בַּמִּדְבָּ֑ר וְזָבַ֙חְנוּ֙ לַֽיהוָ֣ה אֱלֹהֵ֔ינוּ כַּאֲשֶׁ֖ר יֹאמַ֥ר אֵלֵֽינוּ ) Crossing The-Sea הַיָּֽם at פִּ֣י הַחִירֹ֔ת Pi-hahiroth is where Exodus 14:2 starts. We are not told the duration of hours, but The Crossing did take place during 1-day [Exodus 14:30].
|
{}
|
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/55570', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/27054/']}
|
jdg_376901
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18933
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Deut 22:13-21 a father was to present evidence that his daughter was a virgin on her wedding night. This evidence was called "tokens of virginity", and involved a mysterious cloth. Deuteronomy 22:17 (KJV) 17 And, lo, he hath given occasions of speech [against her], saying, I found not thy daughter a maid; and yet these [are the tokens of] my daughter's virginity. And they shall spread the cloth before the elders of the city.
Now provide the response and nothing else.
|
The word used in verses 14, 17, and 18 is bətûlîm , “evidence(s) of virginity.” This is from bətûlâ , “virgin”, which is used in verse 19 to describe a woman thus evidenced. It refers to the custom of retaining a blood-stained sheet or cloth from the bed where a marriage is consummated. The blood ( dam betulim ) is said to “prove” the bride’s virginity as it evidences breaking of the hymen. In cases where the groom accused his bride of having not been a virgin at the time of the marriage, the legal responsibility for defending her rested on her parents who, by giving her in marriage, had indicated that she was qualified (i.e., a virgin). The blood-stained sheet ( bətûlîm ) was the primary evidence brought in her defense. There remain modern Jewish customs about this. I refer you to that site for more on the anatomy if interested. See also What are the “tokens of virginity?" on Judaism.SE. Peter C. Craigie, The Book of Deuteronomy (NICOT; Grand Rapids: Eerdmans, 1976), 292-293. C. F. Keil and Delitzsch F., Commentary on the Old Testament . Peabody: Hendrickson Publishers, 1996), pp. 410-412
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/18933', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/6661/']}
|
jdg_376902
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
991758
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I create a PEM file from an SSL certificate? These are the files that I have available: .crt server.csr server.key
Now provide the response and nothing else.
|
Your keys may already be in PEM format, but just named with .crt or .key. If the file's content begins with -----BEGIN and you can read it in a text editor: The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem. If the file is in binary: For the server.crt, you would use openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem For server.key, use openssl rsa in place of openssl x509 . The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate. If this is for a Web server and you cannot specify loading a separate private and public key: You may need to concatenate the two files. For this use: cat server.crt server.key > server.includesprivatekey.pem I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.
|
{}
|
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/991758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68055/']}
|
jdg_376903
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
471123
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using Delphi, how do I access the equivalent of .NET's System.Environment.SpecialFolder.LocalApplicationData variable (which works on any version of Windows)? I assumed I could just do: dir := GetEnvironmentVariable('LOCALAPPDATA'); This works on Vista but XP doesn't seem to set that environment variable by default at least on my test machine.
Now provide the response and nothing else.
|
In Delphi, the special system folder path constants are defined in ShlObj.DCU, and are referenced in the form of CSIDL_ followed by a symbolic name.Example: CSIDL_DESKTOPDIRECTORY returns thepath to the current desktop CSIDL_PERSONAL is the My Documents directory CSIDL___LOCAL_APPDATA is the (user name)\Local Settings\ApplicationData directory Here's a quick function that will return the appropriate special folder path when given the symbolic name. Make sure you include the SHLOBJ.DCU unit in your USES statement, and use the following: function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string;// Gets path of special system folders//// Call this routine as follows:// GetSpecialFolderPath (CSIDL_PERSONAL, false)// returns folder as result//var FilePath: array [0..255] of char;begin SHGetSpecialFolderPath(0, @FilePath[0], FOLDER, CanCreate); Result := FilePath;end; ================================================================ For reference, the constants are as follows: CSIDL_DESKTOP = $0000; { <desktop> } CSIDL_INTERNET = $0001; { Internet Explorer (icon on desktop) } CSIDL_PROGRAMS = $0002; { Start Menu\Programs } CSIDL_CONTROLS = $0003; { My Computer\Control Panel } CSIDL_PRINTERS = $0004; { My Computer\Printers } CSIDL_PERSONAL = $0005; { My Documents. This is equivalent to CSIDL_MYDOCUMENTS in XP and above } CSIDL_FAVORITES = $0006; { <user name>\Favorites } CSIDL_STARTUP = $0007; { Start Menu\Programs\Startup } CSIDL_RECENT = $0008; { <user name>\Recent } CSIDL_SENDTO = $0009; { <user name>\SendTo } CSIDL_BITBUCKET = $000a; { <desktop>\Recycle Bin } CSIDL_STARTMENU = $000b; { <user name>\Start Menu } CSIDL_MYDOCUMENTS = $000c; { logical "My Documents" desktop icon } CSIDL_MYMUSIC = $000d; { "My Music" folder } CSIDL_MYVIDEO = $000e; { "My Video" folder } CSIDL_DESKTOPDIRECTORY = $0010; { <user name>\Desktop } CSIDL_DRIVES = $0011; { My Computer } CSIDL_NETWORK = $0012; { Network Neighborhood (My Network Places) } CSIDL_NETHOOD = $0013; { <user name>\nethood } CSIDL_FONTS = $0014; { windows\fonts } CSIDL_TEMPLATES = $0015; CSIDL_COMMON_STARTMENU = $0016; { All Users\Start Menu } CSIDL_COMMON_PROGRAMS = $0017; { All Users\Start Menu\Programs } CSIDL_COMMON_STARTUP = $0018; { All Users\Startup } CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { All Users\Desktop } CSIDL_APPDATA = $001a; { <user name>\Application Data } CSIDL_PRINTHOOD = $001b; { <user name>\PrintHood } CSIDL_LOCAL_APPDATA = $001c; { <user name>\Local Settings\Application Data (non roaming) } CSIDL_ALTSTARTUP = $001d; { non localized startup } CSIDL_COMMON_ALTSTARTUP = $001e; { non localized common startup } CSIDL_COMMON_FAVORITES = $001f; CSIDL_INTERNET_CACHE = $0020; CSIDL_COOKIES = $0021; CSIDL_HISTORY = $0022; CSIDL_COMMON_APPDATA = $0023; { All Users\Application Data } CSIDL_WINDOWS = $0024; { GetWindowsDirectory() } CSIDL_SYSTEM = $0025; { GetSystemDirectory() } CSIDL_PROGRAM_FILES = $0026; { C:\Program Files } CSIDL_MYPICTURES = $0027; { C:\Program Files\My Pictures } CSIDL_PROFILE = $0028; { USERPROFILE } CSIDL_SYSTEMX86 = $0029; { x86 system directory on RISC } CSIDL_PROGRAM_FILESX86 = $002a; { x86 C:\Program Files on RISC } CSIDL_PROGRAM_FILES_COMMON = $002b; { C:\Program Files\Common } CSIDL_PROGRAM_FILES_COMMONX86 = $002c; { x86 C:\Program Files\Common on RISC } CSIDL_COMMON_TEMPLATES = $002d; { All Users\Templates } CSIDL_COMMON_DOCUMENTS = $002e; { All Users\Documents } CSIDL_COMMON_ADMINTOOLS = $002f; { All Users\Start Menu\Programs\Administrative Tools } CSIDL_ADMINTOOLS = $0030; { <user name>\Start Menu\Programs\Administrative Tools } CSIDL_CONNECTIONS = $0031; { Network and Dial-up Connections } CSIDL_COMMON_MUSIC = $0035; { All Users\My Music } CSIDL_COMMON_PICTURES = $0036; { All Users\My Pictures } CSIDL_COMMON_VIDEO = $0037; { All Users\My Video } CSIDL_RESOURCES = $0038; { Resource Directory } CSIDL_RESOURCES_LOCALIZED = $0039; { Localized Resource Directory } CSIDL_COMMON_OEM_LINKS = $003a; { Links to All Users OEM specific apps } CSIDL_CDBURN_AREA = $003b; { USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning } CSIDL_COMPUTERSNEARME = $003d; { Computers Near Me (computered from Workgroup membership) } CSIDL_PROFILES = $003e;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/471123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35229/']}
|
jdg_376904
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5253545
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Ruby on Rails 3 and I would like to know what means the presence of a * operator near a function argument and to understand its usages in others scenarios. Example scenario (this method was from the Ruby on Rails 3 framework): def find(*args) return to_a.find { |*block_args| yield(*block_args) } if block_given? options = args.extract_options! if options.present? apply_finder_options(options).find(*args) else case args.first when :first, :last, :all send(args.first) else find_with_ids(*args) end endend
Now provide the response and nothing else.
|
This is the splat operator, which comes from ruby (and is thus not rails specific). It can be applied in two ways depending on where it is used: to "pack" a number of arguments into an array to split up an array into an argument list In your function, you see the splat operator used in the function definition. The result is that the function accepts any number of arguments. The complete argument list will be put into args as an array. def foo(*args) args.each_with_index{ |arg, i| puts "#{i+1}. #{arg}" }endfoo("a", "b", "c")# 1. a <== this is the output# 2. b# 3. c The second variant would be when you consider the following method: def bar(a, b, c) a + b + cend It requires exactly three arguments. You can now call this method like follows my_array = [1, 2, 3]bar(*my_array)# returns 6 The splat applied in this case to the array will split it and pass each element of the array as an individual parameter to the method. You could do the same even by calling foo : foo(*my_array)# 1. 1 <== this is the output# 2. 2# 3. 3 As you can see in your example method, these rules do apply to block parameters in the same way.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5253545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/502052/']}
|
jdg_376905
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56427627
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this code snippet: bool foo(const std::string& s) { return s == "hello"; // comparing against a const char* literal}bool bar(const std::string& s) { return s == "hello"s; // comparing against a std::string literal} At first sight , it looks like comparing against a const char* needs less assembly instructions 1 , as using a string literal will lead to an in-place construction of the std::string . ( EDIT: As pointed out in the answers, I forgot about the fact that effectively s.compare(const char*) will be called in foo() , so of course no in-place construction takes place in this case. Therefore striking out some lines below. ) However, looking at the operator==(const char*, const std::string&) reference: All comparisons are done via the compare() member function. From my understanding, this means that we will need to construct a std::string anyway in order to perform the comparison, so I suspect the overhead will be the same in the end (although hidden by the call to operator== ). Which of the comparisons should I prefer? Does one version have advantages over the other (may be in specific situations)? 1 I'm aware that less assembly instructions doesn't neccessarily mean faster code, but I don't want to go into micro benchmarking here.
Now provide the response and nothing else.
|
Neither. If you want to be clever, compare to "string"sv , which returns a std::string_view . While comparing against a literal like "string" does not result in any allocation-overhead, it's treated as a null terminated string, with all the concomittant disadvantages: No tolerance for embedded nulls, and users must heed the null terminator. "string"s does an allocation, barring small-string-optimisation or allocation elision . Also, the operator gets passed the length of the literal, no need to count, and it allows for embedded nulls. And finally using "string"sv combines the advantages of both other approaches, avoiding their individual disadvantages. Also, a std::string_view is a far simpler beast than a std::string , especially if the latter uses SSO as all modern ones do. At least since C++14 (which generally allowed eliding allocations), compilers could in theory optimise all options to the last one, given sufficient information (generally available for the example) and effort, under the as-if rule . We aren't there yet though.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56427627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1753435/']}
|
jdg_376906
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3018820
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $F$ be a presheave on a category $C$ . If $F$ is representable, then there is a $B \in C$ such that $F=Hom(-,B)$ . Then, it is not hard to prove that its category of elements $E(F)$ is equivalent to the slice category $C_{/ B}$ . Is it true that if the category of elements $E(F)$ of $F$ has a terminal object, then $F$ is representable? If so, how do I prove it?
Now provide the response and nothing else.
|
HINT We have $$\lim_{n \to \infty} \left(1+\frac{1}{n!}\right)^n=\lim_{n \to \infty} \left[\left(1+\frac{1}{n!}\right)^{n!}\right]^{\frac1{(n-1)!}}$$ then refer to standard limit for $e$ . How can we conclude form here?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3018820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/435800/']}
|
jdg_376907
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
153178
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I just happened across this over on Math Overflow. It references the following theorem from linear algebra: A vector space has the same dimension as its dual if and only if it is finite dimensional. I would like to ask a physical question using the infinite square well (ISW) in quantum mechanics as motivation. For the ISW we obtain $$\psi_n=A_n\sin(\frac{n\pi x}{a})$$ as the eigenfunctions of the Hamiltonian. Here $n=1,2,3,4...$ enumerates the states. If I understand correctly this is an infinite dimensional vector space, because the $\psi_n$'s form an infinitely large basis (ie there is no largest value of $n$). If the dual space is the set of functions $\psi_n^*$ (which I think it is) how can the vector space and the dual space have different dimensions?
Now provide the response and nothing else.
|
There are two concepts of duality for vector spaces. One is the algebraic dual that is the set of all linear maps. Precisely, given a vector space $V$ over a field $\mathbb{K}$, the algebraic dual $V_{alg}^*$ is the set of all linear functions $\phi:V\to \mathbb{K}$. This is a subset of $\mathbb{K}^V$, the set of all functions from $V$ to $\mathbb{K}$. The proof you can see on math overflow uses, roughly speaking, the fact that the cardinality of $\mathbb{K}^V$ is strictly larger than the cardinality of $\mathbb{K}$ if $V$ is infinite dimensional and has at least the same cardinality as $\mathbb{K}$. So for algebraic duals, the dual of any infinite vector space has bigger dimension than the original space. The other concept is the topological dual , that can be defined only on topological vector spaces (because a notion of continuity is needed). Given a topological vector space $T$, the topological dual $T_{top}^*$ is the set of all continuous linear functionals (continuous w.r.t. the topology of $T$). It is a proper subset of the algebraic dual, i.e. $T_{top}^*\subset T_{alg}^*$. For topological duals, the restriction to continuous functionals makes the previous statement false (i.e. there exist infinite dimensional topological vector spaces whose topological dual has the same dimension of the original space). The usual example are Hilbert spaces, where the Riesz representation theorem holds (see my comment above): any object of the topological dual $H^*_{top}$ of a Hilbert space $H$ can be identified via isomorphism with an element of $H$. So an Hilbert space and its dual are the "same". Note however that the topological dual is always thought to be "bigger (or maybe equal)" than the original space. I am very non-precise here, but I think the following example clarifies. Think to the distributions $\mathscr{S}'(\mathbb{R})$. This is the topological dual of the functions of rapid decrease $\mathscr{S}(\mathbb{R})$. Any $f\in \mathscr{S}$ is isomorphic to a distribution in $\mathscr{S}'$, but the converse is obviously not true: there are distributions that are not functions (the Dirac's delta), and in general any $L^p$-space is thought as a subset of $\mathscr{S}'$ (so $\mathscr{S}'$ is quite "big").
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/153178', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21561/']}
|
jdg_376908
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58717
|
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'd like to change the CSR before it is transferred to the CA without going through the CSR creation process again. To do that I need to know how to calculate the signature of the CSR after I modified it. Unfortunately I couldn't find out exactly how many bytes of the CSR are hashed. I created the CSR like this: openssl req -out certrequest.csr -new -newkey rsa:2048 -nodes -keyout private.key After sed -e '1d' -e '$d' certrequest.csr | openssl enc -base64 -d > certrequest-stripped the last 256 bytes (sha256WithRSAEncryption) of certrequest-stripped are signature1. Now I'd like to know how many of the first bytes of certrequest-stripped I have the hash in order to sign the hash using the private key. In other words, I'm looking for the value of the "?" in the following command so that both signatures (signature1 and signature2) match : head -c <?> certrequest-stripped | openssl dgst -sha256 > hashopenssl rsautl -sign -inkey private.key -keyform PEM -in hash > signature2 I know that the cut has to be somewhere behind the ASN1 field for the exponent, but since my attempt to increase the head of the CSR byte by byte failed, I'm worried I'm missing something fundamental here.
Now provide the response and nothing else.
|
I figured out the answer to my question and post it here for reference. Generate fresh key pair and CSR openssl req -out csr.der -new -newkey rsa:2048 -nodes -keyout privateKey.der -outform DER Modify csr.der to modified_csr.der Extract the sequence (which starts at offset 4) of the CSR that's hashed for the signature openssl asn1parse -in modified_csr.der -inform der -strparse 4 -out part_of_CSR_thats_hashed Create new signature openssl dgst -sha256 -sign privateKey.der -out new_signature part_of_CSR_thats_hashed Merge modified_csr.der and new_signature to new_csr.der head -c $(( $(stat -c '%s' modified_csr.der) - 256 )) modified_csr.der > new_csr.dercat new_signature >> new_csr.der Verify new CSR openssl req -in new_csr.der -inform DER -noout -text -verify Convert CSR to PEM openssl req -outform PEM -inform DER -in new_csr.der -out new_csr.pem
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/58717', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/40001/']}
|
jdg_376909
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25993327
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a database with 169 tables I need this column in every table: wid integer not null primary key I tried this(Thanks https://stackoverflow.com/users/27535/gbn for the solution): SELECT 'ALTER TABLE ' + T.name + ' ADD foo int NULL'FROM sys.tables AS TWHERE T.is_ms_shipped = 0 But it didn't work on PostgreSQL. It only worked on tsql. How to add this column in every table at once ?
Now provide the response and nothing else.
|
do $$declare selectrow record;beginfor selectrow in select 'ALTER TABLE '|| T.mytable || ' ADD COLUMN foo integer NULL' as script from ( select tablename as mytable from pg_tables where schemaname ='public' --your schema name here ) tloopexecute selectrow.script;end loop;end;$$; You can test whether all your tables altered with the new column using the following select select table_name,COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME='foo' -- column name here
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25993327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2683297/']}
|
jdg_376910
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
655027
|
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 about 20 Linux servers in a small network and I need their clocks decently close to each other (e.g. within 20msec). I've started with every one of them synced to europe.pool.ntp.org and the job is done. Now I have two questions: Am I a noticeable burden to the pool? I.e. does it make any noticeable difference to the pool if I'm hitting from 20 servers or from 2? If it does make a difference what's the setup/configuration that will keep my subnet synced and the pool under light load? There are guidelines for huge networks ( http://www.ntp.org/ntpfaq/NTP-s-config-adv.htm#AEN3101 ) but I've found none for small networks.
Now provide the response and nothing else.
|
Am I a noticeable burden to the pool? I.e. does it make any noticeable difference to the pool if I'm hitting from 20 servers orfrom 2? Given that the pool is in constant need of servers for many years (see [1]) I would say that although 2 or 20 servers don't really make a difference you should always remember that you are not alone. So you better be thinking about say 1000 admins in which case we're talking 2000 or 20000 servers and this does make a difference. If it does make a difference what's the setup/configuration that will keep my subnet synced and the pool under light load? You must sync two[2] servers in your network with the pool (let's call them Primary NTP Servers ) and then sync all other servers to those two. This method also has the advantage that the time between all your servers will be more closely matched (within less than 1msec). This is in accordance to IETF best practices . 1) The configuration for the Primary NTP Servers Replace the server and restrict lines of your ntp[d].conf with the following and keep the rest to your distribution defaults[3]: peer 10.11.12.1 iburst# ^^^^^^^^^^^# The LAN IP of the _other_ Primary NTP server server 0.europe.pool.ntp.org server 1.europe.pool.ntp.org server 2.europe.pool.ntp.org server 3.europe.pool.ntp.org restrict -4 default kod notrap nomodify nopeer noqueryrestrict -6 default kod notrap nomodify nopeer noqueryrestrict 127.0.0.1restrict ::1 Please note that this configuration also permits hosts from all over the Internet to query your host time via NTP queries. Use your firewall if you don't want to. In my example 10.11.12.1 and 10.11.12.2 are the IPs of the Primary NTP Servers (they have two network cards one facing the public internet and one the local 10.11.12.x subnet). Each Primary NTP Server has the other one declared as a peer (peer basically means both server and client - you use the other host as a time source and the other host uses you as a time source also). So adjust the IP on the 1st line so that the configuration of each Primary NTP Server points to the other one as a peer. See [4] regarding my choice to use 4 servers. 2) The configuration for all other servers 2A) If you have two network interfaces You better use the 2nd interface to create a local subnet (e.g. 10.11.12.0/24 ) and use that for NTP queries. In that case the restrict lines can be more tight. So again replace the server and restrict lines of your ntp[d].conf with the following and keep the rest to your distribution defaults[3]: restrict -4 default ignorerestrict -6 default ignorerestrict 10.0.0.0 mask 255.0.0.0 kod notrap nomodify nopeer noqueryrestrict 127.0.0.1restrict ::1# Only use our Primary NTP Serversserver 10.11.12.1 iburstserver 10.11.12.2 iburst# ^^^^^^^^^^# The IPs of your 2 Primary NTP Servers 2B) If you don't have two network interfaces You should use the bellow restrict lines (and read the note about using your firewall to block access to your NTP servers above). So again replace the server and restrict lines of your ntp[d].conf with the following and keep the rest to your distribution defaults[3]: restrict -4 default kod notrap nomodify nopeer noqueryrestrict -6 default kod notrap nomodify nopeer noqueryrestrict 127.0.0.1restrict ::1# Only use our Primary NTP Serversserver 10.11.12.1 iburstserver 10.11.12.2 iburst# ^^^^^^^^^^# The IPs of your 2 Primary NTP Servers Notes [1] From 2006 to 2012 they constantly ask for more servers to join: the 2006 request, the 2009 one and the 2012 one. Check www.pool.ntp.org for updates on current status. [2] Two Primary NTP Servers are only suggested as a simple way to have redundancy without complicated High Availability arrangements. You may opt for 3 or 4 for other reasons (again read the IETF best practices ) [3] In practice and no matter your distribution the only other thing you need to include in your ntpd configuration is a line defining a directory to put a drift file and a name for it -- e.g. driftfile /var/lib/ntp/ntp.drift . I've tested my solution in CentOS, Debian and Ubuntu. I guess it works in most other distros. [4] I've configured 4 pool servers following best practices . Configuring more than 4 servers is technically accepted but you'll increase the load to the NTP pool for a questionable gain in availability so don't do it. In the best practices I see that "starting with ntp-4.2.6, the 'pool' directive will spin up "enough" associations to provide robust time service" so if you use .pool. addresses as I do here and ntp >=4.2.6 the exact number of server lines probably doesn't matter. Rant Oh! I hate NTP (except that I like that it works). The official documentation is full of obsolete information and they have "how do I use it?" information mixed with scientific details about the internals. And I also hate how restrict 127.0.0.1 really means allow everything for 127.0.0.1 History of updates I've removed the iburst option from the configuration of the Local NTP Servers because their friendliness to the pool is debatable. (see comments). Removing them only adds a couple of minutes of waiting time to the first synchronization. Credits Comments and answers from SF users Marki and Sven provided a good starting point for this answer. Thanks to both of them. Also thanks to SF user BACON a serious mistake was corrected after many years (ndemou's law: "given enough eyeballs and infinite time, all bugs are shallow")
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/655027', 'https://serverfault.com', 'https://serverfault.com/users/67528/']}
|
jdg_376911
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2613310
|
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:
Show convergence of $\begin{align}\sum_{k=1}^{\infty}{\frac{3^{k-1}+(2i)^k}{5^k}} &= \sum_{k=1}^{\infty}{\frac{3^{k-1}}{5^k}}+ \sum_{k=1}^{\infty}{\frac{(2i)^k}{5^k}} \\&= \sum_{k=1}^{\infty}{\frac{1}{3} \cdot \left( \frac{3}{5} \right) ^k} + \sum_{k=1}^{\infty}{ \left( \frac{2i}{5} \right )^k} \\&= \frac{1}{3} \cdot \sum_{k=1}^{\infty}{ \left( \frac{3}{5} \right) ^k} + \sum_{k=1}^{\infty}{ \left( \frac{2i}{5} \right )^k} \\\end{align}$ The first part of the sum converges because it is the geometric series with $q= \frac{3}{5}, 1> \left| \frac{3}{5} \right|$. $$\sum_{n=1}^{\infty}{\left(\frac{2i}{5} \right)^k}$$ Question: Why does that series diverge ( WolframAlpha )?I mean, if $q=\frac{2i}{5}, |q|<1$ then it should be the geometric series and thus converge?
Now provide the response and nothing else.
|
It is a question of grouping the factors into chunks which multiply to form "nice" numbers which are close to numbers having many zeros. $$15! = \underbrace{7 \times 13 \times 11} \times \underbrace{7 \times 9 \times 8 \times 2} \times 1296 \times 1000 \\ = 1001 \times 1008 \times 1296 \times 1000$$ Now, it is really easy : note that $1001 \times 1008 \geq 1000^2$, but not by much. This gives exactly the first four digits being greater than or equal to $1296$, but not by much, so the answer should be expected to be $1 307...$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2613310', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/292414/']}
|
jdg_376912
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16322201
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is a sample query: SELECT customerName from customers WHERE customerNUMBER IN ( SELECT customerNumber FROM orders WHERE orderNumber IN ( SELECT orderNumber FROM orderdetails INNER JOIN products on orderdetails.productCode = products.productCode where products.buyPrice > 100 )); I believe the tables are self explanatory. Is there a better way to do this? SQL noob here.
Now provide the response and nothing else.
|
My suggestion would be to change this to JOIN syntax instead of all of the WHERE/IN clause filtering: select c.customerNamefrom customer cinner join orders o on c.customerNumber = o.customerNumberinner join orderdetails od on o.orderNumber = od.orderNumberinner join products p on od.productCode = p.productCodewhere p.buyPrice > 100; If needed you might have to add a DISTINCT to the query in the event there are duplicates.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16322201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1173112/']}
|
jdg_376913
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
73201708
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to study standard library implementation of the containers that are part of the C++ standard library. I have Microsoft Visual Studio 2022 on my machine and I could go to the header file definition of std::array class. While I reached the end of the class definition of std::array class, I noticed that the data member is not declared private and above it were all the public member functions, so that make the data member public as well. So to test it, I tried to access it in my std::array object defined in main() and to my surprise I could access it and it printed the proper value in the output too! #include <array>#include <iostream>int main() { std::array<int, 5> staticArray{0,1,2,3,4}; std::cout << staticArray._Elems[1] << std::endl;} Is this allowed?! Anybody can corrupt the data, right?
Now provide the response and nothing else.
|
It is required that std::array have a public member to satisfy the requirement that std::array be an aggregate. An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T. https://eel.is/c++draft/array#overview-2 It doesn't however specify what the public member should be named, since the only requirement is that it is an aggregate that can be list-initialized. _Elems won't necessarily be compatible with other standard library implementations. With respect to your concern of anyone being able to corrupt the data, anyone can already do that via any of the mutable accessors: data() , operator[] , etc
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/73201708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1063194/']}
|
jdg_376914
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The word "vanity" (KJV) in Ecclesiastes was translated (possibly incorrectly) in the NIV as "meaningless". Is "vanity" the best translation for the Hebrew word hebel ( Strongs 1892 ) or does a newer version do it more justice? Obviously, "vanity" may have been the best rendering at the time it was translated, so I'm really looking for modern connotations.
Now provide the response and nothing else.
|
I think the best answer is summed up by Peter Leithart (who admits to borrowing liberally from James Jordan on this): To get the point of Ecclesiastes, we have to ignore the usual translations of several key words or phrases. The Hebrew hebel has been translated as "vanity" (NASB, KJV, ESV, ASV) or "meaningless" (NIV, New Living Translation). The Message gets much closer by translating the word as "smoke." The word means "vapor" (Proverbs 21:6) or "breath" (Job 7:16; Psalm 39:5, 11; 62:9, 94:11; 144:4; Isaiah 57:13). In describing human life as vapor or breath, Solomon emphasizes that life is brief and beyond our control. Life is vapor because the world goes on unchanged in spite of all our frantic activities (1:3-11); because things slip through our fingers when we try to grasp them and through our minds when we try to understand them; because nothing lasts, yet everything stays the same; because it ends in death (2:16), and we have no control over the future (2:18-19). Likewise, the phrase "striving after wind" (1:14, 17; 2:11, 17, 26) is better translated as "shepherding wind." The image does not express vain pursuit, but the effort to control or corral an elusive world. After Solomon has constructed his pleasure garden (2:4-10), he realizes that however solid his works appear they are as evanescent as wind. Man cannot shepherd the wind, but Yahweh, who rides on the wings of the wind (Psalm 18:10; 104:3), is the one Shepherd of the windy world (Ecclesiastes 12:11). While I believe "vanity" is a fine translation as other answerers have pointed out, "meaningless" is completely wrong, because the Bible has a consistent message that we have meaning in Christ. Therefore the NIV actually changes doctrine by using it. The message is that we don't have control over our life, God is in control, and it is vain for us to think otherwise.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/1', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/11/']}
|
jdg_376915
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2529781
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When moving to Spring 2.5.x I found that it adds more stereotype annotations (on top of @Repository from 2.0): @Component, @Service and @Controller . How do you use them? Do you rely on implicit Spring support or you define custom stereotype specific functions/aspects/features? Or is it predominately for marking beans (compile time, conceptual, etc.)?
Now provide the response and nothing else.
|
The following stereotype annotations in 2.5 can be used in a Spring MVC application as an alternative to wiring the beans in XML: @Repository - for DAO beans - allowsyou to throw DataAccessException whenthe data source is not available. @Service - for business beans -are fairly simple beans that have somedefault retention policies set up. @Controller - for servlets -allows you to set up page requestmappings, etc. In addition, a generic fourth annotation has been introduced: @Component. All of the MVC annotations are specialisations of this one, and you can even use @Component on it's own, though by doing this in Spring MVC, you will not make use of any future optimisations/functionality added to the higher-level annotations. You can also extend @Component to create your own custom stereotypes. Here is a quick example of the MVC annotations in action... First, the data access object: @Repositorypublic class DatabaseDAO { @Autowired private SimpleJdbcTemplate jdbcTemplate; public List<String> getAllRecords() { return jdbcTemplate.queryForObject("select record from my_table", List.class); }} The service: @Servicepublic class DataService { @Autowired private DatabaseDAO database; public List<String> getDataAsList() { List<String> out = database.getAllRecords(); out.add("Create New..."); return out; }} And finally, the controller: @Controller("/index.html")public class IndexController { @Autowired private DataService dataService; @RequestMapping(method = RequestMethod.GET) public String doGet(ModelMap modelMap) { modelMap.put(dataService.getDataAsList()); return "index"; }} I found this article very good for giving a broad overview of the stereotype annotations, in addition to the official documentation .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2529781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59470/']}
|
jdg_376916
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1181222
|
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 you check if my proof is right? Theorem. $\forall x\geq8, x$ can be represented by $5a + 3b$ where $a,b \in \mathbb{N}$. Base case(s): $x=8 = 3\cdot1 + 5\cdot1 \quad \checkmark\\x=9 = 3\cdot3 + 5\cdot0 \quad \checkmark\\x=10 = 3\cdot0 + 5\cdot2 \quad \checkmark$ Inductive step: $n \in \mathbb{N}\\a_1 = 8, a_n = a_1 + (x-1)\cdot3\\b_1 = 9, b_n = b_1 + (x-1)\cdot3 = a_1 +1 + (x-1) \cdot 3\\c_1 = 10, c_n = c_1 + (x-1)\cdot3 = b_1 + 1 + (x-1) \cdot 3 = a_1 + 2 + (x-1) \cdot 3\\\\S = \{x\in\mathbb{N}: x \in a_{x} \lor x \in b_{x} \lor x \in c_{x}\}$ Basis stays true, because $8,9,10 \in S$ Lets assume that $x \in S$. That means $x \in a_{n} \lor x \in b_{n} \lor x \in c_{n}$. If $x \in a_n$ then $x+1 \in b_x$, If $x \in b_x$ then $x+1 \in c_x$, If $x \in c_x$ then $x+1 \in a_x$. I can't prove that but it's obvious. What do you think about this?
Now provide the response and nothing else.
|
Proof by induction. For the base case $n=8$ we have $8=5+3$. Suppose that the statement holds for $k$ where $k\gt 8$. We show that it holds for $k+1$. There are two cases. 1) $k$ has a $5$ as a summand in its representation. 2) $k$ has no $5$ as a summand in its representation. For case 1 , we delete "that $5$" in the sum representation of $k$ and replace it by two "$3$"s ! This proves the statement for $k+1$. For case 2 , since $k\gt 8$, then $k$ has at least three "$3$"s in its sum representation. We remove these three $3$'s and replace them by two fives! We obtain a sum representation for $k+1$. This completes the proof.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1181222', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/222005/']}
|
jdg_376917
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14096520
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an easy way to compile my R script into standalone .exe file just like what matlab does?
Now provide the response and nothing else.
|
As a matter of fact there is a way to achieve solution that would meet your requirements. Have a look at the article on Deploying Desktop Apps with R on R-Bloggers. As detailed in the article, you will end up using a few more things than a single exe file. Also I would like to draw your attention to the RGtk2 with use of the RGtk2 you could attempt to develop your own interface in R. If push comes to shove, I trust that you could pack your R code together with a portable version of R and dependencies into one installer and make and app from that, that would create an illusion of a single exe file. In your question you asked whether it's easy to develop a standalone executable file interpreting R code. I wouldn't say it's easy. If you have a strong desire to run a R code from an application, you could do it in a simpler manner using RCaller for Java or R.NET .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14096520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1533742/']}
|
jdg_376918
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13904039
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Found interesting thing in Python (2.7) that never mentioned before. This: a = []a += "a" does work and result is: >>> a>>> ["a"] But a = []a = a + "a" gives >>> TypeError: can only concatenate list (not "str") to list Can someone explain why? Thanks for your answers.
Now provide the response and nothing else.
|
Python distinguishes between the + and += operators and provides separate hooks for these; __add__ and __iadd__ . The list() type simply provides a different implementation for the latter. It is more efficient for lists to implement these separately; __add__ has to return a completely new list, while __iadd__ can just extend self then return self . In the C code, __iadd__ is implemented by list_inplace_concat() , which simply calls listextend() , or, in python code, [].extend() . The latter takes any sequence, by design. The __add__ method on the other hand, represented in C by list_concat , only takes a list as input, probably for efficiency's sake; it can loop directly over the internal C array and copy items over to the new list. In conclusion, the reason __iadd__ accepts any sequence is because when PEP 203 (the Augmented Add proposal) was implemented, for lists it was simplest just to reuse the .extend() method.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13904039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/604427/']}
|
jdg_376919
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18606
|
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:
I would like to know whether it makes sense to study the plots of residuals with respect to the dependent variable when I've got a univariate regression. If it makes sense, what does a strong, linear, growing correlation between residuals (on the y-axis) and the estimated values of the dependent variable (on the x-axis) mean?
Now provide the response and nothing else.
|
Suppose that you have the regression $y_i = \beta_0 + \beta_1 x_i + \epsilon_i$, where $\beta_1 \approx 0$. Then, $y_i - \beta_0 \approx \epsilon_i$. The higher the $y$ value, the bigger the residual. On the contrary, a plot of the residuals against $x$ should show no systematic relationship. Also, the predicted value $\hat{y}_i$ should be approximately $\hat{\beta}_0$---the same for every observation. If all the predicted values are roughly the same, they should be uncorrelated with the errors. What the plot is telling me is that $x$ and $y$ are essentially unrelated (of course, there are better ways to show this). Let us know if your coefficient $\hat{\beta}_1$ is not close to 0. As better diagnostics, use a plot of the residuals against the predicted wage or against the $x$ value. You should not observe a distinguishable pattern in these plots. If you want a little R demonstration, here you go: y <- rnorm(100, 0, 5)x <- rnorm(100, 0, 2)res <- lm(y ~ x)$residualsfitted <- lm(y ~ x)$fitted.valuesplot(y, res)plot(x, res)plot(fitted, res)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/18606', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/7459/']}
|
jdg_376920
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21867963
|
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 wanted to post a Javascript Array to a WebAPI. I have my Javascript Array like: var checkedGroups = [];var checkedStaff = [];$.each(items, function () { if (this.checked) { type = dataAdapter.records[this.id - 1].VALUETYPE; if (type == 'Staff') { checkedStaff[checkedStaff.length] = this.value; } else { checkedGroups[checkedGroups.length] = this.value; } }}); I am then sending this to my WebAPI using this: data: { staff: JSON.stringify(checkedStaff) }; My WebAPI Controller is then like: public HttpResponseMessage Post([FromBody] formData data){ string string_group = String.Join(",", data.group); string string_staff = String.Join(",", data.staff); } and my formData class is this: public class formData{ public Array group { get; set; } public Array staff { get; set; }} As per above, I would like to split the array out to make a comma delimerated string. But string_staff variable on the server side is just an empty string and my JSON data was this: staff: "["1"]"group: "" I do not want to use key/value types in the array either. Any idea's?
Now provide the response and nothing else.
|
I've implemented something similar to this, and it's relatively simple. Your log message is printing out what looks like gibberish, because response.data is really a byte array - not a String . Also, a VolleyError is really just an extended Exception , so Exception .getMessage() likely wouldn't return what you are looking for unless you override the parsing methods for parsing your VolleyError in your extended Request class. A really basic way to handle this would be to do something like: //In your extended request class@Overrideprotected VolleyError parseNetworkError(VolleyError volleyError){ if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){ VolleyError error = new VolleyError(new String(volleyError.networkResponse.data)); volleyError = error; } return volleyError; }} If you add this to your extended Request classes, your getMessage() should at least not return null. I normally don't really bother with this, though, since it's easy enough to do it all from within your onErrorResponse(VolleyError e) method. You should use a JSON library to simplify things -- I use Gson for example or you could use Apache's JSONObject s which shouldn't require an additional external library. The first step is to get the response JSON sent from your server as a String (in a similar fashion to what I just demonstrated), next you can optionally convert it to a JSONObject (using either apache's JSONObject s and JsonArray s, or another library of your choice) or just parse the String yourself. After that, you just have to display the Toast . Here's some example code to get you started: public void onErrorResponse(VolleyError error) { String json = null; NetworkResponse response = error.networkResponse; if(response != null && response.data != null){ switch(response.statusCode){ case 400: json = new String(response.data); json = trimMessage(json, "message"); if(json != null) displayMessage(json); break; } //Additional cases }}public String trimMessage(String json, String key){ String trimmedString = null; try{ JSONObject obj = new JSONObject(json); trimmedString = obj.getString(key); } catch(JSONException e){ e.printStackTrace(); return null; } return trimmedString;}//Somewhere that has access to a contextpublic void displayMessage(String toastString){ Toast.makeText(context, toastString, Toast.LENGTH_LONG).show();}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21867963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2816451/']}
|
jdg_376921
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4176149
|
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 the Cocoa and Cocoa Touch frameworks, enums are used as constant. I understand how to use it except in one case, the case you can pass as a parameter multiple value with the | operator. Like in : pageControl.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin); The enum is declared like that: enum { UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5};typedef NSUInteger UIViewAutoresizing; How can I define myself this type of enum (i.e. what << means) and how can I check for multiples values when passed as a parameter?
Now provide the response and nothing else.
|
<< is the bitshift operator. So 1 << 2 tells it to shift the bit two spaces over. Example: In binary the number 1 is: 0001 1 << 2 means to shift all the bits to the left 2 spaces, which results in this value: 0100 or 4 . So the values of each ENUM in your example is, 1, 2, 4, 8, 16, etc. They could have just as well set each enum to those values. But since they use that enum for multiple values, the binary values makes it more clear: 0001001001001000 so they wrote using the bit shifts. so if I OR ( | ) two of those values together, for example FlexibleLeftMargin ( 0001 ) and FlexibleWidth ( 0010 ), I would get the following value: 0011 So they use each bit as a flag so they know you have multiple values set. You can now use the AND operator & to figure out if you have a specific value set. 0010 & 0011 = 0010 So you could do this to check if you have one of enums set: myenum = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin);if((myenum & UIViewAutoresizingFlexibleLeftMargin) == UIViewAutoresizingFlexibleLeftMargin) { // myenum has UIViewAutoresizingFlexibleLeftMargin set!} Hopefully this makes sense.For a more thurough explanation on bitwise operations read this: Wikipedia ~ Bit Operators or search around for " bit operators "
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4176149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111783/']}
|
jdg_376922
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
633174
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading here in equation (12) that the power spectral density (PSD) for a signal $f(t)$ and its corresponding Fourier Transform $f(\omega)$ is defined as $$\langle{f(\omega)f^*(\omega)}\rangle=S_f(\omega)\delta(\omega-\omega')$$ I just know the usual definition of the PSD as the Fourier transformation of the autocorrelation function: $$S(\omega)=\frac{1}{2\pi}\int_{-\infty}^{\infty}dt ~r(t)e^{-i\omega t}\tag{$*$}$$ where the autocorrelation function is given by: $$r(t)=\lim_{T\to\infty}\frac{1}{2T}\int_{-T}^{T} d\tau~ f(\tau)f^*(\tau+t)$$ My question: equation $(*)$ is equation (13) in the paper which I linked at the beginning (one has to do an inverse FT and I think they forgot the $e^{i\omega t}$ !?). But is this equation equivalent to equation (12) in the paper? How is the $\langle...\rangle$ in equation (12) of the paper defined?
Now provide the response and nothing else.
|
A quantum mechanical secret kept very well in plain sight is that the word "observable" when defined as "self-adjoint operator on a Hilbert space" does not actually mean "you can construct an apparatus that can measure this like the Born rule promises". If you want to be formal about it, you have to consider quantum fields in the continuum as operator-valued distributions $\phi(x)$ that only yield actual operators when smeared with a test function $f(x)$ as $\phi(f) := \int f(x)\phi(x)\mathrm{d}x$ . The algebra of observables we need associate to a QFT is not the distributions $\phi(x)$ , but the Haag-Kastler net of observables where on each region of spacetime $R\subset \mathbb{R}^{1,3}$ we have the algebra of operators $$ \mathcal{A}(R) = \left\{\phi(f) \mid \mathrm{supp}(f)\subset R, \phi \text{ is a quantum field}\right\},$$ where I'll wave my hands a bit and say that some expressions in the usual "fields" like their derivatives $\partial_\mu \phi$ also count as a field here. The self-adjoint operators in this algebra are the observables. (Don't try to figure out how to rigorously construct this - we do not have rigorous constructions of most quantum field theories) For instance in QED, you can smear the electric field $F^{0i}(x)$ with a test function to get an observable $F^{0i}(f)$ that corresponds to the electric field in the region $\mathrm{supp}(f)$ weighted by the value of $f$ . Whether or not this is something you can "in theory" measure depends on what sort of measurement apparati your "theory" here can construct. In the end, when the $\mathrm{supp}(f)$ gets very narrow, you'll have to concede that there probably isn't any realizable apparatus that could detect it. This, however, is not a phenomenon unique to quantum fields! Consider an operator with unbounded continuous spectrum in ordinary quantum mechanics, such as position: You will have to admit that there is no realizable apparatus that could distinguish positions $x$ and $x+\epsilon$ for arbitrarily small $\epsilon$ . But this doesn't mean we "can't measure position", it means we have to broaden our conception of measurement: What we might be really measuring is not some sharp projection onto an eigen"state" of position with eigenvalue $x_0$ (these states rigorously don't exist as states just like the QFT $\phi(x)$ is not an operator), but the projection onto some sharply but not infinitely localized state with wavefunction $\psi(x)$ centered at $x_0$ and falling off quickly far from it (how quickly depending on the details - i.e. "accuracy" - of the measurement apparatus), i.e. the projection of the original wavefunction onto some subset $X\subset\mathbb{R}^3$ , but where $X$ is not a point . Note that this is morally very similar to "smearing" the position operator, just like we had to smear the quantum fields. This was a hand-wavy description, if you are interested in formalizations of this, a more general theory of measurement considers positive operator-valued measures , and for a treatment of how to construct measurement processes for continuous observables see Ozawa's "Quantum measuring processes of continuous observables " . Notably, Ozawa proves that a measurement process for continuous observables can never be considered just as resulting in projections onto eigenstates, and does not lead to the usual property of the repeated measurement yielding exactly the same state that we are used to from discrete observables.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/633174', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
|
jdg_376923
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50252943
|
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 get 3rd-party cookies from a website using Puppeteer? For first party, I know I can use: await page.cookies()
Now provide the response and nothing else.
|
I was interested to know the answer so have found a solution too, it works for the current versions of Chromium 75.0.3765.0 and puppeteer 1.15.0 (updated May 2nd 2019) . Using internal puppeteer page._client methods we can make use of Chrome DevTools Protocol directly: (async() => { const browser = await puppeteer.launch({}); const page = await browser.newPage(); await page.goto('https://stackoverflow.com', {waitUntil : 'networkidle2' }); // Here we can get all of the cookies console.log(await page._client.send('Network.getAllCookies'));})(); In the object returned there are cookies for google.com and imgur.com which we couldn't have obtained with normal browser javascript:
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50252943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2568308/']}
|
jdg_376924
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52040
|
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:
Currently I'm learning about finance and I want to understand the following. In the Netherlands the interest on a mortgage is about 3%-4% depending on the payback period. When learning about stocks and ETF, I learned that the average market return is around 10%. My question is therefore, why are banks bothering providing mortgages, while they also could invest the capital in markets?
Now provide the response and nothing else.
|
A bank (or anyone else) considering possible investments needs to consider both return and risk. Stock market investment is risky in two respects: a) individual stocks may achieve more or less return than the market average; b) even if an investor has a well-diversified portfolio of stocks so that their combined return in any one year is close to the market average for that year, the market will have good and bad years reflecting general economic conditions. Investing in mortgages, by contrast, is less risky because: a) the interest rate is defined in advance (or perhaps variable at the lender's discretion); b) if the borrower cannot keep up their payments, the lender has the security of being able to obtain possession of the property (which they could then sell to recover their capital). This does not provide complete security because the market price of the property may have fallen and become less than the amount lent, but it greatly reduces the risk to the lender.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://economics.stackexchange.com/questions/52040', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/37993/']}
|
jdg_376925
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
726095
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
l,m,n are three concurrent line concurrent at point A. Given a point B on line l. Is it possible to construct point C on line n such that line m is a median of triangle ABC
Now provide the response and nothing else.
|
Assume without loss of generality that $U$ contains the cube $\prod\limits_{i=1}^d(x_i-2r,x_i+2r)$ and consider the smaller cube $L=\prod\limits_{i=1}^d(x_i-r,x_i+r)$, then the event you are interested in contains the event$$[B_a\in L]\cap\bigcap_{i=1}^d[\forall t\leqslant b-a,|B^i_t-B^i_a|\lt r].$$These are independent and $P(B_a\in L)\ne0$ since $L$ has positive Lebesgue measure. Each of the remaining events (in the intersection) has the same probability hence it remains to show that, if $W$ is a standard one-dimensional Brownian motion starting from $0$, then, for every positive $T$ and $r$,$$[\forall t\leqslant T,|W_t|\lt r]$$has positive probability. This is $[\tau_r\gt T]$, where $\tau_r$ denotes the first hitting time of $r$ by $|W|$ thus it remains to show that, for every $T$,$$P(\tau_r\gt T)\ne0.$$Depending on the properties of Brownian motion that one can use, the proof of this property may vary. An approach uses the fact that, for every $u$, $$M^u_t=\cos(uW_t)\,\mathrm e^{u^2t/2}$$ defines a martingale $M^u$ starting from $M^u_0=1$. If $\tau_r$ is almost surely bounded, $M^u$ is bounded before $\tau_r$ hence the stopping time theorem yields $E(M^u_{\tau_r})=1$. By symmetry $W_{\tau_r}$ is uniformly distributed on $\{-r,r\}$ and independent on $\tau_r$ hence $$\cos(ur)\,E(\mathrm e^{u^2\tau_r/2})=1.$$ By hypothesis, $E(\mathrm e^{u^2\tau_r/2})\leqslant E(\mathrm e^{u^2T/2})$ is finite for every $u$ hence, if $\cos(ur)=0$, then we have a problem, Houston... QED.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/726095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/137858/']}
|
jdg_376926
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
113009
|
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:
After learning and experimenting with microcontrollers, I've understood the concept of pull-up- and pull-down resistors. I now understand when and how to use them, and how they work. I've mainly used pull-ups because I was taught to, but it has always seemed a little backwards to me, as closing the switch sets the MCU input to LOW. I think it would make more sense to use a pull-down resistor, so that the input is LOW when the switch is open, but that is just my way of thinking. Should I pull my single-throw inputs up or down? When is pulling down preferred over pulling up and vice versa?
Now provide the response and nothing else.
|
The answer depends on what you want the "default" configuration to be. For example, say you have a down-stream N-channel MOSFET, and you want it default off. Then you would use a pull-down resistor to ensure this behavior if the input becomes high impedance. simulate this circuit – Schematic created using CircuitLab On the other hand, suppose you have an upstream P-channel MOSFET, and want it default off. This time a pull up resistor is required to create this behavior. simulate this circuit There's also the alternative case where you want a device to be default-on, in which case the above two cases would be reversed (pull-up for the N-channel MOSFET, pull-down for the P-channel MOSFET). A few other considerations: I2C lines specify pull-up resistors because devices are "expected" to have an open-drain to ground, and thus need some way to raise the line potential. Analog comparators are usually configured as open-drain devices, and thus also need pull up resistors to get a high potential output. You may draw more current using pullup/pulldown resistors, depending on what's hooked to the input/output. Either configuration could works equally well in your application (i.e. there's no significant advantage one way or the other). ... And any number of very application-specific reasons why one configuration may be preferred.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/113009', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20569/']}
|
jdg_376927
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40450023
|
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 BitmapScalingHelper.java: public class BitmapScalingHelper{ public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight) { Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inJustDecodeBounds = false; options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight); Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options); return unscaledBitmap; } public static Bitmap decodeFile(String filePath, int dstWidth, int dstHeight) { Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); options.inJustDecodeBounds = false; options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight); Bitmap unscaledBitmap = BitmapFactory.decodeFile(filePath, options); return unscaledBitmap; } public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) { final float srcAspect = (float)srcWidth / (float)srcHeight; final float dstAspect = (float)dstWidth / (float)dstHeight; if (srcAspect > dstAspect) { return srcWidth / dstWidth; } else { return srcHeight / dstHeight; } } public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight) { Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight()); Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight); Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(), Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG)); return scaledBitmap; } public static Rect calculateSrcRect(int srcWidth, int srcHeight) { System.out.print("Scr" + srcWidth + " " + srcHeight); return new Rect(0, 0, srcWidth, srcHeight); } public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight) { final float srcAspect = (float)srcWidth / (float)srcHeight; final float dstAspect = (float)dstWidth / (float)dstHeight; if (srcAspect > dstAspect) { return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect)); } else { return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight); } }} In this class there is: createScaledBitmap() ...which returns a scaled bitmap image. In another class, I have this method: public Bitmap readSelectedBitmapFromFile(Context context, String fileName) { DisplayMetrics metrics = new DisplayMetrics(); WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(metrics); Bitmap scaledBitmap = getDefaultBitmap(context); try { File themeParentDir = context.getDir(THEME_DIRECTORY_NAME, Context.MODE_PRIVATE); //Creating an internal dir; File themeSubDir = new File(themeParentDir, THEME_SUB_DIRECTORY_NAME + getThemeBasedDirectoryNumber(m_SelectedTheme)); themeSubDir.mkdir(); File themeFileWithinDir = new File(themeSubDir, fileName); //Getting a file within the dir. if(themeFileWithinDir.exists()) { // Part 1: Decode image Bitmap unscaledBitmap = BitmapScalingHelper.decodeFile(themeFileWithinDir.getPath(), metrics.widthPixels, metrics.heightPixels); // Part 2: Scale image scaledBitmap = BitmapScalingHelper.createScaledBitmap(unscaledBitmap, metrics.widthPixels, metrics.heightPixels); unscaledBitmap.recycle(); } m_SelectedBitmap = scaledBitmap; } catch (Error e) { e.printStackTrace(); } return scaledBitmap; } This code was working fine in many devices. But it was crashing in some devices. Can any one please help me out ? I am getting a log like this: Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) at android.app.ActivityThread.access$1100(ActivityThread.java:222) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7229) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at in.plackal.lovecyclesfree.util.BitmapScalingHelper.createScaledBitmap(SourceFile:62) at in.plackal.lovecyclesfree.general.ThemeManager.readSelectedBitmapFromFile(SourceFile:202) at in.plackal.lovecyclesfree.activity.SplashActivity.onCreate(SourceFile:70) at android.app.Activity.performCreate(Activity.java:6876) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) at android.app.ActivityThread.access$1100(ActivityThread.java:222) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7229) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) If it's a permissions issue, it should not crash below the Android-M version, but it is crashing in some pre-Android-M devices also.
Now provide the response and nothing else.
|
The problem you are facing is that you are trying to getWidth() on your unscaledBitmap in the createScaledBitmap function. Clearly, your unscaledBitmap is null sometimes; and calling getWidth() is causing the Null Pointer exception. The root cause is that decodeResource is returning you a null for whatever reason. The reasons can include - No read permission The image file is corrupt There is not enough memory to decode the file The resource does not exist Invalid options specified in the options variable. I'd suggest that you modify your code to include a null-check on the decoded bitmap, log it and debug from there on the specific devices that you see the error occurring. It may also be that your options variable that you are re-using is being interpreted differently in the second call to decodeResource . You might try passing a null there. The modified code should be as follows - public class BitmapScalingHelper{ public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight) { Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inJustDecodeBounds = false; options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight); options = new Options(); //May use null here as well. The funciton may interpret the pre-used options variable in ways hard to tell. Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options); if(unscaledBitmap == null) { Log.e("ERR","Failed to decode resource - " + resId + " " + res.toString()); return null; } return unscaledBitmap; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40450023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4570569/']}
|
jdg_376928
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45813
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am curious as to why Nancy Pelosi (until 9/24/2019 17:00 EDT) seemed to be so reluctant to push for Donald Trump's impeachment. It seems that the Democratic Party is becoming increasingly outraged by what they perceive as Trump's corruption; lack of respect for the law and continued stonewalling of Congressional oversight. So, it appears that she is quite at odds with a large contingent of her party. Has Nancy Pelosi made any public statements about why she is not supporting a push for impeachment, or what line Trump would have to cross, before she would support it? The obvious answer is that she is concerned any push for impeachment would galvanize Trump's support base. But, is it that simple? What has she said?
Now provide the response and nothing else.
|
Has Nancy Pelosi made any public statements about why she is not supporting a push for impeachment, or what line Trump would have to cross, before she would support it? On September 20, 2019, House Speaker Pelosi gave an interview to NPR, Pelosi Says Congress Should Pass New Laws So Sitting Presidents Can Be Indicted . But despite the growing chants among Democrats for an impeachment inquiry in the House, Pelosi has remained reluctant about recourse. She fears it could alienate swing voters ahead of next year's elections and imperil moderate Democrats who were critical to her party's taking back the House last November. Pelosi did not shift her position on impeachment and said Congress would continue to follow "the facts and the law." From an earlier, linked, article, Who In The House Is Calling For Impeachment? updated September 17, 2019: House Speaker Nancy Pelosi, D-Calif., now stands apart from most of her caucus in opposing such a move, at least for now. She recently cited ongoing litigation as a reason she is not ready to advance an impeachment process. "My position has always been: Whatever decision we made [regarding impeachment] would have to be done with our strongest possible hand, and we still have some outstanding matters in the courts," Pelosi said during a news conference in July. "We have subpoenas in the courts. ... When we get that information we can make that judgment. ... This isn't endless, understand that. But we have live cases in the courts." Pelosi, who has the most influential voice in the decision whether to move forward, has repeatedly stated that she is focused on public sentiment on the issue. She also stresses the need to focus on current congressional committee investigations into Trump before considering impeachment articles. There is no line President Trump would have to cross; rather, it depends on facts and public sentiment. From What Nancy Pelosi Learned From the Clinton Impeachment , June 19, 2019: Drew Hammill, Pelosi’s deputy chief of staff, told me she was too busy to talk about her own takeaways from the Clinton impeachment. But the House speaker has hardly kept her broader views a secret, making it clear that she prefers to have the relevant House committees continue their investigations into Trump’s potential misdeeds, and pressing the courts for access to documents and witnesses as needed in the face of the White House’s stonewalling. She hasn’t totally ruled out impeachment, but unlike some of her colleagues, she has been wary to commit. “Well, it’s not off the table,” Pelosi told CNN’s Manu Raju on Wednesday. “I don’t think you should impeach for political reasons, and I don’t think you should not impeach for political reasons. It’s not about politics. It’s not about Democrats and Republicans. It’s not about partisanship. It’s about patriotism to our country.” Quotes reported after 5 PM, September 24, 2019 Pelosi launches formal Trump impeachment inquiry -- live updates , UPDATED ON: SEPTEMBER 24, 2019 / 6:40 PM / CBS NEWS: 5:43 p.m.: "I'm directing our six committees to proceed with their investigations under that umbrella of impeachment inquiry," Pelosi said in her announcement. 5:57 p.m.: Pelosi on Tuesday outlined the rationale behind her decision to launch a formal impeachment inquiry, a shift from her earlier reluctance to do so. "The president must be held accountable," she said. "No one is above the law." 6:13 p.m.: Later in the Capitol, Pelosi told reporters the Ukraine episode marked a "sea change" in how she approached the question of impeachment, and said it was a "sad day" for the country. "The president of the United States has admitted that he spoke to the president of another country -- that would be the Ukraine -- about something that would assist him in his election," she said. "So, that has changed everything." Pelosi said the inspector general's determination that the whistleblower complaint constitutes an "urgent concern" meant she "accelerated the pace of how we go forward" with the inquiry. 6:40 p.m. Speaker Nancy Pelosi announced the House is launching a formal impeachment inquiry into President Trump, setting up a dramatic constitutional clash just over a year before the presidential election. "Today I'm announcing the House of Representatives is moving forward with an official impeachment inquiry," Pelosi said in a scathing statement at the Capitol late Tuesday afternoon. The speaker has long resisted calls from many progressive lawmakers to initiate impeachment proceedings against the president, but Democrats appear to have reached a breaking point over the administration's refusal to hand over a whistleblower complaint related to Mr. Trump's interaction with a foreign leader.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/45813', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/25684/']}
|
jdg_376929
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
101649
|
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've been programming for a few years and I began in Java, and in my time I've found many different sources claiming Java to be an inferior language in some way or another. I'm well aware that each language has it's strengths and weaknesses, but a lot of things I've read about Java seem to be dated. The most often cited reason for Java being inferior is that it is much slower than other natively compiled languages, like C++ for example. Many people criticize the game designer Notch (who developed Minecraft) for using Java because of its apparent lack in the performance department. I know Java was much slower back in the day, but there have been many improvements since, especially JIT compilation. I would like to get some objective opinions of Java as a language today. So my question has 4 parts. Performance. a. How does Java's speed today compare to C++? b. Would it be possible to create a modern AAA title using Java? c. In what areas specifically is Java slower than C++, if at all? (i.e. Number-crunching, graphics, or just all around) Is Java now considered a compiled language or interpreted language? What are some major shortcomings of Java that have been addressed since the early days? What are some major shortcomings of Java that have yet to be addressed? Edit: Just for clarification purposes I'm not making this Java vs C++, obviously on average c++ will be a little faster than Java. I simply need something to compare Java to in terms of maturity as a language at this point in time. Since c++ has been around forever I thought I would be a good point of comparison.
Now provide the response and nothing else.
|
a. How does Java's speed today compare to C++? Difficult to measure. It's worth noting that a major part of the speed of an implementation, it's memory allocator, are very different algorithms in Java and C++. The non-deterministic nature of the collector makes it extremely difficult to obtain meaningful performance data in comparison to the deterministic memory management of C++, because you can never be certain what state the collector is in. This means that it's very hard to write a benchmark that might meaningfully compare them. Some memory allocation patterns run much faster with a GC, some run much faster with a native allocator. What I would say, however, is that the Java GC has to run fast in every situation. A native allocator, however, can be swapped out for one that's more appropriate. I recently fielded a question on SO about why a C# Dictionary could execute in (0.45 ms on my machine) compared to an equivalent std::unordered_map which executed on (10ms on my machine). However, by simply swapping out the allocator and hasher for more appropriate ones, I cut that execution time to 0.34ms on my machine- a thirtieth of the original run-time. You could never, ever hope to perform that kind of custom optimization with Java. An excellent example of where this can make a real difference is threading. Native thread libraries like TBB provide thread-caching allocators which are massively faster than traditional allocators when dealing with many allocations on many threads. Now, many people will talk about JIT improvements and how the JIT has more information. Sure, that's true. But it's still not even remotely close to what a C++ compiler can pull- because the compiler has, comparatively, infinite time and space in which to run, from the perspective of the run-time of the final program. Every cycle and every byte that the JIT spends thinking about how best to optimize your program is a cycle that your program isn't spending executing and can't use for it's own memory needs. In addition, there will always be times where compiler and JIT optimizations cannot prove certain optimizations- especially in the case of things like escape analysis. In C++, then as the value is on the stack anyway , the compiler doesn't need to perform it. In addition, there are simple things, like contiguous memory. If you allocate an array in C++, then you allocate a single, contiguous array. If you allocate an array in Java, then it's not contiguous at all, because the array is only filled with pointers which could point anywhere. This is not only a memory and time overhead for the double indirections, but cache overheads as well. This kind of thing is where the language semantics of Java simply enforce that it must be slower than equivalent C++ code. Ultimately, my personal experience is that Java could be about half the speed of C++, on average. However, there's realistically no way to back up any performance statements without an extremely comprehensive benchmark suite, because of the fundamentally different algorithms involved. b. Would it be possible to create a modern AAA title using Java? I assume that you mean "game", here, and not a chance. Firstly, you'd have to write everything from scratch yourself as nearly all the existing libraries and infrastructure target C++. Whilst not making it impossible per se, it could certainly contribute solidly towards unfeasible. Secondly, even the C++ engines can hardly fit in the tiny memory constraints of existing consoles- if JVMs even exist for those consoles- and PC gamers expect a little more for their memory. Creating performant AAA games is hard enough in C++, I don't see how it could be achieved in Java. Nobody has ever written an AAA game with significant time spent in a non-compiled language. More than that, it would simply be extremely error-prone. Deterministic destruction is essential when dealing with, for example, GPU resources- and in Java, you'd basically have to malloc() and free() them. c. In what areas specifically is Java slower than C++, if at all? (i.e. Number-crunching, graphics, or just all around) I'd definitely go for all-around. The enforced-reference nature of all Java objects mean that Java has far more indirection and references in it than C++ does- an example I gave earlier with arrays, but also applies to all member objects, for example. Where a C++ compiler can look up a member variable in constant time, a Java run-time has to follow another pointer. The more accesses you do, the slower this is gonna get, and there's nothing the JIT can do about it. Where C++ can free and re-use a piece of memory almost instantly, in Java you have to wait for the collection, and I hope that piece didn't go out of cache, and inherently requiring more memory means lower cache and paging performance. Then look at the semantics for things like boxing and unboxing. In Java, if you want to reference an int, you have to dynamically allocate it. That's an inherent waste compared to the C++ semantics. Then you have the generics problem. In Java, you can only operate on generic objects through run-time inheritance. In C++, templates have literally zero overhead- something Java can't match. This means that all generic code in Java is inherently slower than a generic equivalent in C++. And then you come to Undefined Behaviour. Everyone hates it when their program exhibits UB, and everyone wishes that it didn't exist. However, UB fundamentally enables optimizations that can never exist in Java. Take a look at this post describing optimizations based on UB. Not defining behaviour means that implementations can do more optimizations and reduce the code required to check for conditions that would be undefined in C++ but defined in Java. Fundamentally, the semantics of Java dictate that it is a slower language than C++. Is Java now considered a compiled language or interpreted language? It doesn't really fit into either of those groups. I'd say that managed is really a separate category on it's own, although I'd say it's definitely more like an interpreted language than a compiled language. More importantly, there pretty much only are two major managed systems, the JVM and the CLR, and when you say "managed" it's sufficiently explicit. What are some major shortcomings of Java that have been addressed since the early days? Automatic boxing and unboxing is the only thing I know of. The generics solve some issues, but far from many. What are some major shortcomings of Java that have yet to be addressed? Their generics are very, very weak. C#'s generics are considerably stronger- although of course, neither is quite templates. Deterministic destruction is another major lack. Any form of lambda/closure is also a major problem- you can forget a functional API in Java. And, of course, there's always the issue of performance, for those areas that need them.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/101649', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/29987/']}
|
jdg_376930
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
70052479
|
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 create a Vue Composable that uploads a file to Firebase Storage. To do this I am using the modular Firebase 9 version. But my current code does not upload anything, and instead returns this error: FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown) Since this error is already coming from my console.log("ERROR", err); I'm not sure where else to look for a solution. My code is implemented using TypeScript, incase that matters. import { projectStorage } from "@/firebase/config";import { ref, watchEffect } from "vue";import { ref as storageRef, uploadBytesResumable, UploadTaskSnapshot, UploadTask, getDownloadURL, StorageError,} from "firebase/storage";const useStorage: any = (file: File) => { const error = ref<StorageError | null>(null); const url = ref<string | null>(null); const progress = ref<number | null>(null); watchEffect(() => { // references const storageReference = storageRef(projectStorage, "images/" + file.name); // upload file const uploadTask: UploadTask = uploadBytesResumable(storageReference, file); // update progess bar as file uploads uploadTask.on( "state_changed", (snapshot: UploadTaskSnapshot) => { console.log("SNAPSHOT", snapshot); }, (err) => { error.value = err; console.log("ERROR", err); }, async () => { // get download URL & make firestore doc const downloadUrl = await getDownloadURL(storageReference); url.value = downloadUrl; console.log("DOWNLOADURL", downloadUrl); } ); }); return { progress, url, error };};export default useStorage;
Now provide the response and nothing else.
|
The console error is not sufficent. It does not give enough information. When viewing the console error you need to click the other red POST 400 error shown in the console. This will take you to the Network tab. From there scroll down and click the offending red error. This should finally show you a more helpful error message that reads something like this: Permission denied. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources. This may lead you to think that it's your Firebase Storage rules to blame. And you should double check those rules before continuing, but the more likely problem is that you are missing an esoteric firebase-storage@system.gserviceaccount.com permission inside the Google Cloud Console. To fix that take these steps: Go to https://console.cloud.google.com Select your project in the top blue bar (you will probably need to switch to the "all" tab to see your Firebase projects) Scroll down the left menu and select "Cloud Storage" Select all your buckets then click "Show INFO panel" in the top right hand corner click "ADD PRINCIPAL" Add "firebase-storage@system.gserviceaccount.com" to the New Principle box and give it the role of "Storage Admin" and save it That should fix it!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70052479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1526396/']}
|
jdg_376931
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1081463
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to prove: $$\lim_{n \rightarrow \infty} \sqrt [n] {n^2 +n} $$ I am incline to believe it is 1 but all I have tried to prove it had failed so far.
Now provide the response and nothing else.
|
$1 \le \sqrt[n]{n^2+n} \le \sqrt[n]{2n^2} = \sqrt[n]{2} \cdot \sqrt[n]{n}^2 \to 1 \cdot 1^2 = 1$ as $n \to \infty$ Therefore by squeeze theorem...
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1081463', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/199155/']}
|
jdg_376932
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26088
|
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:
I recently used bootstrapping to estimate confidence intervals for a project. Someone who doesn't know much about statistics recently asked me to explain why bootstrapping works, i.e., why is it that resampling the same sample over and over gives good results. I realized that although I'd spent a lot of time understanding how to use it, I don't really understand why bootstrapping works. Specifically: if we are resampling from our sample, how is it that we are learning something about the population rather than only about the sample? There seems to be a leap there which is somewhat counter-intuitive. I have found a few answers to this question here which I half-understand. Particularly this one . I am a "consumer" of statistics, not a statistician, and I work with people who know much less about statistics than I do. So, can someone explain, with a minimum of references to theorems, etc., the basic reasoning behind the bootstrap? That is, if you had to explain it to your neighbor, what would you say?
Now provide the response and nothing else.
|
fwiw the medium length version I usually give goes like this: You want to ask a question of a population but you can't. So you take a sample and ask the question of it instead. Now, how confident you should be that the sample answer is close to the population answer obviously depends on the structure of population. One way you might learn about this is to take samples from the population again and again, ask them the question, and see how variable the sample answers tended to be. Since this isn't possible you can either make some assumptions about the shape of the population, or you can use the information in the sample you actually have to learn about it. Imagine you decide to make assumptions, e.g. that it is Normal, or Bernoulli or some other convenient fiction. Following the previous strategy you could again learn about how much the answer to your question when asked of a sample might vary depending on which particular sample you happened to get by repeatedly generating samples of the same size as the one you have and asking them the same question. That would be straightforward to the extent that you chose computationally convenient assumptions. (Indeed particularly convenient assumptions plus non-trivial math may allow you to bypass the sampling part altogether, but we will deliberately ignore that here.) This seems like a good idea provided you are happy to make the assumptions. Imagine you are not. An alternative is to take the sample you have and sample from it instead. You can do this because the sample you have is also a population, just a very small discrete one; it looks like the histogram of your data. Sampling 'with replacement' is just a convenient way to treat the sample like it's a population and to sample from it in a way that reflects its shape. This is a reasonable thing to do because not only is the sample you have the best, indeed the only information you have about what the population actually looks like, but also because most samples will, if they're randomly chosen, look quite like the population they came from. Consequently it is likely that yours does too. For intuition it is important to think about how you could learn about variability by aggregating sampled information that is generated in various ways and on various assumptions. Completely ignoring the possibility of closed form mathematical solutions is important to get clear about this.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://stats.stackexchange.com/questions/26088', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/52/']}
|
jdg_376933
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
89345
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm doing a MATLAB assignment in which you work out and implement a better version of Newton-Raphson using a second degree Taylor polynomial instead of a first degree one. I have the algorithm worked out and it is working good. The second part of the assignment is to study the order of convergence empirically. The problem is that with all the functions I've come up with so far gets a very good answer after only 2-4 iterations which doesn't give me a very reliable grounds for analyzing the order of convergence. Can you help me come up with a function that the N-R method works on pretty badly, so that it, for some starting value, takes some more iterations to get to a good value?
Now provide the response and nothing else.
|
As lhf points out, it isn't hard to produce examples where Newton's Method performs poorly -- pick a function whose derivative vanishes near a root, or whose second derivative is unbounded near a root. Or pick an initial guess far from the root. However, studying such examples is counterproductive if you're trying to determine its order of convergence: the reason why the method performs poorly in these corner cases is because they violate the assumptions needed to guarantee typical convergence! In other words, to determine the order of convergence of Newton's method empirically, you should study the best, usual case, not the degenerate cases where the method converges slowly (and where your method will have trouble as well.) If you use double-precision numbers you should have enough digits to estimate the order.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/89345', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4973/']}
|
jdg_376934
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14175
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If the "primordial soup" theory of abiogenesis is to be believed, self-reproducing organisms spontaneously arose on Earth at least 3.5 billion years ago, surprisingly soon after the Earth cooled down enough to potentially harbor life. It may never have happened again, however, since all lifeforms on Earth today are similar on a molecular level (DNA), suggesting a common origin. This appears to imply at least one of the following: Immediately after the first spontaneous abiogenesis, environmental conditions on Earth changed dramatically, making a repeat impossible. The first organisms that arose consumed any subsequent organisms that came into being. This was suggested by Alexander Oparin, but I find it very difficult to believe since it would have to happen everywhere on Earth. Also, most single-celled organisms found today do not consume other organisms, and even where they do that does not usually lead to their complete extinction. The common origin theory is in fact false, despite the similarities between organisms, and abiogenesis did occur multiple times in the same way. Abiogenesis happened more than once, but only the descendants of one occurrence survived till today. Spontaneous abiogenesis never occurred on Earth after all because the conditions never allowed it; instead, a proto-organism arrived on Earth from a planet where the conditions do (Panspermia). The standard theory of geological history is wrong (i.e. the Earth was in a "fertile" state for much longer before the eventual origin of life than commonly thought, due to some unknown mechanism causing radiometric dating to give wrong results). None of these seem likely to me, yet even less likely I find the idea that life arose spontaneously almost immediately (within a few hundred million years, possibly even faster) after the Earth's crust solidified, and never again afterwards. What are the currently held theories on that matter? Can poeple provide references to relevant publications.
Now provide the response and nothing else.
|
It may never have happened again, however, since all lifeforms on Earth today are similar on a molecular level (DNA), suggesting a common origin. An important distinction to make here is that all extant life on Earth has a common origin. It's completely possible that abiogenesis occurred many times, but whatever organisms emerged as a result became extinct early on or are not preserved in the fossil record. Immediately after the first spontaneous abiogenesis, environmental conditions on Earth changed dramatically, making a repeat impossible. Nope. The red bands and subsequent dating techniques suggest it took a very long time for a change to occur. The first organisms that arose consumed any subsequent organisms... Possible, but we have solid data suggesting the first functional organisms were autotrophs. That is, they made their own food from whatever they were exposed to, and the predator/prey relationship had yet to play a major role. The common origin theory is in fact false, despite the similarities between organisms, and abiogenesis did occur multiple times in the same way. The Common Origin Theory - as you've defined it - is almost certainly true. DNA is a constant, as is RNA, mitochondria, etc. That, however, doesn't mean abiogenesis couldn't have happened more than once. As I said above, the Common Origin Theory applies to extant (living) species, not necessarily all organisms that have ever existed. Species go extinct all the time. Spontaneous abiogenesis never occurred on Earth after all because the conditions never allowed it; instead, a proto-organism arrived on Earth from a planet where the conditions do (Panspermia). That merely pushes the question of abiogensis back a bit. Why did it evolve on another world and not Earth, then? How did it survive in space? Why was it so well suited to Earth's environment if Earth-like planets are (relatively speaking) rare? The standard theory of geological history is wrong (i.e. the Earth was in a "fertile" state for much longer before the eventual origin of life than commonly thought, due to some unknown mechanism causing radiometric dating to give wrong results). Estimations and conclusions have come from more than radiometric dating. We have fossil records, geological records spanning continents, and even ice-core records from the poles that both confirm radiometric dating and establish themselves as independent evidence. None of these seem likely to me, yet even less likely I find the idea that life arose spontaneously almost immediately (within a few hundred million years, possibly even faster) after the Earth's crust solidified, and never again afterwards. Why? What are the currently held theories on that matter? Both random speculations and references to relevant publications are welcome. This SE is not the place for random speculations. I don't have publications handy, so I may return and edit my answer when I have the impetus. The most widely held theory is that all extant life, with a few possible exceptions, has evolved from a single organism that existed billions of years ago. That organism may or may not have been the only one to arise. If it was one among many variations of progenitors, we have yet to find the progenitors in the fossil or biological records. Given the extremely long time span between now and the beginnings of life, we don't expect fossil records to exist of all the organisms that existed some 3 B.Y.A. so the best we can do is speculate on what might have existed to account for what we see today.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/14175', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/5264/']}
|
jdg_376935
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1324568
|
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 got a script executing on $(document).ready() that's supposed to vertically align block element in my layout. 90% of the time, it works without issue. However, for that extra 10% one of two things happens: There's an obvious lag in the time it takes to do the centering, and the block elements jump into position. This could simply be performance related - as the page size is often large and there is a fair amount of javascript that is executing at once. The centering will completely mess up, and the block element will either pushed down too far or not far enough. It appears as if it tried to calculate the height, but was getting improper measurements. Is there any reason why executing a script on DOM-ready would not have all the correct CSS values injected into the DOM yet? (all CSS is in the <head> via a <link> ). Also, here's the script that's causing the issue (yes, it's been taken straight from here ): (function ($) { // VERTICALLY ALIGN FUNCTION $.fn.vAlign = function() { return this.each(function(i) { var ah = $(this).height(); var ph = $(this).parent().height(); var mh = (ph - ah) / 2; $(this).css('margin-top', mh); }); }; })(jQuery); Thanks.
Now provide the response and nothing else.
|
From the 1.3 release notes : The ready() method no longer tries to make any guarantees about waiting for all stylesheets to be loaded. Instead all CSS files should be included before the scripts on the page. More Information From the ready(fn) documentation : Note: Please make sure that all stylesheets are included before your scripts (especially those that call the ready function). Doing so will make sure that all element properties are correctly defined before jQuery code begins executing. Failure to do this will cause sporadic problems, especially on WebKit-based browsers such as Safari. Note that the above is not even about actually rendering the CSS, so you may still see the screen change when ready() kicks in. But it should save you from problems. Actually, I find it a bit strange that just putting the CSS above the JS will solve all issues. The CSS is loaded asynchronously, so JS loading can start and finish while the CSS is still being downloaded. So if the above is a solution, then executing any JS code is then halted until all earlier requests have completed? I did some testing, and indeed, sometimes JS is delayed until the CSS is loaded. I don't know why, because the waterfall shows that the JS has completed loading long before downloading the CSS has finished. See JS Bin for some HTML and its results (this has a 10 second delay), and see webpagetest.org for its waterfall results . This uses some script from Steve Souders' cuzillion.com to mimic slow responses. In the waterfall, the reference to resource.cgi is the CSS. So, in Internet Explorer, the first external JS starts to load right after the CSS was requested (but that CSS will take another 10 seconds to finish). But the second <script> tag is not executed until the CSS has finished loading as well: <link rel="stylesheet" type="text/css" href=".../a script that delays.cgi" /><script type="text/javascript" src=".../jquery.min.js"></script> <script type="text/javascript"> alert("start after the CSS has fully loaded"); $(document).ready(function() { $("p").addClass("sleepcgi"); alert("ready"); }); </script> Another test with a second external JS after getting jQuery, shows that the download of the second JS is not started until the CSS has loaded. Here, the first reference to resource.cgi is the CSS, the second the JS: Moving the stylesheet below all JS indeed shows that the JS (including the ready function) runs much earlier, but even then the jQuery-applied class --which is yet unknown when the JS runs-- is used correctly in my quick tests in Safari and Firefox. But it makes sense that things like $(this).height() will yield wrong values at that time. However, additional testing shows that it is not a generic rule that JS is halted until earlier defined CSS is loaded . There seems to be some combination with using external JS and CSS. I don't know how this works. Last notes: as JS Bin includes Google Analytics in each script when running from the bare URL (like jsbin.com/aqeno , the test results are actually changed by JS Bin ... It seems that the Output tab on the edit URL such as jsbin.com/aqeno/edit does not include the additional Google Analytics things, and surely yields different results, but that URL is hard to test using webpagetest.org. The reference to Stylesheets Block Downloads in Firefox and JavaScript Execution in IE as given by strager is a good start for a better understanding, but I got many questions left... Also note Steve Souders' IE8 Parallel Script Loading to make things even more complicated. (The waterfalls above are created using IE7.) Maybe one should simply believe the release notes and documentation...
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1324568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4636/']}
|
jdg_376936
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2636563
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is the C code that frees memory of a singly linked list. It is compiled with Visual C++ 2008 and code works as it should be. /* Program done, so free allocated memory */current = head;struct film * temp;temp = current;while (current != NULL){ temp = current->next; free(current); current = temp;} But I also encountered ( even in a books ) same code written like this: /* Program done, so free allocated memory */current = head;while (current != NULL){ free(current); current = current->next;} If I compile that code with my VC++ 2008, program crashes because I am first freeing current and then assigning current->next to current. But obviously if I compile this code with some other complier ( for example, compiler that book author used ) program will work. So question is, why does this code compiled with specific compiler work? Is it because that compiler put instructions in binary file that remember address of current->next although I freed current and my VC++ doesn't. I just want to understand how compilers work.
Now provide the response and nothing else.
|
The second program is invoking undefined behavior. It is not a difference in the compiler, but rather a difference in the implementation of the C standard library and the function free(). The compiler will store the pointer current as a local variable, but it will not store a copy of the memory that it references. When you invoke free(), you give up ownership of the memory being pointed-to by the pointer passed to the free() function. It is possible that after you relinquish ownership, the contents of the memory pointed-to are still reasonable and are still valid memory locations in your process's address space. Consequently, it is possible that accessing them will appear to work (note that you can silently corrupt memory this way). A pointer that is non-null and points to memory that has already been relinquished is known as a dangling pointer and is incredibly dangerous. Just because it may appear to work does not mean it is correct. I should also point out that it is possible to implement free() in such a way as to catch these errors, such as using a separate page per allocation, and unmapping the page when free() is called (so that the memory address is no longer a valid address for that process). Such implementations are highly inefficient, but are sometimes used by certain compilers when in debugging mode to catch dangling pointer errors.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2636563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308697/']}
|
jdg_376937
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2979512
|
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 is maximal ideal $\mathbb{Z}_{(p)}$ ? And how it is calculated?Also why $\mathbb{Z}_{(p)}/p\mathbb{Z}_{(p)} = \mathbb{F}_p.$ ? I know $p\mathbb{Z}_{(p)}$ is maximal ideal for $\mathbb{Z}_{(p)}$ but how? I know $\mathbb{Z}_{(p)} $ is local so it has unique maximal ideal .
Now provide the response and nothing else.
|
You want to show that the angle between $e^{2\pi k i /n}$ and $e^{2\pi (k+1)i/n}$ is constant. Note that if you divide these two complex numbers you get the resulting angle of rotation between the two. $$ \frac {e^{2\pi (k+1)i/n}}{e^{2\pi ki /n}}= e^{2\pi i/n}$$ which is the same for all $k$ , that is they are vertices of a regular polygon, considering that they all have unit length. For the side-length of the polygon you need to find the norm of the difference of two consecutive roots, for example $$|1-e^{2\pi i/n}|$$ Multiply the result by n and let n goes to $\infty$ to get your $2\pi$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2979512', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/317044/']}
|
jdg_376938
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
191280
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $\omega^\omega$ denote the set of all functions $f:\omega\to\omega$. We write $f <^* g$ if there is $N\in\omega$ such that $f(n) < g(n)$ for all $n>N$. A set $D\subseteq \omega^\omega$ is said to be dominating if for all $f\in \omega^\omega$ there is $g\in D$ such that $f <^* g$. Set $$\frak{d} = \textrm{min}\{|\mathrm{D}|: \mathrm{D}\subseteq \omega^\omega \textrm{ and } \mathrm{D} \textrm{ is dominating}\}.$$ Is it consistent that $\frak{d} < 2^{\aleph_0}$?
Now provide the response and nothing else.
|
Use the fact that adding any number of random reals does not increase the dominating number since every new real is dominated by a ground model real.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/191280', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
|
jdg_376939
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38320886
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using Azure Application Insights for a website (Azure App Service).On that I'm using a clustered Umbraco setup and hangfire. These two alone keep hitting the database every minute and are flooding my 'App Insights'. So my question is, how do I disable the Sql Dependency Tracker?I've had a look at the ApplicationInsights.config and couldn't find anything obvious.I can see Microsoft.ApplicationInsights.DependencyCollector which is probably responsible, but I don't want to remove all types of dependency telemetry, only sql. Thanks
Now provide the response and nothing else.
|
Your best bet here is to use a Telemetry Processor to filter out certain types of dependency requests. Check out these resources below for information. Sampling, filtering and preprocessing telemetry in the Application Insights SDK Request filtering in Application Insights with Telemetry Processor An example processor might look like this. using Microsoft.ApplicationInsights.Channel;using Microsoft.ApplicationInsights.Extensibility;using Microsoft.ApplicationInsights.DataContracts;public class NoSQLDependencies : ITelemetryProcessor{ private ITelemetryProcessor Next { get; set; } // Link processors to each other in a chain. public NoSQLDependencies(ITelemetryProcessor next) { this.Next = next; } public void Process(ITelemetry item) { if (IsSQLDependency(item)) { return; } this.Next.Process(item); } private bool IsSQLDependency(ITelemetry item) { var dependency = item as DependencyTelemetry; if (dependency?.DependencyTypeName == "SQL") { return true; } return false; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38320886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465509/']}
|
jdg_376940
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.