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 | 18109890 |
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 learning to program C# and I am trying to count the vowels. I am getting the program to loop through the sentence, but instead of returning vowel count, it is just returning the length of the string. Any help would be greatly appreciated. static void Main() { int total = 0; Console.WriteLine("Enter a Sentence"); string sentence = Console.ReadLine().ToLower(); for (int i = 0; i < sentence.Length; i++) { if (sentence.Contains("a") || sentence.Contains("e") || sentence.Contains("i") || sentence.Contains("o") || sentence.Contains("u")) { total++; } } Console.WriteLine("Your total number of vowels is: {0}", total); Console.ReadLine(); }
Now provide the response and nothing else.
| Right now, you're checking whether the sentence as a whole contains any vowels, once for each character. You need to instead check the individual characters. for (int i = 0; i < sentence.Length; i++) { if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u') { total++; } } That being said, you can simplify this quite a bit: static void Main(){ int total = 0; // Build a list of vowels up front: var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' }; Console.WriteLine("Enter a Sentence"); string sentence = Console.ReadLine().ToLower(); for (int i = 0; i < sentence.Length; i++) { if (vowels.Contains(sentence[i])) { total++; } } Console.WriteLine("Your total number of vowels is: {0}", total); Console.ReadLine();} You can simplify it further if you want to use LINQ: static void Main(){ // Build a list of vowels up front: var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' }; Console.WriteLine("Enter a Sentence"); string sentence = Console.ReadLine().ToLower(); int total = sentence.Count(c => vowels.Contains(c)); Console.WriteLine("Your total number of vowels is: {0}", total); Console.ReadLine();} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18109890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2108870/']} | jdg_75241 |
stackexchange | llm_judgeable_groundtruth_similarity | 37609328 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Pretty basic, I want to make a title of a message bold based on whether the text it is read or not. I can't seem to find a solution for this. Here is my XML code: <TextView android:text="@{message.title}" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginBottom="5dp" android:layout_marginTop="5dp" android:layout_toLeftOf="@+id/timestamp" android:textSize="18sp" android:textStyle='@{message.isRead() ? "bold" : "normal"}' android:textColor='@{message.isRead() ? 0xff313131 : 0xff0662ab}' /> Th colorchange is working great, only the bold text is giving me some problems. Error:Execution failed for task ':app:compileDebugJavaWithJavac'. java.lang.RuntimeException: Found data binding errors. ****/ data binding error ****msg:Cannot find the setter for attribute 'android:textStyle' with parameter type java.lang.String on android.widget.TextView. file:D:......xml loc:39:41 - 39:79 ****\ data binding error ****
Now provide the response and nothing else.
| I ended up using the following code, it implements DataBinding. public abstract class BindingAdapter { @android.databinding.BindingAdapter("android:typeface") public static void setTypeface(TextView v, String style) { switch (style) { case "bold": v.setTypeface(null, Typeface.BOLD); break; default: v.setTypeface(null, Typeface.NORMAL); break; } }} And the XML <TextView android:text="@{bericht.titel}" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginBottom="5dp" android:layout_marginTop="5dp" android:layout_toLeftOf="@+id/timestamp" android:textSize="18sp" android:textColor='@{bericht.isGelezen() ? 0xff313131 : 0xff0662ab}' android:typeface='@{bericht.isGelezen() ? "normal" : "bold"}' /> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37609328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207633/']} | jdg_75242 |
stackexchange | llm_judgeable_groundtruth_similarity | 12187996 |
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 someone with the natural gift to explain complex things in an easy and straightforward way address this question? To acquire the best performance when should I use direct ByteBuffers versus regular ByteBuffers when doing network I/O with Java NIO? For example: Should I read into a heap buffer and parse it from there, doing many get() (byte by byte) OR should I read it into a direct buffer and parse from the direct buffer?
Now provide the response and nothing else.
| To acquire the best performance when should I use direct ByteBuffers versus regular ByteBuffers when doing network I/O with Java NIO? Direct buffers have a number of advantages The avoid an extra copy of data passed between Java and native memory. If they are re-used, only the page used are turning into real memory. This means you can make them much larger than they need to me and they only waste virtual memory. You can access multi-byte primitives in native byte order efficiently. (Basically one machine code instruction) Should I read into a heap buffer and parse it from there, doing many get() (byte by byte) OR should I read it into a direct buffer and parse from the direct buffer? If you are reading a byte at a time, you may not get much advantage. However, with a direct byte buffer you can read 2 or 4 bytes at a time and effectively parse multiple bytes at once. [real time] [selectors] If you are parsing real time data, I would avoid using selectors. I have found using blocking NIO or busy waiting NIO can give you the lowest latency performance (assuming you have a relatively small number of connections e.g. up to 20) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12187996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967300/']} | jdg_75243 |
stackexchange | llm_judgeable_groundtruth_similarity | 22796788 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried compiling some C++ code with VS2013, and unique_ptr::reset() doesn't seem to work with make_unique() ; a small compilable repro code snippet follows: #include <memory>using namespace std;int main() { unique_ptr<int[]> p = make_unique<int[]>(3); p.reset(make_unique<int[]>(10)); } Compiling from command-line: C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp These are the errors from the MSVC compiler: test.cpp(6) : error C2280: 'void std::unique_ptr<int [],std::default_delete<_Ty>>::reset<std::unique_ptr<_Ty,std::default_delete<_Ty>>>(_Ptr2)' : attempting toreference a deleted function with [ _Ty=int [], _Ptr2=std::unique_ptr<int [],std::default_delete<int []>> ] C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\memory(1623) : see declaration of 'std::unique_ptr<int [],std::default_delete<_Ty>>::reset' with [ _Ty=int [] ] However, the following code seems to compile fine: p = make_unique<int[]>(10); What is the reason of this behavior? Why does unique_ptr::operator=() work with make_unique() , but unique_ptr::reset() doesn't?
Now provide the response and nothing else.
| reset() takes a pointer. What you seem to want is simple move assignment : #include <memory>using namespace std;int main() { unique_ptr<int[]> p = make_unique<int[]>(3); p = make_unique<int[]>(10); } some compilers might still like you to specify the std::move() there, but it's not strictly required. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22796788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1629821/']} | jdg_75244 |
stackexchange | llm_judgeable_groundtruth_similarity | 2933377 |
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 know that for $n=1$ the integral is divergent and that for $n=2$ the integral has a closed form. However, I wonder if the general expression has a closed form. My attempt: $$\int_0^\infty \left(\frac{\arctan(x)}{x}\right)^ndx=\frac{n}{1-n}\int_0^\infty\frac{\arctan^{n-1}(x)}{x^{n-1}(x^2+1)}dx=\frac{n}{1-n}\int_0^{(\frac{\pi}{2})^{n-1}} u^{n-1}\cot^{n-1}\left(u^{1/(n-1)}\right)du$$ I don't know if I'm on the right track here or not but I do not know through what methods to evaluate the last integral. Any help is appreciated.
Now provide the response and nothing else.
| Used formulas and definitions: $\displaystyle\Re(i^n)=\cos\left(\frac{\pi n}{2}\right)\enspace$ for integer $~n\enspace$ ; $\enspace\displaystyle\tan x = -i\frac{1-e^{-i2x}}{1+e^{-i2x}}$ $\displaystyle \sum\limits_{j=0}^{-1} a_j := \sum\limits_{j=0}^0 a_j - a_0 = 0\enspace$ ; $\enspace\displaystyle \left(\sum\limits_{k=0}^{\infty} a_k\right) \left(\sum\limits_{k=0}^{\infty} b_k\right) = \left(\sum\limits_{k=0}^{\infty} \sum\limits_{v=0}^k a_v b_{k-v}\right) $ $\displaystyle \int\limits_0^a x^m e^{zx} dx = \frac{m!}{(-z)^{m+1}} - e^{az}\sum\limits_{v=0}^m\frac{m!a^{m-v}}{(m-v)!(-z)^{v+1}} \enspace$ for $\enspace m\in\mathbb{N}_0 , \, a\in\mathbb{R} , \, z\in\mathbb{C}\setminus\{0\} $ Stirling numbers of the first kind $\displaystyle \begin{bmatrix}n\\k\end{bmatrix}$ defined by $\hspace{4cm}\displaystyle\sum\limits_{j=0}^n\begin{bmatrix}n\\j\end{bmatrix}x^j:=\prod\limits_{k=0}^{n-1}(x+k) \enspace$ for $\enspace n\in\mathbb{N}_0 , \, x\in\mathbb{C} $ $\displaystyle \sum\limits_{j=0}^n f(j) \sum\limits_{l=0}^j g(j,l) k^l = \sum\limits_{j=0}^n k^j \sum\limits_{l=j}^n f(l)g(l,j) \enspace\enspace$ formal summation permutation $\displaystyle \sum\limits_{v=-1}^k {\binom {n+1} {k-v}}{\binom {n+v} v} = \displaystyle \sum\limits_{v=0}^{n+1} {\binom {n+1} v}{\binom {n+k-v} n}\enspace$ for $\enspace k,n\geq 0$ $\displaystyle c_{n,j} := \frac{1}{n!} \sum\limits_{v=0}^{n+1} {\binom {n+1} {v}} \sum\limits_{l=j}^m \begin{bmatrix}n+1\\l+1\end{bmatrix} {\binom l j} (-v)^{l-j} \enspace$ for $\enspace 0\leq j\leq n\enspace$ with $\enspace 0^0:=1$ $\displaystyle b_{n,k} := \sum\limits_{v=0}^k {\binom {n+1} {k-v}} {\binom {n+v} v} = -0^{n+k} +\sum\limits_{j=0}^n k^j c_{n,j} \enspace$ for $\enspace k,n \geq 0 \,~~ ; \enspace b_{n,0 }=1$ It follows: $\displaystyle\sum\limits_{k=1}^\infty \frac{b_{n,k}~x^k}{k^s} = \sum\limits_{j=0}^n c_{n,j}~\text{Li}_{s-j}(x) \enspace$ for $\enspace s\in\mathbb{C}\enspace$ where $\enspace \text{Li}_s(x)\enspace$ is the Polylogarithm with the special cases $\enspace \text{Li}_s(1)\equiv \zeta(s)\,$ and $\hspace{4.1cm}\text{Li}_s(-1)\equiv -\eta(s) = \left(2^{1-s}-1\right)\zeta(s) \enspace$ with $\enspace\eta(1)=\ln 2$ $\underline{\text{Solution:}}$ Let $\enspace\displaystyle |a| \leq \frac{\pi}{2} \, , \enspace 0\leq n\leq m \,$ . $\displaystyle \int\limits_0^{\tan a} \frac{\arctan^m x}{x^n} dx = \int\limits_0^a \frac{x^m}{\tan^n x} dx + \int\limits_0^a \frac{x^m}{\tan^{n-2} x} dx \enspace$ for $\enspace n\geq 2$ $$\int\limits_0^a \frac{x^m}{\tan^n x}dx = i^n\frac{a^{m+1}}{m+1} + \frac{i^{n-m-1}m!}{2^{m+1}}\sum\limits_{j=0}^{n-1}~c_{n-1,j}~\text{Li}_{m+1-j}~(1) $$ $$\hspace{2.5cm} -\sum\limits_{v=0}^m \frac{i^{n-v-1}m!a^{m-v}}{(m-v)!2^{v+1}} \sum\limits_{j=0}^{n-1}~c_{n-1,j}~\text{Li}_{v+1-j}~(e^{-i2a})$$ $\displaystyle a:=\frac{\pi}{2}\,$ : $$\int\limits_0^{\pi/2} \frac{x^m}{\tan^n x}dx = $$ $$ \cos\left(\frac{\pi n}{2}\right)\frac{(\pi/2)^{m+1}}{m+1} +\cos\left(\frac{\pi (n-m-1)}{2}\right) \frac{m!}{2^{m+1}}\sum\limits_{j=0}^{n-1}~c_{n-1,j}~\zeta(m+1-j) $$ $$\hspace{2.5cm} +\sum\limits_{v=0}^m \cos\left(\frac{\pi (n-v-1)}{2}\right)\frac{m!(\pi/2)^{m-v}}{(m-v)!2^{v+1}} \sum\limits_{j=0}^{n-1}~c_{n-1,j}~\eta(v+1-j)\hspace{1cm}$$ Finally we get: $$\int\limits_0^\infty \left(\frac{\arctan x}{x}\right)^n dx = $$ $$\frac{1}{2^{n+1}} \sum\limits_{v=0}^n \left(\cos\frac{\pi(n-v-1)}{2}\right) \frac{n!\pi^{n-v}}{(n-v)!}~\cdot $$ $$\cdot~\left( \sum\limits_{j=0}^{n-1} c_{n-1,j}~\eta(v-j+1) - \sum\limits_{j=0}^{n-3} c_{n-3,j}~\eta(v-j+1) \right)$$ Analytical continuations $(s\in\mathbb{C})$ : $$\begin{align}\zeta(1-s)&=\dfrac{2}{(2\pi)^s}\cos\bigg(\dfrac{\pi s}{2}\bigg)~\Gamma(s)~\zeta(s)\\\\\eta(1-s)&=\dfrac{2^s-1}{1-2^{s-1}}~\pi^{-s}\cos\bigg(\dfrac{\pi s}{2}\bigg)~\Gamma(s)~\eta(s)\end{align}$$ Simplifications $(k\in\mathbb{N}_0)$ : $$\begin{align}\eta(1)=\ln 2 \enspace ; \enspace \eta(1-k)~&=~\frac{2^k-1}{k}~B_k\end{align}$$ $$\begin{align}\eta(2k)~&=~(-1)^{k-1}~\frac{2^{2k-1}-1}{(2k)!}~B_{2k}~\pi^{2k}\end{align}$$ $$\begin{align}\eta(2k+1)~&=~\bigg(1-\frac{1}{2^{2k}}\bigg)\zeta(2k+1)\end{align}$$ Examples: $\displaystyle c_{0,0} = \frac{2}{0!}(1)$ $\displaystyle (c_{1,0}~;~ c_{1,1}) = \frac{2}{1!} \left(0~;~2\right)$ $\displaystyle (c_{2,0}~;~c_{2,1}~;~c_{2,2}) = \frac{2}{2!} \left(2~;~0~;~4\right)$ $\displaystyle (c_{3,0}~;~c_{3,1}~;~c_{3,2}~;~c_{3,3}) = \frac{2}{3!} \left(0~;~16~;~0~;~8\right)$ $\displaystyle (c_{4,0}~;~c_{4,1}~;~c_{4,2}~;~c_{4,3}~;~c_{4,4}) = \frac{2}{4!} \left(24~;~0~;~80~;~0~;~16\right)$ $\displaystyle (c_{5,0}~;~c_{5,1}~;~c_{5,2}~;~c_{5,3}~;~c_{5,4}~;~c_{5,5}) = \frac{2}{5!} \left(0~;~368~;~0~;~320~;~0~;~32\right)$ $\displaystyle (c_{6,0}~;~c_{6,1}~;~c_{6,2}~;~c_{6,3}~;~c_{6,4}~;~c_{6,5}~;~c_{6,6}) = \frac{2}{6!} \left(720~;~0~;~3136~;~0~;~1120~;~0~;~64\right)$ $\displaystyle (c_{7,0}~;~c_{7,1}~;~c_{7,2}~;~c_{7,3}~;~c_{7,4}~;~c_{7,5}~;~ c_{7,6}~;~ c_{7,7}) $ $\hspace{7cm}\displaystyle =\frac{2}{7!} \left(0~;~16896~;~0~;~19712~;~0~;~3584~;~0~;~128\right)$ ... $\displaystyle \int\limits_0^\infty \left(\frac{\arctan x}{x}\right)^2 dx = \pi\ln 2$ $\displaystyle \int\limits_0^\infty \left(\frac{\arctan x}{x}\right)^3 dx = -\frac{\pi^3}{16} + \frac{3\pi}{2}\ln 2$ $\displaystyle \int\limits_0^\infty \left(\frac{\arctan x}{x}\right)^4 dx = -\frac{\pi^3}{12}(2\ln 2 + 1) + \frac{\pi}{4}(3\zeta(3) + 8\ln 2)$ $\displaystyle \int\limits_0^\infty \left(\frac{\arctan x}{x}\right)^5 dx = \frac{\pi^5}{128} - \frac{5\pi^3}{48}(8\ln 2 + 1) + \frac{5\pi}{4}(3\zeta(3) + 2\ln 2)$ $\displaystyle \int\limits_0^\infty \left(\frac{\arctan x}{x}\right)^6 dx = $ $\displaystyle\hspace{8mm} =\frac{3\pi^5}{320}(4\ln 2 + 3) - \frac{\pi^3}{16}(9\zeta(3) + 40\ln 2 + 2) + \frac{3\pi}{32}(45\zeta(5) + 120\zeta(3) + 32\ln 2)$ ... | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2933377', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/468742/']} | jdg_75245 |
stackexchange | llm_judgeable_groundtruth_similarity | 284606 |
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 apologize if my question is trivial. I am a group theorist with a minor knowledge of topology. Suppose $(X, T_X)$ and $(Y, T_Y)$ are two topological spaces and there is an inclusion-reversing (inclusion preserving) bijection $\varphi:T_X\to T_Y$. What is the name of this kind of equivalence? What can be said about the relation of these two spaces?
Now provide the response and nothing else.
| As far as I can see there are two possibilities where we can say more: The bijection is order preserving. As Qiaochu Yuan said in a comment, this is the same as asking that their associated locales are isomorphic. Thanks to the equivalence of sober spaces with spatial locales, this is the same as asking that their soberifications are homeomorphic. In particular, if $X$ and $Y$ are already sober (a very common condition, sober is strictly weaker than Hausdorff), this is the same as asking that $X$ and $Y$ are homeomorphic. The bijection is order reversing. Then the lattice of opens of both spaces need to have arbitrary meets distribute over finite joins (i.e. each frame of opens must have the property that its opposite lattice is a frame too). This is a very rare situation, that happens mainly for Alexandrov spaces ,although as მამუკაჯიბლაძე notes in the comments there might be other examples. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/284606', 'https://mathoverflow.net', 'https://mathoverflow.net/users/44949/']} | jdg_75246 |
stackexchange | llm_judgeable_groundtruth_similarity | 18429491 |
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 DataFrame with many missing values in columns which I wish to groupby: import pandas as pdimport numpy as npdf = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})In [4]: df.groupby('b').groupsOut[4]: {'4': [0], '6': [2]} see that Pandas has dropped the rows with NaN target values. (I want to include these rows!) Since I need many such operations (many cols have missing values), and use more complicated functions than just medians (typically random forests), I want to avoid writing too complicated pieces of code. Any suggestions? Should I write a function for this or is there a simple solution?
Now provide the response and nothing else.
| pandas >= 1.1 From pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False : pd.__version__# '1.1.0.dev0+2004.g8d10bfb6f'# Example from the docsdf a b c0 1 2.0 31 1 NaN 42 2 1.0 33 1 2.0 2# without NA (the default)df.groupby('b').sum() a cb 1.0 2 32.0 2 5 # with NAdf.groupby('b', dropna=False ).sum() a cb 1.0 2 32.0 2 5NaN 1 4 | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18429491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2715498/']} | jdg_75247 |
stackexchange | llm_judgeable_groundtruth_similarity | 385356 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In QM states are vectors in a Hilbert space $\mathscr{H}$. These are often denoted like $|\psi\rangle$. On the other hand, in the algebraic approach, we have one $\ast$-algebra $\mathscr{A}$ and states are linear functionals $\omega : \mathscr{A}\to \mathbb{C}$ such that $\omega(a^\ast a)\in [0,\infty)$ and $\omega(1)=1$. It is not at all clear how these two things are related. For a first step, we have the GNS construction. The GNS construction is the following: GNS Construction : Given a $\ast$-algebra $\mathscr{A}$ and a state $\omega : \mathscr{A}\to \mathbb{C}$ we can construct one Hilbert space $\mathscr{H}_\omega$, one $\ast$-representation $\pi_{\omega} : \mathscr{A}\to \mathscr{A}(\mathscr{H}_\omega)$ and one $\Omega \in \mathscr{H}$ such that $\pi_{\omega}(\mathscr{A})\Omega$ is dense and $$\omega(a)=\langle \Omega ,\pi_\omega(a)\Omega\rangle.$$ Now we have some interesting things: Every algebraic state $\omega$ gives rise to a whole Hilbert space on which $\omega$ becomes the distinguished $\Omega$ and it produces one mean value on the usual QM sense. The other unit vectors on the Hilbert space give rise to algebraic states. Actually, if $\Phi\in \mathscr{H}$ we have that$$\omega_\Phi(a)=\langle \Phi, \pi_{\omega}(a)\Phi\rangle$$is one algebraic state. It is obviously a linear functional and certainly satisfies $\omega_{\Phi}(1)=1$ and $$\omega_{\Phi}(a^\ast a)=\langle \Phi,\pi_{\omega}(a^\ast a)\Phi\rangle=\langle \Phi,\pi_{\omega}(a^\ast)\pi_{\omega}(a)\Phi\rangle=\langle \Phi,\pi_{\omega}(a)^\ast \pi_\omega(a)\Phi\rangle=\langle \pi_\omega(a)\Phi,\pi_{\omega}( a)\Phi\rangle=|\Phi|^2\in [0,+\infty)$$ On the other hand it doesn't seem that every algebraic state gives rise to one usual state in $\mathscr{H}_\omega$. In truth, because of the Riesz representation theorem it would suffice that to every algebraic state $\phi$ there was one algebraic state $\tilde{\Phi}$ on $\mathscr{A}(\mathscr{H}_\omega)$. This in turn requires that $\tilde{\Phi}(\pi_{\omega}(a))=\phi(a)$ thus for this to be true we would need $\pi_\omega$ to be invertible. In other words, the representation must be faithful. These points show that although related to the usual state vectors from QM, the algebraic states aren't equivalent to them. In fact, it seems we have more algebraic states than state vectors. Furthermore, GNS allows us to indeed represent each state as a state vector, but on different Hilbert spaces. The point (2) I made then guarantee that each such state vector can be identified with one algebraic states, but there are other apart from it which do not belong on this Hilbert space. Even, though, if we pick one of those states in (2) and perform the GNS construction with them it seems we get an entirely different Hibert space. It seems that the role of algebraic states is to generate a representation only and this is quite strange, considering the usual QM point of view on states. So what is the correct way to understand algebraic states? How they relate to the usual notion of states from QM? To work with them in practice do we always need to use the GNS construction? How do we deal with the fact that it appears that there are more algebraic states than QM vector states, in the sense that when we perform the GNS construction some algebraic states appear to be "left out"?
Now provide the response and nothing else.
| The algebraic formulation is more general and takes into account many subtleties that arise in QFT and that are hidden in quantum mechanics. In fact, in quantum mechanics the Stone-von Neumann theorem tells us that the irreducible representation of the algebra of quantum observables (more precisely, of the algebra of canonical commutation relations) is essentially unique ( i.e. it is unique up to unitary transformations). So the only relevant representation is the usual one (called Schrödinger representation), and the physically relevant states are the ones that are normal with respect to such representation ( i.e. that can be written as density matrices on the corresponding Hilbert space $L^2(\mathbb{R}^d)$). In quantum field theories, on the other hand, there are infinitely many inequivalent irreducible representations of the canonical (anti)commutation relations. Therefore, there are indeed states that can be represented as density matrices (or vectors) in one representation, but not in another (it is said that they are not normal with respect to the latter). In addition, the so-called Haag's theorem explains that inequivalent representations, or more precisely disjoint states (states that are not normal w.r.t. the GNS irrepresentation of each other), play a very important role in QFT. In fact, given a group $G$ acting on the C*-algebra of observables, and two $G$-invariant states $\omega_1,\omega_2$ (with an additional technical condition that is not important here), then either $\omega_1=\omega_2$, or $\omega_1$ and $\omega_2$ are disjoint. In a relativistic theory, the ground state (or vacuum) is invariant w.r.t. the restricted Poincaré group. In addition, it is easy to see that in general the vacua of a free and an interacting theory must be different (and both invariant). Therefore, by Haag's theorem they are disjoint , and so they cannot both be represented as density matrices in a single representation. This is just one example of why non-normal states (w.r.t. the free or Fock irrepresentation) are very important in QFT, and of why the algebraic description of quantum theories is so often used for relativistic quantum mechanics. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/385356', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21146/']} | jdg_75248 |
stackexchange | llm_judgeable_groundtruth_similarity | 31436783 |
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 generating a dictionary out of multiple .csv files and it looks like this (example): dtDict = {'AV-IM-1-13991730': {'6/1/2014 0:10': '0.96', '6/1/2014 0:15': '0.92', '6/1/2014 0:20': '0.97'}, 'AV-IM-1-13991731': {'6/1/2014 0:10': '1.96', '6/1/2014 0:15': '1.92', '6/1/2014 0:20': '1.97'}, 'AV-IM-1-13991732': {'6/1/2014 0:10': '2.96', '6/1/2014 0:15': '2.92', '6/1/2014 0:20': '2.97'}, 'AV-IM-1-13991733': {'6/1/2014 0:10': '3.96', '6/1/2014 0:15': '3.96', '6/1/2014 0:20': '3.97'}} I want to save it to a .csv file in the following format: timestamp,AV-IM-1-13991730,AV-IM-1-13991731,AV-IM-1-13991732,AV-IM-1-139917336/1/2014 0:10,0.96,1.96,2.96,3.966/1/2014 0:15,0.92,1.92,2.92,3.966/1/2014 0:20,0.97,1.97,2.97,3.97 The piece of code I have as of now (related to this objective): header = '''# file...... Recorder file# date...... Thu Mar 12 14:35:32 2015# user...... Sri# host...... (null)# group..... None# property.. AVA Measurements# limit..... # interval..''' testpower = open("custpower.csv",'w')testpower.writelines([header,'\n','# timestamp\n'])...for key, value in dtDict.iteritems(): #Still trying to figure out how to write to custpower.csv I tried doing something similar to this: for key, value in dtDict.iteritems(): testpower.writelines([key,',',','.join(value),'\n']) but it didnot quite do what I was trying to do.
Now provide the response and nothing else.
| This is beyond simple if you can use pandas . import pandas as pddata = {'AV-IM-1-13991730': {'6/1/2014 0:10': '0.96', '6/1/2014 0:15': '0.92', '6/1/2014 0:20': '0.97'}, 'AV-IM-1-13991731': {'6/1/2014 0:10': '1.96', '6/1/2014 0:15': '1.92', '6/1/2014 0:20': '1.97'}, 'AV-IM-1-13991732': {'6/1/2014 0:10': '2.96', '6/1/2014 0:15': '2.92', '6/1/2014 0:20': '2.97'}, 'AV-IM-1-13991733': {'6/1/2014 0:10': '3.96', '6/1/2014 0:15': '3.96', '6/1/2014 0:20': '3.97'}}df = pd.DataFrame(data)df.to_csv(PATH_TO_OUTPUT_FILE) df becomes a DataFrame that looks like AV-IM-1-13991730 AV-IM-1-13991731 AV-IM-1-13991732 AV-IM-1-139917336/1/2014 0:10 0.96 1.96 2.96 3.966/1/2014 0:15 0.92 1.92 2.92 3.966/1/2014 0:20 0.97 1.97 2.97 3.97 And your resulting csv looks like ,AV-IM-1-13991730,AV-IM-1-13991731,AV-IM-1-13991732,AV-IM-1-139917336/1/2014 0:10,0.96,1.96,2.96,3.966/1/2014 0:15,0.92,1.92,2.92,3.966/1/2014 0:20,0.97,1.97,2.97,3.97 Pandas is also nice because you can then do: df.convert_objects(convert_numeric=True).plot()# the converts change "0.97" -> 0.97 so it's plottable To get: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31436783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3931263/']} | jdg_75249 |
stackexchange | llm_judgeable_groundtruth_similarity | 27010110 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two related questions regarding TinyMCE (v. 3.5.11) default paste functionality: Why isn't the text available on paste? After pasting text into the editor, the content is visible in the editor, but not available via the .getContent() method. Why? Can I force TinyMCE to get the text it is displaying in the editor during this event? Why does Ctrl + V trigger a change event, but context menu paste does not? If you paste text into the editor with key combo Ctrl+V, first TinyMCE's onPaste event is fired and the text is not available via .getContent() (as mentioned above); immediately following that, the onChange event is fired and the text is now available via the .getContent() method. However, if you paste text into the editor with mouse by right-click, then select Paste from context menu, TinyMCE's onPaste event is fired, but not onChange . Why the difference? What can be done about this? See this JSFiddle for a working example . Note: I am not using the Paste plugin, so please don't offer it or any other plugin as an answer. I am interested in creating my own solution.
Now provide the response and nothing else.
| Listen to paste event, get clipboard data Why isn't the text available on paste? After pasting text into the editor, the content is visible in the editor, but not available via the .getContent() method. Why? I don't know why, but apparently pasting via context menu doesn't trigger a change event in TinyMCE. From my observation, the text in the editor gets cached by TinyMCE and only updated during an onChange event. So even though the text is visible, it hasn't been cached by TinyMCE and therefore .getContent() returns the last cached value (or undefined if nothing has been cached yet). Can I force TinyMCE to get the text it is displaying in the editor during this event? No. Why does Ctrl + V trigger a change event, but context menu paste does not? … Why the difference? Ultimately, it is because pasting via Ctrl + V triggers an "Undo level" — which in turn triggers the onChange event — while the context menu paste event does not (to me, this seems like a TincyMCE bug): Undo levels are added when the user types text and then moves the cursor, performs an action like pressing the bold button while having text selected, or pressing return. There are many ways undo levels get added to the editor. See: TinyMCE documentation for onchange_callback What can be done about this? You can listen for the onPaste event and bind a callback function to get the text directly from the clipboard and insert it into the editor. Using the .execCommand() method to insert the content will trigger an Undo level, which in turn will trigger an onChange event even when pasting via the context menu. Here is an example using a "Paste as plain text" callback onPaste : tinyMCE.init({ // ..., setup: function (editor) { // Listen for paste event, add "Paste as plain text" callback editor.onPaste.add(function (editor, e) { // Prevent default paste behavior e.preventDefault(); // Check for clipboard data in various places for cross-browser compatibility. // Get that data as text. var content = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text'); // Let TinyMCE do the heavy lifting for inserting that content into the editor. editor.execCommand('mceInsertContent', false, content); }); }}); Note: Naturally, you don't have to make this function "paste as plain text". You could choose to get the full HTML from the clipboard if you wanted to retain formatting, but then you get into additional cross-browser compatibility issues outside the scope of this answer. Pasting as plain text requires fewer lines of code and so it is more suited for an example in a Stack Overflow answer. It also happens to be a commonly sought solution for TinyMCE developers, so its inclusion here might be helpful in that regard. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27010110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502532/']} | jdg_75250 |
stackexchange | llm_judgeable_groundtruth_similarity | 32457080 |
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 created a with left bar button item added from storyboard, titleView and three right bar button items from code. Here is the code: override func viewDidLoad() { super.viewDidLoad() var screenWidth = UIScreen.mainScreen().bounds.width // custom title view var navBarWidth: CGFloat = self.navigationController!.navigationBar.frame.size.width let customTitleView = UIView(frame: CGRectMake(0, 0, navBarWidth, 44)) titleLabel = UILabel(frame: CGRectMake(20, 0, navBarWidth, 40)) titleLabel.text = conversationName if let titleFont = UIFont(name: "Roboto-Regular", size: 20) { titleLabel.font = titleFont } titleLabel.textColor = UIColor.whiteColor() customTitleView.addSubview(titleLabel) self.navigationItem.titleView = customTitleView // right bar buttons var searchImage = UIImage(named: "search")! var clipImage = UIImage(named: "clip")! var pencilImage = UIImage(named: "pencil")! var searchBtn = UIBarButtonItem(image: searchImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("searchBtnPressed")) searchBtn.tintColor = UIColor.whiteColor() var clipBtn = UIBarButtonItem(image: clipImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("clipBtnPressed")) clipBtn.tintColor = UIColor.whiteColor() var pencilBtn = UIBarButtonItem(image: pencilImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("pencilBtnPressed")) pencilBtn.tintColor = UIColor.whiteColor() self.navigationItem.setRightBarButtonItems([pencilBtn, clipBtn, searchBtn], animated: false)} My problem is that I want to change the spacing between right buttons but I don't know how. I've tried to add a fixedButton between them but it just increased the existing space. Can some one help me? Thanks.
Now provide the response and nothing else.
| I solved my problem in this way: var searchImage = UIImage(named: "search-selected")!var clipImage = UIImage(named: "clip")!var pencilImage = UIImage(named: "pencil")!let searchBtn: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButtonsearchBtn.setImage(searchImage, forState: UIControlState.Normal)searchBtn.addTarget(self, action: "searchBtnPressed", forControlEvents: UIControlEvents.TouchUpInside)searchBtn.frame = CGRectMake(0, 0, 30, 30)let searchBarBtn = UIBarButtonItem(customView: searchBtn)let clipBtn: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButtonclipBtn.setImage(clipImage, forState: UIControlState.Normal)clipBtn.addTarget(self, action: "clipBtnPressed", forControlEvents: UIControlEvents.TouchUpInside)clipBtn.frame = CGRectMake(0, 0, 30, 30)let clipBarBtn = UIBarButtonItem(customView: clipBtn)let pencilBtn: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButtonpencilBtn.setImage(pencilImage, forState: UIControlState.Normal)pencilBtn.addTarget(self, action: "pencilBtnPressed", forControlEvents: UIControlEvents.TouchUpInside)pencilBtn.frame = CGRectMake(0, 0, 30, 30)let pencilBarBtn = UIBarButtonItem(customView: pencilBtn)self.navigationItem.setRightBarButtonItems([pencilBarBtn, clipBarBtn, searchBarBtn], animated: false) Now it looks good, Update for Swift 4.1 let testButton : UIButton = UIButton.init(type: .custom)testButton.setImage(editImage, for: .normal)testButton.addTarget(self, action: #selector(didTapCameraButton), for: .touchUpInside)testButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)let addButton = UIBarButtonItem(customView: testButton) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32457080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4861858/']} | jdg_75251 |
stackexchange | llm_judgeable_groundtruth_similarity | 65634 |
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 stuck on an exercise in Isaacs's book "Character Theory of Finite Groups" - it relates to something I'm looking at as part of ongoing research, but I guess it belongs here rather than on MathOverflow, since it's an exercise and hence ought to be solvable by basic techniques... Anyway, the question/problem is Exercise 5.14(a), and goes as follows. Let G be a finite nonabelian group and let $f$ be the smallest character degree that is not 1. Suppose that the derived subgroup (a.k.a. the commutator subgroup) has order $\leq f$. Prove that the derived subgroup is contained in the centre of $G$. The hint given is the (fairly obvious) fact that each conjugacy class injects into $G'$, so by the assumption of the problem is bounded above by $f$. This makes me think that the solution has something to do with column orthogonality in the character table, using the fact that the linear characters all take the value 1 on the derived subgroup; but I haven't managed to make that idea work. If it helps or makes any difference: the chapter for which this is an exercise is the one introducing induced characters (but precedes the discussion of induction from normal subgroups, and Clifford theory). Again, I can't see a way to induce anything from the derived subgroup to make progress: my only idea would be to take a non-trivial irreducible character on the derived subgroup, induce it to a character on $G$, and observe that the induced character is orthogonal to all the linear characters of $G$ by e.g. Frobenius reciprocity. I'm sure I'm just missing something obvious, so would be happy with just a hint or two.
Now provide the response and nothing else.
| By the hint, as explained in Jack Schmidt's answer, you see that every conjugacy class has size smaller than f. Consider the conjugation action of G on the conjugacy class $g^G$. This is the sum of the trivial with a representation of dimension smaller than f. Thus, by assumption it is a sum of 1-dimensional representations, and therefore abelian. This means that $x y g y^{-1} x^{-1} = y x g x^{-1} y^{-1}$. Rearranging we get, $x^{-1} y^{-1} x y g = g x^{-1} y^{-1} x y$, and thus every commutator is central. The reason this has to do with induced representations is that the conjugation action on $g^G$ is the representation induced from the trivial rep of the centralizer of g. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/65634', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_75252 |
stackexchange | llm_judgeable_groundtruth_similarity | 9831641 |
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 already build a recursive function to get the directory size of a folder path. It works, however with the growing number of directories I have to search through (and number of files in each respective folder), this is a very slow, inefficient method. static string GetDirectorySize(string parentDir){ long totalFileSize = 0; string[] dirFiles = Directory.GetFiles(parentDir, "*.*", System.IO.SearchOption.AllDirectories); foreach (string fileName in dirFiles) { // Use FileInfo to get length of each file. FileInfo info = new FileInfo(fileName); totalFileSize = totalFileSize + info.Length; } return String.Format(new FileSizeFormatProvider(), "{0:fs}", totalFileSize);} This is searches all subdirectories for the argument path, so the dirFiles array gets quite large. Is there a better method to accomplish this? I've searched around but haven't found anything yet. Another idea that crossed my mind was putting the results in a cache and when the function is called again, try and find the differences and only re-search folders that have changed. Not sure if that's a good thing either...
Now provide the response and nothing else.
| You are first scanning the tree to get a list of all files. Then you are reopening every file to get its size. This amounts to scanning twice. I suggest you use DirectoryInfo.GetFiles which will hand you FileInfo objects directly. These objects are pre-filled with their length. In .NET 4 you can also use the EnumerateFiles method which will return you a lazy IEnumable . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9831641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1157509/']} | jdg_75253 |
stackexchange | llm_judgeable_groundtruth_similarity | 304718 |
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 have already removed three outliers from the ANOVA and ANCOVA analysis to improve the models. I want to report the descriptive statistics and p-values. First I removed these outliers, and then I applied the analysis. My question is, for publication, should I provide the information before or after removing the outliers?
Now provide the response and nothing else.
| In publications honesty is the best policy. It's all right to remove outliers and to report descriptive statistics based on the reduced dataset. However in order for others to understand and appreciate what was done you have to state which samples were removed as outliers and your reasoning for why they were outliers. If your justification of marking those samples as outliers is solid (for example - instrument malfunctioned when they were recorded) then others reading your paper will agree with you and thank you for removing those samples. If there might be disputes about those samples being outliers then there is always a possibility of doing the calculations twice: one time with outliers present and another time with outliers removed. Then you can present numbers without outliers in the main text and include the numbers calculated with outliers in the supplement. However it's hard to ignore one part of your question. You write: removed three outliers ... to improve the models Here you have to be extra careful. If a sample disagrees with your model it doesn't mean that the sample is outlier. The situation is like this: there is a real phenomenon you have data about that phenomenon you have some imaginary model that you think explains the phenomenon Now you find that some samples from the real world don't agree with your imaginary model. Would you say that removing those samples will improve your model? Likely not. What might be happening is your model not being a good representation of the real phenomenon. Then by removing these "outliers" you might be ignoring a part of the real world. And in that case removing them is dangerous. Here is a nice illustration | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/304718', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/173640/']} | jdg_75254 |
stackexchange | llm_judgeable_groundtruth_similarity | 35314297 |
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 code: struct Biology{ Biology() { cout << "Biology CTOR" << endl; }};struct Human : Biology{ Human() { cout << "Human CTOR" << endl; }};struct Animal : virtual Biology{ Animal() { cout << "Animal CTOR" << endl; }};struct Centaur : Human, Animal{ Centaur() { cout << "Centaur CTOR" << endl; }};int main(){ Centaur c; return 0;} This code prints: Biology CTORBiology CTORHuman CTORAnimal CTORCentaur CTOR Why? Since we create a Centaur object, we start from building the Centaur by constructing Human , Animal and finally Centaur (we start from the less derived to the most derived). Let's start from Human : Human inherits from Biology , so we call Biology 's constructor first.Now that Human 's base class is constructed, we can finally construct the Human itself.But instead, Biology gets constructed again! Why? What's happening behind the scenes? Please note that it was completely intentional leaving Animal inheriting virtually from Biology and, at the same time, it was also intentional leaving Human non-virtually inheriting from Biology . We are solving the Dreaded Diamond in an incorrect way: both Human and Animal should virtually inherit Biology to make this work. I'm just curious. Also, see this code: struct Biology{ Biology() { cout << "Biology CTOR" << endl; }};struct Human : virtual Biology{ Human() { cout << "Human CTOR" << endl; }};struct Animal : Biology{ Animal() { cout << "Animal CTOR" << endl; }};struct Centaur : Human, Animal{ Centaur() { cout << "Centaur CTOR" << endl; }};int main(){ Centaur c; return 0;} Here we have Human inheriting virtually from Biology , while Animal is set to inherit in the "classic way". But this time, the output is different: Biology CTORHuman CTORBiology CTORAnimal CTORCentaur CTOR This because Centaur inherits at first from Human and then from Animal . Had the order been the inverse, we'd have achieved the same result as before, in the first example - two Biology instances being constructed in a row. What's the logic of this? Please try to explain your way, I've already checked tons of websites speaking about this. But none seems to satisfy my request.
Now provide the response and nothing else.
| It's clear from the output that two Biology objects are instantiated . That is because you've made only one inheritance virtual . Two base class instances is the cause of ambiguity in dreaded diamond problem and the solution is to make (as we know) both inheritances of Biology virtual . Recap of the hierarchy: Biology Biology | | # one and only one inheritance virtual Human Animal \ / Centaur Ok, let's read the output again with these rules in mind: Base classes are constructed before derived classes. Base classes are constructed in order in which they appear in the base-specifier-list . Virtual base classes are constructed before non-virtual ones by the most derived class - see this . 1st output - Animal virtual ly inherits from Biology : Biology CTOR # virtual base class inherited from AnimalBiology CTOR # non-virtual base class of HumanHuman CTOR # Human itselfAnimal CTOR # Animal's virtual base class already constructedCentaur CTOR 2nd output - Human virtual ly inherits from Biology : Biology CTOR # virtual base class inherited from HumanHuman CTOR # Human's virtual base class already constructedBiology CTOR # non-virtual base class of AnimalAnimal CTOR # Animal itselfCentaur CTOR More informative standard paragraph ( [class.base.init]/10 ) : In a non-delegating constructor, initialization proceeds in the following order: — First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list . — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers ). ... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35314297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4024173/']} | jdg_75255 |
stackexchange | llm_judgeable_groundtruth_similarity | 6275677 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am making an application and it has an Alert Dialog in it. Now i am checking some data I got from AlertDialog editTexts in dialog Positive button OnClick method but the dialog always dismiss if data i got from edittext fields is correct or not. How can we disable this feature. UPDATED: I am gettin Pin Code and Confirm Pin Code from the Dialog Box and in onPositive click i have checked to verify the pin codes. Now if the pin codes matches then it is calling dialog.dismiss() and if not matching then display a Toast. But in case of pin code not matched it displays me the message and dismiss the dialog. I dont want that to be happen. MORE UPDATES: is there any way that i will disable the OK Button and when data is verified it will enable the positive Button?? Please help
Now provide the response and nothing else.
| This is the trick (override onClickListener inside onShowListener): final AlertDialog d = new AlertDialog.Builder(context) .setView(v) .setTitle(R.string.my_title) .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { //Do nothing here. We override the onclick } }) .setNegativeButton(android.R.string.cancel, null) .create(); d.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button b = d.getButton(AlertDialog.BUTTON_POSITIVE); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO Do something //Dismiss once everything is OK. d.dismiss(); } }); } }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6275677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/521015/']} | jdg_75256 |
stackexchange | llm_judgeable_groundtruth_similarity | 33530011 |
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 created a class with two fields that need to be dates, start_date and date_passed . I have been researching the best way in java to have dates in a YYYY MM DD format that allows for easy date subtraction, and the ability to "make-up" a date, say in the future for example. Example of what I'd like it to do... library.circulate_book("Chemistry", **start date here**) //actual date or random datelibrary.pass_book("Chemistry", **Date Passed here**) //random date such as 5 days after start dateint days_had = Date_Passed - start_date So far, I've found plenty of ways to format dates using Calendars and Date classes, but have yet to find one that looks like it would work considering most dates end up as Strings. Any suggestions/small examples are greatly appreciated! Also, any links to examples would be awesome!
Now provide the response and nothing else.
| tl;dr To move from one date to another by adding/subtracting a number of days. LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ).minusDays( 5 ) To calculate the number of days, months, and years elapsed between two dates. ChronoUnit.DAYS.between( start , stop ) Parsing First you must parse your string inputs into date-time objects. Then you work on preforming your business logic with those objects. Stop thinking of date-time values as strings, that will drive you nuts. We work with date-time objects in our code; we exchange data with users or other apps using a String representation of that date-time object. In Java 8 and later, use the java.time framework. See Tutorial . You want only a date, without time-of-day, so we can use the LocalDate class. That funky double-colon syntax is a method reference , a way to say what method should be called by other code. String input = "2015 01 02";DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyy MM dd" );LocalDate localDate = formatter.parse ( input , LocalDate :: from ); Current date Determining today’s date requires a time zone. For any given moment, the date varies around the globe by zone. ZoneId z = ZoneId.of( "Africa/Tunis" ) ;LocalDate todayTunis = LocalDate.now( z ) ; If you want the JVM’s current default time zone, call ZoneId.systemDefault . Subtracting Dates This has been addressed many times before on StackOveflow.com. For example, How to subtract X days from a date using Java calendar? . For details, see other Answers such as this one by me and this one by me for more details. Tip: "elapsed" is a key search word. Use ChronoUnit.DAYS enum to calculate count of days elapsed. LocalDate weekLater = localDate.plusDays ( 7 );long daysElapsed = java.time.temporal.ChronoUnit.DAYS.between( todayTunis , weekLater ) ; Dump to console. System.out.println ( "localDate: " + localDate + " to " + weekLater + " in days: " + daysElapsed ); localDate: 2015-01-02 to 2015-01-09 in days: 7 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33530011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2175534/']} | jdg_75257 |
stackexchange | llm_judgeable_groundtruth_similarity | 1562074 |
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 figure out what version of Boost my code thinks it's using. I want to do something like this: #error BOOST_VERSION but the preprocessor does not expand BOOST_VERSION. I know I could print it out at run-time from the program, and I know I could look at the output of the preprocessor to find the answer. I feel like having a way of doing this during compilation could be useful.
Now provide the response and nothing else.
| I know that this is a long time after the original query, but this may still be useful. This can be done in GCC using the stringify operator "#", but it requires two stages. #define XSTR(x) STR(x)#define STR(x) #x The value of a macro can then be displayed with: #pragma message "The value of ABC: " XSTR(ABC) See: 3.4 Stringification in the gcc online documentation. How it works: The preprocessor understands quoted strings and handles them differently from normal text. String concatenation is an example of this special treatment. The message pragma requires an argument that is a quoted string. When there is more than one component to the argument then they must all be strings so that string concatenation can be applied. The preprocessor can never assume that an unquoted string should be treated as if it were quoted. If it did then: #define ABC 123int n = ABC; would not compile. Now consider: #define ABC abc#pragma message "The value of ABC is: " ABC which is equivalent to #pragma message "The value of ABC is: " abc This causes a preprocessor warning because abc (unquoted) cannot be concatenated with the preceding string. Now consider the preprocessor stringize (Which was once called stringification, the links in the documentation have been changed to reflect the revised terminology. (Both terms, incidentally, are equally detestable. The correct term is, of course, stringifaction. Be ready to update your links.)) operator. This acts only on the arguments of a macro and replaces the unexpanded argument with the argument enclosed in double quotes. Thus: #define STR(x) #xchar *s1 = "abc";char *s2 = STR(abc); will assign identical values to s1 and s2. If you run gcc -E you can see this in the output. Perhaps STR would be better named something like ENQUOTE. This solves the problem of putting quotes around an unquoted item, the problem now is that, if the argument is a macro, the macro will not be expanded. This is why the second macro is needed. XSTR expands its argument, then calls STR to put the expanded value into quotes. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1562074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6160/']} | jdg_75258 |
stackexchange | llm_judgeable_groundtruth_similarity | 1796440 |
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:
$$\lim_{x\to-2} \frac{x+2}{\sqrt{6+x}-2}=\lim_{x\to-2} \frac{1+2/x}{\sqrt{(6/x^2)+(1/x)}-2/x^2}$$ Dividing numerator and denominator by $x \neq0$ $$\frac{1+2/-2}{\sqrt{(6/4)+(1/-2)}-2/4}=\frac{0}{1/2}=0$$ but the limit is $4$ according to Wolfram Alpha?
Now provide the response and nothing else.
| You say you divide by $x$, but that's not what you do in the denominator; it would be: $$\lim_{x\to-2} \frac{x+2}{\sqrt{6+x}-2}=\lim_{x\to-2} \frac{1+\tfrac{2}{x}}{\tfrac{\sqrt{6+x}}{x}-\tfrac{2}{x}} =\lim_{x\to-2} \frac{1+\tfrac{2}{x}}{-\sqrt{\tfrac{6}{x^2}+\tfrac{1}{x}}-\tfrac{2}{x}} $$ A better approach:$$\begin{array}{rl}\displaystyle \lim_{x\to-2} \frac{x+2}{\sqrt{6+x}-2}& \displaystyle = \lim_{x\to-2} \frac{\left(x+2\right)\color{blue}{\left(\sqrt{6+x}+2\right)}}{\left(\sqrt{6+x}-2\right)\color{blue}{\left(\sqrt{6+x}+2\right)}} \\[7pt]& \displaystyle = \lim_{x\to-2} \frac{\left(x+2\right)\left(\sqrt{6+x}+2\right)}{x+2} \\[7pt]& \displaystyle = \lim_{x\to-2} \left(\sqrt{6+x}+2\right) \\& = 4\end{array}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1796440', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/341627/']} | jdg_75259 |
stackexchange | llm_judgeable_groundtruth_similarity | 4381290 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why am I getting this exception? package com.domain.idea;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.JoinColumn;import javax.persistence.OneToOne;import javax.persistence.Table;import org.hibernate.annotations.AccessType;/** * object model for the view [InvestmentReturn].[vMAE_MFE] */@Entity@Table(name="vMAE_MFE", schema="InvestmentReturn")@AccessType("field")public class MAE_MFEView{ /** * trade property is a SuggestdTradeRecommendation object */ @OneToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST }) @JoinColumn(name = "suggestedTradeRecommendationID") private SuggestedTradeRecommendation trade; /** * Most Adeverse Excursion value */ private int MAE; public int getMAE() { return MAE; } /** * Most Favorable Excursion value */ private int MFE; public int getMFE() { return MFE; } /** * @return trade property * see #trade */ public SuggestedTradeRecommendation getTrade() { return trade; }} Update: I've changed my code to look like this: package com.domain.idea;import javax.persistence.CascadeType;import javax.persistence.FetchType;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.OneToOne;import javax.persistence.Table;import org.hibernate.annotations.AccessType;/** * object model for the view [InvestmentReturn].[vMAE_MFE] */@Entity@Table(name="vMAE_MFE", schema="InvestmentReturn")@AccessType("field")public class MAE_MFEView{ /** * trade property is a SuggestdTradeRecommendation object */ @Id @OneToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST }) @JoinColumn(name = "suggestedTradeRecommendationID") private SuggestedTradeRecommendation trade; /** * Most Adeverse Excursion value */ private int MAE; public int getMAE() { return MAE; } /** * Most Favorable Excursion value */ private int MFE; public int getMFE() { return MFE; } /** * @return trade property * see #trade */ public SuggestedTradeRecommendation getTrade() { return trade; }} but now I'm getting this exception: Caused by: org.hibernate.MappingException: Could not determine type for: com.domain.idea.SuggestedTradeRecommendation, at table: vMAE_MFE, for columns: [org.hibernate.mapping.Column(trade)] at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:292) at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:276) at org.hibernate.mapping.RootClass.validate(RootClass.java:216) at org.hibernate.cfg.Configuration.validate(Configuration.java:1135) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1320) at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867) at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669) ... 145 more
Now provide the response and nothing else.
| You are missing a field annotated with @Id . Each @Entity needs an @Id - this is the primary key in the database. If you don't want your entity to be persisted in a separate table, but rather be a part of other entities, you can use @Embeddable instead of @Entity . If you want simply a data transfer object to hold some data from the hibernate entity, use no annotations on it whatsoever - leave it a simple pojo. Update: In regards to SQL views, Hibernate docs write: There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4381290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226473/']} | jdg_75260 |
stackexchange | llm_judgeable_groundtruth_similarity | 23821014 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I had some html like this: <ul> <li> 1 </li> <li> 2 </li></ul><ul> <li> a </li> <li> b </li></ul> This HTML was generated using CKEditor, but I got fed up with WYSIWYGs and decided to use markdown instead. I then converted it to markdown. My markdown looks like: - 1- 2- a- b However my output from my markdown is this: <ul> <li> 1 </li> <li> 2 </li> <li> a </li> <li> b </li> </ul> I need two separate lists as per the html prior to conversion. Can this be done?
Now provide the response and nothing else.
| First I'll clarify the undesired behaviour, then I'll show you how to get the desired behaviour. Undesired Behaviour - Concatenated Lists: Markdown implementations often concatenate lists separated by whitespace. For example, the following markdown has 5 lists - a- a- b- a - b- a - b- c- a - b - c and it renders as one big list: a a b a b a b c a b c Desired Behaviour - Separated lists: To get separate lists to render separately, separate your markdown lists with something that maps from markdown to invisible HTML . Each of these work fine: an HTML comment: <!-- --> a linebreak: <br> a non-breaking space: Below are 4 markdown lists using each of them - a<!-- -->- a- b<br>- a - b - a - b- c which render as 4 separate lists: a a b a b a b c | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23821014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/818951/']} | jdg_75261 |
stackexchange | llm_judgeable_groundtruth_similarity | 1034802 |
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 class representing an interval. This class has two properties "start" and "end" of a comparable type. Now I'm searching for an efficient algorithm to take the union of a set of such intervals. Thanks in advance.
Now provide the response and nothing else.
| Sort them by one of the terms (start, for example), then check for overlaps with its (right-hand) neighbor as you move through the list. class tp: def __repr__(self): return "(%d,%d)" % (self.start, self.end) def __init__(self, start, end): self.start = start self.end = ends = [tp(5, 10), tp(7, 8), tp(0, 5)]s.sort(key=lambda self: self.start)y = [s[0]]for x in s[1:]: if y[-1].end < x.start: y.append(x) elif y[-1].end == x.start: y[-1].end = x.end | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1034802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47009/']} | jdg_75262 |
stackexchange | llm_judgeable_groundtruth_similarity | 306 |
Below is a question asked on the forum computergraphics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Signed Distance Fields (SDFs) was presented as a fast solution to achieve resolution independent font rendering by Valve in this paper . I already have the Valve solution working but I'd like to preserve sharpness around corners. Valve states that their method can achieve sharp corners by using a second texture channels ANDed with the base one, but lacks to explain how this second channel would be generated. In fact there's a lot of implementation details left out of this paper. I'd like to know if any of you could point me out a direction to get SDFs font rendering with sharp corners.
Now provide the response and nothing else.
| EDIT: Please see my other answer with a concrete solution. I have actually solved this exact problem over a year ago for my master's thesis. In the Valve paper, they show that you can AND two distance fields to achieve this, which works as long as you only have one convex corner. For concave corners, you also need the OR operation. This guy actually developed some obscure system to switch between the two operations using four texture channels. However, there is a much simpler operation that can facilitate both AND and OR depending on the situation, and this is the principal idea of my thesis: the median of three . So basically, you use exactly three channels (ideal for RGB), which are completely interchangeable, and combine them using the median operation (choose the middle value out of the three). To accomodate anti-aliasing, we don't work with just booleans, but floating point values, and the AND operation becomes the minimum, and the OR becomes the maximum of two values. The median of three can indeed do both: if a < b , for ( a , a , b ), the median is the minimum, and for ( a , b , b ), it is the maximum. The rendering process is still extremely simple. The entire fragment shader including anti-aliasing can look something like this: int main() { // Bilinear sampling of the distance field vec3 s = texture2D(sdf, p).rgb; // Acquire the signed distance float d = median(s.r, s.g, s.b) - 0.5; // Weight between inside and outside (anti-aliasing) float w = clamp(d/fwidth(d) + 0.5, 0.0, 1.0); // Combining the background and foreground color gl_FragColor = mix(outsideColor, insideColor, w);} So the only difference from the original method is computing the median right after sampling the texture. You will have to implement the median function though, which can be done with just 4 min/max operations . Now of course, the question is, how do I build such a three-channel distance field? And this is the tricky part. The most obvious approach that I took in the beginning was to perform a decomposition of the input shape/glyph into three components, and then generate a conventional distance field out of each. The rules for this decomposition aren't that complicated. Firstly , the area with at least 2 out of 3 channels on is the inside. Then, if you imagine this as the RGB color channels, convex corners must be made of a secondary color, and its two primary components continue outward. Concave corners are the inverse: Two secondary colors enclose their common primary color, and the wedge between where both edges continue inward is white. I also found that some padding is necessary where two primary or two secondary colors would otherwise touch to avoid artifacts (for example, in the middle stroke of the "N" in the picture). The following image is an example decomposition generated by the program from my thesis: This approach however has some drawbacks. One of them is that the special effects, such as outlines and shadows will no longer work correctly. Fortunatelly, I also came up with a second, much more elegant method, which generates the distance fields directly, and even supports all of the graphical effects. It is also included in my thesis and so is also over a year old. I am not going to give any more details right now, because I am currently writing a paper that describes this second technique in detail, but I will post it here as soon as it's finished. Anyway, here is an example of the difference in quality. The texture resolution is the same in each image, but the left one uses a regular texture, the middle one uses an ordinary distance field, and the right one uses my three-channel distance field. The performance overhead is only the difference between sampling an RGB texture versus a monochrome one. | {} | {'log_upvote_score': 6, 'links': ['https://computergraphics.stackexchange.com/questions/306', 'https://computergraphics.stackexchange.com', 'https://computergraphics.stackexchange.com/users/250/']} | jdg_75263 |
stackexchange | llm_judgeable_groundtruth_similarity | 56245 |
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:
During the time of David and Solomon, the original Tabernacle of the Lord made by Moses was located in Gibeon (ex. 1 Ch 16:39, 21:29). But in 2 Sam 6:17 and 1 Ch 16:1, it said David moved the ark into the tabernacle in Jerusalem that David erected. I see that the Strong's definitions of the tabernacle/tent used in 1 Ch 16:1 is also different than that of 16:39. However both seem acceptable to refer to the original tabernacle. It would also seem to be a great irreverence to move the ark into a different tent. I've read some websites that made a great distinction of the two tabernacles. But I'm not sure if that's the common interpretation - that there were two tabernacles during the time of David. If so, are there other references in the bible that made a distinction of the tabernacle of David and the tabernacle of Moses? Do they carry different functions or meanings?
Now provide the response and nothing else.
| I want to offer an alternate perspective, mostly because I think several faulty lines of reasoning have been proposed for why it is "unlikely" that πέτρα refers to Πέτρος. My response will be divided into three parts: Against objections Reasons in favor Other testimonies Let me start by acknowledging a strong parallel brought up by Dottard. I think this is the strongest evidence in favor of the reading that πέτρα refers to Christ himself (or Peter's declaration): καὶ πάντες τὸ αὐτὸ πνευματικὸν βρῶμα ἔφαγον καὶ πάντες τὸ αὐτὸ πνευματικὸν ἔπιον πόμα, ἔπινον γὰρ ἐκ πνευματικῆς ἀκολουθούσης πέτρας, ἡ πέτρα δὲ ἦν ὁ χριστός . (1 Cor 10:3-4) RSV Translation: and all ate the same supernatural food 4 and all drank the same supernatural[b] drink. For they drank from the supernatural Rock which followed them, and the Rock was Christ . Despite this passage, though, I find it very difficult to interpret Mt 16:18 as not referring to Peter. I will start by responding to some weak arguments against this reading, and then I will defend what I think is the clear, straightforward reading. 1. Against objections Two of the above answers rely heavily on the fact that πέτρα is feminine and Πέτρος is masculine. How could the former refer to the latter? To this objection, a few observations should suffice: Despite the language used in these answers, talk of "antecedents" or "agreement of grammatical gender" is misguided. A pronoun agrees with its antecedent in gender and number. But πέτρα is not a pronoun. If we wished to maintain that a noun had to agree in gender with the person to whom it refers, we would be committed to absurdities. Consider, for instance, three famous examples from the Gospel of John: ἐγώ εἰμι ὁ ἄρτος τῆς ζωῆς. (6:35) ἐγώ εἰμι τὸ φῶς τοῦ κόσμου. (8:12) ἐγώ εἰμι ἡ ἀνάστασις καὶ ἡ ζωή. (11:25) Any argument that the neuter or feminine terms couldn't apply to Christ Himself is just a basic misunderstanding of how grammatical gender works. Another argument mentioned by Dottard in his translation is that πέτρος refers to a "stone" while πέτρα refers to a "large rock," and that a Greek ear would have drawn a sharp distinction between these two things. It is true that the two are not interchangeable as common nouns, as the LSJ entries for each attest . My first observation is textual: πέτρος is never used in the New Testament to refer to a stone. In fact, even the Septuagint only uses the word in this way twice, in 2 Maccabees 1:16 and 4:41. The New Testament frequently (56x by my count) and exclusively uses λίθος for a "stone." My second observation is commonsensical: Though feminine-gender nouns can be used to refer to men, they would never be used to name a man. If Christ wanted to give Simon a new name meaning "rock," he certainly couldn't have named him Πέτρα. Πέτρος is a natural way to express this as a male name. (I am not an expert in Aramaic, but I also recall reading that this grammatical shift would have been entirely unnecessary in the language that Christ actually spoke these words in. Both words would have been "Kepha." According to Wikipedia this is also true of the Syriac version.) My final observation is that Greek ears never (as far as I can make out) noted this as a source of problems. For evidence, see my third section below with Patristic testimony. 2. Reasons in favor Having addressed these arguments, what are some positive reasons to think that πέτρα refers to Πέτρος? To this, I can only say that we should consider the dramatic situation and ask ourselves what makes sense. Read the whole passage: Ἀποκριθεὶς δὲ Σίμων Πέτρος εἶπεν· σὺ εἶ ὁ χριστὸς ὁ υἱὸς τοῦ θεοῦ τοῦ ζῶντος. Ἀποκριθεὶς δὲ ὁ Ἰησοῦς εἶπεν αὐτῷ· μακάριος εἶ, Σίμων Βαριωνᾶ , ὅτι σὰρξ καὶ αἷμα οὐκ ἀπεκάλυψέν σοι ἀλλ᾽ ὁ πατήρ μου ὁ ἐν τοῖς οὐρανοῖς. κἀγὼ δέ σοι λέγω ὅτι σὺ εἶ Πέτρος καὶ ἐπὶ ταύτῃ τῇ πέτρᾳ οἰκοδομήσω μου τὴν ἐκκλησίαν, καὶ πύλαι ἅδου οὐ κατισχύσουσιν αὐτῆς. (Mt 16:16-18) Simon Peter answers Christ's question with remarkable faith. Christ first addresses him by his birth name, Simon, and then proceeds ("κἀγὼ δέ σοι λέγω...") to give him a new name, Πέτρος, and immediately say that he will build his church on this πέτρα . ταύτῃ is the dative feminine singular form of the "close" demonstrative adjective. Why would Christ address Simon by a new name, and then--in the very next phrase!--use that name exclusively to refer to himself? It's also telling that Christ goes on in the following verse to give Peter extraordinary authority. Why seesaw ("You are Peter. I am the rock. You shall have the keys.") when the straightforward reading makes more sense? Imagine a similar monologue: "Brian, your name shall be Hunter, and this hunter shall provide food from now on." Even if the speaker is a hunter, one has to do interpretative gymnastics not to connect the second "hunter" with the first. Of course, it's another question entirely in what capacity this πέτρα refers to Peter. It could refer to him as a person or him as a representative of faith. But this reference only works because it is grounded on the reference to Peter himself. 3. Other testimonies My final set of observations: Doesn't this make sense? We can appeal first to Scripture. Doesn't this fit, for instance, with the injunction to "Feed my sheep" at the end of John's gospel, as well as the clear leadership role that Peter assumes in the early church? I will also include a quick smattering from Greek-speaking Church fathers. Here are the first three relevant examples I found (I promise I did not "skip" any patristic counterexamples-though perhaps there are some!) BASILIUS Caesariensis, Homilia de paenitentia [Sp.] (sub auctore Eusebio Emeseno). {2040.060} - (N.B. I don't have the time to track this work down, but the "sp." means that it spurious--i.e. falsely attributed to Basil.): Ἀλλὰ Πέτρος εἰπὼν καὶ εὐλογηθεὶς, εἰπὼν, ὅτι «Υἱὸς εἶ τοῦ Θεοῦ» τοῦ ὑψίστου, καὶ ἀκούσας, ὅτι «Πέτρα εἶ,» ἐνεγκωμιάσθη. Εἰ γὰρ καὶ πέτρα, οὐχ ὡς Χριστὸς πέτρα, ὡς Πέτρος πέτρα · Χριστὸς γὰρ ὄντως πέτρα ἀσάλευτος· Πέτρος δὲ διὰ τὴν πέτραν. My quick translation: But Peter having spoken and having been blessed--having spoken, that "You are the Son of God" the highest, and having heard, that "You are Peter"--was lauded. For if he was also a πέτρα, Peter was a πέτρα not in the same way Christ was a πέτρα. For Christ was truly the unmoving πέτρα, but Peter was [so] through [Christ] the πέτρα. What I find significant about this passage is that it clearly takes the πέτρα to refer to Peter himself, while also tying it to the "problematic" 1 Cor 10 reading that I mentioned at the beginning of this post. The "contrary" evidence was interpreted as complementary here and in what follows: ORIGENES, Fragmenta in evangelium Joannis (in catenis). {2042.006}Current Text Πέτρον δὲ αὐτὸν κληθήσεσθαι εἶπεν, παρονομασθέντα ἀπὸ τῆς πέτρας, ἥτις ἐστὶν ὁ χριστός· ἵν’ ὥσπερ ἐκ σοφίας σοφὸς καὶ ἅγιος ἐξ ἁγιότητος, οὕτως καὶ ἐκ τῆς πέτρας Πέτρος . ἀποδείκνυται δὲ τοῦτο ἐξ ὧν εἶπεν ὁ σωτὴρ πρὸς τὸν οὕτως ὠνομασμένον· «Σὺ εἶ, φησίν, Πέτρος, καὶ ἐπὶ ταύτῃ τῇ πέτρᾳ οἰκοδομήσω μου τὴν ἐκκλησίαν». My translation: He [Christ] said he would be called Peter, "nicknamed" [παρονομασθέντα] from πέτρα, which is Christ, so that just as σοφία [wisdom: feminine] comes from σοφὸς and 'holiness' from 'holy,' so too Πέτρος comes from πέτρα . What our savior said to the one who was so called is proof of this: "You are," he said, "Peter, and upon this πέτρα I shall build my Church. As before, Origen expresses no doubt that "Peter" and "πέτρα" are supposed to be paired together. He is equally clear, as before, that Peter's status as a "rock" is grounded on Christ the original rock. (N.B. This is not the same thing as saying that Peter himself is not the rock referred to.) Finally, JOANNES CHRYSOSTOMUS, De paenitentia (homiliae 1-9). {2062.027}Current Text: Κλαῦσον ἐπὶ τῇ ἁμαρτίᾳ σου, καὶ διδάχθητι ἐκ τῶν θείων Εὐαγγελίων τοῦτοΠέτρος ἐκεῖνος, ἡ κορυφὴ τῶν ἀποστόλων, ὁ πρῶτος ἐν τῇ Ἐκκλησίᾳ, ὁ φίλος Χριστοῦ, ὁ τὴν ἀποκάλυψιν παρὰ ἀνθρώπων μὴ δεξάμενος, ἀλλὰ παρὰ τοῦ Πατρὸς, καθὼς αὐτῷ μαρτυρεῖ ὁ Δεσπότης λέγων· Μακάριος εἶ, Σίμων Βαριωνᾶ, ὅτι σὰρξ καὶ αἷμα οὐκ ἀπεκάλυψέ σοί, ἀλλ’ ὁ Πατήρ μου ὁ οὐράνιος· οὗτος ὁ Πέτρος· Πέτρον δὲ ὅταν εἴπω, τὴν πέτραν λέγω τὴν ἀῤῥαγῆ , τὴν κρηπῖδα τὴν ἀσάλευτον, τὸν ἀπόστολον τὸν μέγαν, τὸν πρῶτον τῶν μαθητῶν, τὸν πρῶτον κληθέντα, καὶ πρῶτον ὑπακούσαντα. My translation: Griever for your sin, and let that Peter be your teacher from the Holy Gospels, the head of the apostles, the first in the Church, the friend of Christ, the one who did not receive revelation from men but from the Father, as the Lord witnesses to him when he says: "Blessed are you, Simon Bar Jona, for flesh and blood have not revealed this to you, but my heavenly Father." This is Peter. And when I say "Peter," I am talking about the unbroken πέτρα , the unmoving foundation, the great apostle, the first of the disciples, the first to be called, and the first to hearken. These are the first three patristic testimonies I found when I did a proximity search for both terms together. I would be surprised (but grateful to learn!) if there was a Greek-speaking father who did not see the πέτρα as referring to Peter. (N.B. My source for word counts is the TLG Greek Corpus.) | {} | {'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/56245', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/40889/']} | jdg_75264 |
stackexchange | llm_judgeable_groundtruth_similarity | 81556 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Computational Complexity Theory is complex. My understanding of polynomial time is in relation to other time complexity classes, such as non-deterministic polynomial time. This is fine for engineers and mathematicians, but I'm looking for a simple definition of the term, suitable for laypeople. Would it be incorrect to cast polynomial time as "time measured in (computational) operations?" Obviously there would be subsequent qualifications for different time complexity classes, and time complexity may be more properly a ratio based on the problem size, but again, that's a bit more complex than what I'm looking for here.
Now provide the response and nothing else.
| Would it be incorrect to cast polynomial time as "time measured in (computational) operations?" Yes. Completely incorrect. "Time" does indeed mean "time measured in (computational) operations" but you've not translated "polynomial" at all. It's like translating "twelve days" as "time measured in number of rotations of the earth on its axis." That's exactly what what "day" means, but what happened to "twelve"? Polynomials are inherently mathematical objects and I doubt there's any way of explaining them without using mathematics. You can explain that polynomial algorithms are usually regarded as being reasonably efficient, but that's a consequence of what a polynomial relationship is, not an explanation of it. | {} | {'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/81556', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/57340/']} | jdg_75265 |
stackexchange | llm_judgeable_groundtruth_similarity | 1963099 |
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:
Why is $\int \frac{dx}{x^2+1} = \arctan(x)$? I understand the proofs of it, I guess I just don't get the intuition behind it. If I hadn't been taught (and then looked up the derivation) of this fact, I would've thought it was related to the natural log, like $\int \frac{dx}{x}$. So my question is, what mechanism causes this to not be of the same form?
Now provide the response and nothing else.
| It is related to the natural log, as follows. You can use partial fraction decomposition over $\mathbb{C}$ to rewrite the integrand as $$\frac{1}{x^2 + 1} = \frac{1}{2i} \left( \frac{1}{x - i} - \frac{1}{x + i} \right)$$ and then integrating gives, at least formally, $$\int \frac{dx}{x^2 + 1} = \frac{1}{2i} \left( \log (x - i) - \log (x + i) \right) = \frac{1}{2i} \log \frac{x-i}{x+i} + C.$$ It's true but not obvious that this is also $\arctan x$. The idea here is to use Euler's formula $$\cos x + i \sin x = e^{ix}$$ to express $\tan x$ in terms of complex exponentials. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1963099', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/305671/']} | jdg_75266 |
stackexchange | llm_judgeable_groundtruth_similarity | 21600383 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Adding a javascript inside my view results in the ReferenceError: $ is not defined . I assume that the problem is due to Yii2 injects scripts last on my page. How to fix this? Or how will I prevent Yii2 from autoloading the script files? My view <?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\helpers\UrlManager; use yii\widgets\ActiveForm; use backend\controllers\StandardController; use backend\models\standard; ?> <div class="domain-form"><?php $form = ActiveForm::begin(); ?><?php <?= $form->field($model, 'clause')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'name')->textarea(['rows' => 6]) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div><?php ActiveForm::end(); ?> </div> <script type="text/javascript"> $("document").ready( function () { alert("hi"); });</script> I need to get this simple script to show an alert after the page loaded. I hav'nt called any of the script file here since yii loads automatically(i think) in the layout by calling AppAsset::register($this); This results in script files to be registered at the end of the page,after my custom script. How to solve this?
Now provide the response and nothing else.
| Yii2 injects scripts (jquery and the like) last on your page. This is intended and desired. But it means that the jQuery will load AFTER your script, so when your script runs, jQuery does not yet exist. The easiest way for quick testing is to move yii-scripts (jquery and the like) to the head of the page. Modify assets\AppAsset.php and add this: public $jsOptions = array( 'position' => \yii\web\View::POS_HEAD); Done! But in production you usually want the scripts to load last, and instead you let Yii2 handle your javascript: $this->registerJs( '$("document").ready(function(){ alert("hi"); });'); Now Yii will handle this js and place it after anything important (like jQuery). You'll however soon notice that IDE's are usually bad at handling this kind of language nesting (JavaScript inside PHP) so the syntax highlighting is likely to break. One way to solve it is to register your script in a separate file: $this->registerJsFile( 'myScript.js' ); If you want even more control about which order to load your scripts, you can add dependencies as your second argument, and additional options as the third: $this->registerJsFile( 'myScript.js', ['\backend\assets\AppAsset'], ['position' => '\yii\web\View::POS_END']); If you for some reason absolutely want the script to be rendered inline you can do: $this->registerJs( $this->renderPartial('myScript.js') ); The recommended way to add your scripts is to use AssetBundles . Look in assets/AppAssets.php and add your js-file to the $js-array. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21600383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2775597/']} | jdg_75267 |
stackexchange | llm_judgeable_groundtruth_similarity | 8779631 |
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 web application using maven spring and hibernate and I need to create schema using hibernate for which I had the following in my pom.xml to connect to MySQL 5.5 database. <!-- MySql 5.5 Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.15</version> </dependency> This imported mysql-connector-java-5.1.15.jar in my Libraries under Maven Dependencies but when I try to connect to database it gives me Exception in thread "main" org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver . I have done this like gazillions of times, but I did it when I din't used to use Maven to manage my dependencies and build the project. I just used to have it the same jar file in the lib folder of a Dynamic Web Project in Eclipse IDE. Could someone tell me what am I missing here and what else I need to have this jar in my build path? Thanks.
Now provide the response and nothing else.
| To start with, the jar that I need to connect to MySQL 5.5 should have been mysql-connector-java-5.1.15-bin.jar but not mysql-connector-java-5.1.15.jar . Secondly, this jar is not available in maven repository so I needed to manually add it to my local maven repository and then added it as a dependency in my pom.xml . Adding mysql-connector-java-5.1.15-bin.jar to the local maven repository by mvn install:install-file -Dfile=C:\Libraries\mysql-connector-java-5.1.15-bin\mysql-connector-java-5.1.15-bin.jar -DgroupId=mysql -DartifactId=mysql-connector-java -Dversion=5.1.15-bin -Dpackaging=jar and then adding the following dependency to pom.xml of the project. <!-- MySql 5.5 Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.15-bin</version> </dependency> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8779631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411449/']} | jdg_75268 |
stackexchange | llm_judgeable_groundtruth_similarity | 37575722 |
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 it possible to do SQL inner joins kind of stuff in MongoDB? I know there is the $lookup attribute in an aggregation pipeline and it is equivalent to outer joins in SQL, but I want to do something similar to inner joins . I have three collections which need to merge together: // User Collectiondb.User.find({});// Output:{ ID : 1, USER_NAME : "John", password : "pass"}{ ID : 2, USER_NAME : "Andrew", PASSWORD : "andrew"}// Role Collectiondb.ROLE.find({});// Output:{ ID : 1, ROLE_NAME : "admin"},{ ID : 2, ROLE_NAME : "staff"}// USER_ROLE Collectiondb.USER_ROLE.find({});// Output:{ ID : 1, USER_ID : 1, ROLE_ID : 1} I have the above collections and I want to extract only the documents matched with users and their respective roles, not all the documents. How can I manage it in MongoDB?
Now provide the response and nothing else.
| As Tiramisu wrote this looks like schema issue. You can make a manual inner join, by removing documents where $lookup returned empty array. ....{$lookup... as myArray},{$match: {"myArray":{$ne:[]}}},{$lookup... as myArray2},{$match: {"myArray2":{$ne:[]}}}, schema change I personally will go for schema update, like this: db.User.find({}){ ID : 1, USER_NAME : "John", password : "pass" roles:[{ID : 1, ROLE_NAME : "admin"}]}db.ROLE.find({}){ ID : 1, ROLE_NAME : "admin"}, | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37575722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6323944/']} | jdg_75269 |
stackexchange | llm_judgeable_groundtruth_similarity | 19119623 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields. public abstract Base{ protected int field1; protected int field2; .... protected Base() { ... }} Sometimes I need to clone the derived class. So my guess was, just make a virtual Clone method in my base class and only override it in derived classes that have additional fields, but of course my Base class wouldn't be abstract anymore (which isn't a problem since it only has a protected constructor). public Base{ protected int field1; protected int field2; .... protected Base() { ... } public virtual Base Clone() { return new Base(); }}public A : Base { }public B : Base { } The thing is, since I can't know the type of the derived class in my Base one, wouldn't this lead to have a Base class instance even if I call it on the derived ones ? ( a.Clone(); ) (actually after a test this is what is happening but perhaps my test wasn't well designed that's why I have a doubt about it) Is there a good way (pattern) to implement a base Clone method that would work as I expect it or do I have to write the same code in every derived class (I'd really like to avoid that...) Thanks for your help
Now provide the response and nothing else.
| Just override the Clone and have another method to CreateInstance then do your stuff. This way you could have only Base class avoiding generics. public Base{ protected int field1; protected int field2; .... protected Base() { ... } public virtual Base Clone() { var bc = CreateInstanceForClone(); bc.field1 = 1; bc.field2 = 2; return bc; } protected virtual Base CreateInstanceForClone() { return new Base(); }}public A : Base { protected int fieldInA; public override Base Clone() { var a = (A)base.Clone(); a.fieldInA =5; return a; } protected override Base CreateInstanceForClone() { return new A(); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19119623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2008409/']} | jdg_75270 |
stackexchange | llm_judgeable_groundtruth_similarity | 15375886 |
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 string like This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day I wanted to basically split this one long string at the commas and insert a new line so it becomes This is great daytomorrow is a better daythe day after is a better daythe day after the day after that is the greatest day How can I do that ?
Now provide the response and nothing else.
| With the built in split and join methods var formattedString = yourString.split(",").join("\n") If you'd like the newlines to be HTML line breaks that would be var formattedString = yourString.split(",").join("<br />") This makes the most sense to me since you're splitting it into lines and then joining them with the newline character. Although I think speed is less important than readability in most cases, I was curious about it in this case so I've written a quick a benchmark . It seems that (in chrome) using str.split(",").join("\n") is faster than str.replace(/,/g, '\n'); . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15375886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109407/']} | jdg_75271 |
stackexchange | llm_judgeable_groundtruth_similarity | 50080402 |
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 the current Google Analytics tracking code, and on Firefox 59 I get this error in console: unreachable code after return statement On this javascript: https://www.googletagmanager.com/gtag/js?id=UA-my-tracking-code:formatted Since this problem doesn't seem to be googleable, hence it seems others do not have this problem, my guess is that it's me who does something wrong. But what this could be? I'm putting the snippet in <head> , just like the docs say: <!DOCTYPE html><html> <head> <title>some title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-my-tracking-code"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-my-tracking-code'); </script> </head> <body> blah blah </body></html>
Now provide the response and nothing else.
| It is not your fault. If you prettify the code with Firefox's it can be found here: Gc = function (a, b, c) { var d = a.split('.'); var e = function (a, b) { for (var c = 0; void 0 !== a && c < d.length; c++) { if (null === a) return !1; a = a[d[c]] } return void 0 !== a || 1 < c ? a : b.length ? e(Hc(b.pop()), b) : Ic(d) }; return e(Cc.eventModel, [ // <= True return value b, c ]); return Ic(d) // <= This can never be reached!}, To prettify the code: Click on the warning's blue link. You'll see the garbled code. Click on the icon with the {} on the bottom left of that panel to prettify it. However the reference will be lost. Go back to the "Console" panel and click again in the same warning's blue link. Now you'll see the original reference in the correct line. Firefox is correctly pointing the bug, the function Ic(d) will never be reached since the function returns earlier. Seems like a Google Tag Manager bug, however without inspecting the original code we cannot tell the severity. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50080402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4568686/']} | jdg_75272 |
stackexchange | llm_judgeable_groundtruth_similarity | 6368349 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I recently learned about ASSERTION in my databases course, and my prof noted that major databases don't support it, even though it is in the SQL-92 standard. I tried googling to find out why, but there doesn't seem to be any discussion on the topic. So, why isn't ASSERTION supported by the vast majority of relational database packages? Is it soley a performance issue or is there something intrinsically hard about it? If you can, please note any database packages that implement it as well (example: if there's an academic/teaching DB). Also, why is there so little discussion on the issue; it's not even mentioned in the Wikipedia page for SQL or SQL-92) But answer the main question first, or answer in comments. I'm not looking for how to implement it with triggers or anything else.
Now provide the response and nothing else.
| There are four levels of constraint: column-level, row-level, table-level and schema-level. A table-level could, for example, involve a target table other than the source table on which it was declared but only gets checked when the source table changes. In theory a schema-level constraint would be checked for every change in every table in the schema but in practise the optimizer would be able to detect changes in a more granular way; consequently, if your DBMS had support for schema-level constraint then you wouldn't find much use for table-level constraints in practise. No current SQL product supports schema-level constraints i.e. CREATE ASSERTION . Apparently Rdb did support it when it was looked after by DEC but that is no longer the case. -- UPDATE: in a private message I was advised that Sybase's SQL Anywhere supports CREATE ASSERTION but with serious errors that allow such constraints sometimes to be violated! The only SQL-like product I've used that currently supports subqueries in CHECK constraints, which enables table-level constraints, is the Access database engine (ACE, Jet, whatever). It has issues , though. First, there is not support for SQL-92 functionality (or equivalent) to defer constraint checking. Second, table-level constraints are checked for each row affected, rather than when the statement completes as required by the SQL-92 Standard. Needless to say, the workaround is very clunky e.g. drop the constraint and in doing so lock the table, execute the update, recreate the constraint. Schema-level constraints, arguably achievable by adding the same constraint to all the tables it involves, is virtually unworkable. Possibly for these reasons, the Access Team have never publicized its CHECK constraint functionality at all beyond the initial announcements for Jet 4.0 (it remains missing from the Access Help, for example). All that said, for intra-table constraints (e.g. a sequenced key in a valid-state 'history' temporal table) the functionality works well, especially when you consider that Access only got trigger-like functionality (not SQL based, though) last year. SQL of course has UNIQUE constraints and referential integrity constraints that are of course table-level but these are special cases. Therefore, all constraints you will encounter 'in the wild' will be either colum- or row-level. Do be aware with MySQL that, although using CHECK() in SQL DDL will parse without error, it will have no effect. How users can tolerate a SQL product with no CHECK constraints at all is beyond me! PostgreSQL has a excellent constraints model, hint hint :) So why are inter-table constraints so rarelt supported? One reason must be due to historical circumstances. As @gbn correctly identifies (under the title Concurrency), the Sybase/SQL Server family of SQL implementations is based on a model that cannot cope with inter-table constraint checking and that's not something that is likely to ever change. Consider looking at this the other way around: if you were creating a SQL product today, would you include CREATE ASSERTION ? If you did, you would certainly have to also implement DEFERRABLE constraints (even though multiple assignment is arguably the better model). But you would be able to draw on a lot more research and experience if you went down the route of building a 'traditional' optimizer. And perhaps you'd find there is no commercial demand for schema-level constraints (if MySQL can get anyway without CHECK constraints...) If PostgreSQL doesn't do it, I don't think anyone ever will. I think the real show stopper is that most industrial-strength products have already developed trigger functionality that allows users to write 'constraints' of arbitrary complexity (plus can a lot more e.g. send an email to tell something happened). Sure, they are procedural rather than declarative, the coder has to do a lot of extra work that the system would take care of with true constraints, and the performance tends to be not so great. But the fact is they existing in real products today and do provide a 'get out of jail free card' card for vendors. Why should they bother implementing worthy features if customers are not banging the table for them ? As regards academic/teaching langauges, as @Damien_The_Unbeliever correctly identifies, a Tutorial D CONSTRAINT are always 'schema'-level, hence allow for global constraints of arbitrary conplexity by definition. If you are looking to design your own DBMS(!!) with this kind of functionality, you should consider implementing the D specification while using an existing SQL DBMS for storage, as Dataphor have done. A question has been bothering me: given that existing 'industrial strength' SQL DBMSs support triggers, why don't they simply map declarative CREATE ASSERTION to a trigger under the covers? I've long suspected the answer is because they know that performance would be appalling given their legacy technology. A more satisfying answer is provided in Applied Mathematics for Database Professionals By Lex de Haan, Toon Koppelaars , chapter 11. They define various execution models to use when using triggers to enforce multi-tuple constraints. The most sophisticated (though still highly doable) model, which they call EM6, involves the following steps: Translate the formal specification into a constraint validation query. Develop code to maintain transition effects. Devise transition effect (TE) queries that ensure the constraint validation query is only run when necessary [e.g. Can I limit the check to only the updated rows? Can a DELETE ever violate this constraint? Are there only specific columns that an UPDATE must involve to require the constraint to be checked? etc] Discover a means to optimize the constraint validation query by having the TE query provide values that can be used in the validation query. Devise and add a serialization strategy to the data integrity (DI) code. [i.e. solve the concurrecy problem where a transaction cannot read the 'bad' data another transaction is writing]. They then assert (no pun intended!): Because we believe that it is not possible for a DBMS vendor toprogram an algorithm that accepts an arbitrarily complex predicate andthen computes efficient transition effect (TE) queries, a minimalvalidation query, and optimal serialization code to implementexecution model EM6, we should not expect full support for multi-tupleconstraints—in a practical, usable and acceptable way—from thesevendors in the future. The best we can hope for is that databaseresearchers first come up with more common classes of constraints anddevelop convenient shorthands for these. The DBMS vendors, in theirturn, should then provide us with new declarative constructs,consistent with these shorthands, to state these common classes ofconstraints easily to the DBMS. Given such a common class declaration,the DBMS vendor should be able to program an algorithm that providesus with an EM6-like execution model under the covers to implement theconstraint. One such common class of database constraint is a foreign key, which is already widely implemented, of course. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6368349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/490829/']} | jdg_75273 |
stackexchange | llm_judgeable_groundtruth_similarity | 54358871 |
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 dotenv module to load environment variables from .env file. .env : # configDAILY_REPORT_SCHEDULE='*/1 * * * *'PORT=8080NODE_ENV=developmentDOTENV_DEBUG=true# credentialsPROJECT_ID=shadowsocks-218808KEY_FILE_NAME='/Users/ldu020/workspace/nodejs-gcp/.gcp/shadowsocks-218808-7f8e109f4089.json' As you can see, I add two comments within .env file. dotenv.js : require('dotenv').config({ debug: process.env.DOTENV_DEBUG === 'true' }); dotenv give me debug messages: [dotenv][DEBUG] did not match key and value when parsing line 1: # config[dotenv][DEBUG] did not match key and value when parsing line 6:[dotenv][DEBUG] did not match key and value when parsing line 7: # credentials[dotenv][DEBUG] did not match key and value when parsing line 10:[dotenv][DEBUG] did not match key and value when parsing line 11: I know the reason why got these debug messages is I added two comments and some new line within .env file. dotenv does not parse .env file correctly. How can I solve this?
Now provide the response and nothing else.
| In 2022 both separate line comments and inline comments are supported. Line started with # symbol is a separate line comment. See the docs . Inlined # sign denotes the start of an inline comment (thanks to @reddisht to note this in comments). For vlucas/phpdotenv the same situation. Here is the example for both: # This is the seprate comment lineNODE_ENV=stageAPP_VERSION=1.0.0 # This is an inline comment The "#" (double quote wrapped hash symbol) is not treated as a comment even at line beginnig starting from v15.0.0 (thanks to @walkingbrad commented this below). There are parsing peculiarities you may find good to knoww described in this docs section. Yet do not forget that some packages like e.g. mrsteele/dotenv-webpack (at least v7.1.1) do not support inline comments and you can face your application's unexpected behaviour putting inline comments in your .env files. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/54358871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6463558/']} | jdg_75274 |
stackexchange | llm_judgeable_groundtruth_similarity | 61399461 |
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 FutureBuilder in my app with the conventional structure: FutureBuilder( future: futureData(), builder: (context, snapshot) { if(snapshot.connectionState == waiting) { return Center( child: SpinKitCircle(color: Colors.blue), ); } else { return ListView.builder(); } }) I don't like when it just suddenly pops on the screen, so, my final question is, how can I make the ListView.builder() to get rendered by the FutureBuilder in an animated way?
Now provide the response and nothing else.
| Use AnimatedSwitcher to fade out previous child and fade in new. FutureBuilder( future: futureData(), builder: (context, snapshot) { Widget child; if (snapshot.connectionState == ConnectionState.waiting) { child = CircularProgressIndicator( key: ValueKey(0), // assign key ); } else { child = ListView.builder( key: ValueKey(1), // assign key ); } return AnimatedSwitcher( duration: Duration(seconds: 1), child: child, ); },); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61399461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12914401/']} | jdg_75275 |
stackexchange | llm_judgeable_groundtruth_similarity | 7905859 |
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 table with an auto-incrementing primary key in Sqlite3 . I am not sure if this is really possible, but I am hoping to only have to designate the other fields. For example: CREATE TABLE people (id integer primary key auto increment, first_name varchar(20), last_name varchar(20)); Then, when I add a value, I was hoping to only have to do: INSERT INTO peopleVALUES ("John", "Smith"); Is this even possible? I am running sqlite3 under cygwin in Windows 7.
Now provide the response and nothing else.
| You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not. If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column. ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value. Also, you should try to avoid: INSERT INTO people VALUES ("John", "Smith"); and use INSERT INTO people (first_name, last_name) VALUES ("John", "Smith"); instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns). | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7905859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/702948/']} | jdg_75276 |
stackexchange | llm_judgeable_groundtruth_similarity | 53389 |
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:
Multiple websites and media say: Facebook claims its 'fact-check' are just protected opinions, according to Facebook's legal team. However, I have not found any official Facebook sources for this claim. Has Facebook's legal team said something similar?
Now provide the response and nothing else.
| In Stossel v Facebook et al (US District Court, Northern California), Meta/Facebook filed a document on 29 November 2021 stating: ...Stossel’s claims focus on the fact-check articleswritten by Climate Feedback, not the labels affixed through the Facebook platform. The labels themselves are neither false nor defamatory; to the contrary, they constitute protected opinion. The document was signed by Sonal N. Mehta signing as "Attorney for Defendant Meta Platforms, Inc." So in the court filing Ms. Mehta is expressing that the labels “Altered”, “Missing Context”, “False”, and “Partly False” are opinion. She is not stating that the explanations of why the labels are given is purely opinion. (alternative source for the court filing document ) | {} | {'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/53389', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/62566/']} | jdg_75277 |
stackexchange | llm_judgeable_groundtruth_similarity | 21485327 |
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 bit confused that, is dialog an activity or not? if yes can we perform operation as we do on activity and set custom layout that can be loaded from XML..
Now provide the response and nothing else.
| You are on the right path with npm install -g sails and sails new myproj . Since you want to use mongo, you will need to install the waterline adapter for mongo (in project dir) npm install sails-mongo --save and configure sails to use mongo. Add the mongo config to the config/adapters.js file: module.exports.adapters = { 'default': 'mongo', mongo: { module : 'sails-mongo', host : 'localhost', port : 27017, user : 'username', password : 'password', database : 'your mongo db name here', // OR module : 'sails-mongo', url : 'mongodb://USER:PASSWORD@HOST:PORT/DB', // Replica Set (optional) replSet: { servers: [ { host: 'secondary1.localhost', port: 27017 // Will override port from default config (optional) }, { host: 'secondary2.localhost', port: 27017 } ], options: {} // See http://mongodb.github.io/node-mongodb-native/api-generated/replset.html (optional) } }}; Additionally, to create your API, (in the project dir) use sails generate NAME where NAME is the name of the model. By default, anything can be added to the database, so you may want to limit the properties/fields and possibly even validate them. Its easy. The generate command created a few files for you, one of which is models/NAME.js . In this file you can simply export an object with the attributes corresponding to the field you want and any restrictions/validations you want to happen before its saved. // Person.jsvar Person = { attributes: { firstName: 'STRING', lastName: 'STRING', age: { type: 'INTEGER', max: 150, required: true } birthDate: 'DATE', phoneNumber: { type: 'STRING', defaultsTo: '111-222-3333' } emailAddress: { type: 'email', // Email type will get validated by the ORM required: true } }};module.exports = Person; This page lists all of the different types and validations you can have. Once you are all set up, run sails lift to start your server. The default port is 1337, but you can change that with the PORT env var or in your local configs module.exports = { port: 80 // ... more config things} Also, as for the 'A' in MEAN, check out Angular Sails . Its a small angular service to let you easily take advantage of the socket.io things that sails is doing for you. You can call all of your APIs over the socket connection to make them even lighter and faster. In this case $sails replaces $http app.controller("FooController", function ($scope, $sails) { $scope.bars = []; $sails.get("/bars", function (data) { $scope.bars = data; });}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21485327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3236733/']} | jdg_75278 |
stackexchange | llm_judgeable_groundtruth_similarity | 3218019 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to open a window that lists all the method definitions so that I can navigate to the one I am interested in. Eclipse does this very elegantly ; I think it is CTRl + O there.
Now provide the response and nothing else.
| You need to edit your question to show (1) the code that you used (2) the full error and traceback (3) the url that is involved (4) what is the unicode character that you are trying to encode as gbk You seem to have somehow obtained unicode characters from the raw bytes in the the html content -- how? what encoding is specified in the html content? Then (I guess) you are trying to write the unicode characters to a file, endcoding the unicode as gbk. During this process, you got an error something like this: >>> u'\uffff'.encode('gbk')Traceback (most recent call last): File "<stdin>", line 1, in <module>UnicodeEncodeError: 'gbk' codec can't encode character u'\uffff' in position 0: illegal multibyte sequence>>> If the raw bytes in the html content were not encoded in gbk, then it is quite possible that you have some unicode characters that can't be represented in gbk. In that case you may like to encode your results using the original encoding, or encode them in gb18030 which can take any unicode character. Another possibility is that you have mangled the raw bytes or the unicode somehow. I certainly hope that your regex machinations have been done on the unicode and not on some variable-length-character encoding like gb2312, gbk, etc. Update: Here is your code snippet: import sys, urllib.requesturl = "http://www.meilishuo.com"wp = urllib.request.urlopen(url)content = wp.read()str_content = content.decode('utf-8')fp = open("web.txt","w")fp.write(str_content)fp.close() From that I've had to deduce: (1) You are running Python 3.x (2) sys.defaultencoding == "gbk" -- otherwise you wouldn't have got the error message some part of which you reported earlier. As my sys.defaultencoding is NOT 'gbk', I replaced your last 3 lines with gbk_content = str_content.encode('gbk') and ran the amended snippet with Python 3.1.2. Observations: (1) website has charset=utf-8, decodes OK with utf-8 (2) Error message: UnicodeEncodeError: 'gbk' codec can't encode character '\u2764' in position 35070: illegal multibyte sequence \u2664 is a dingbat (HEAVY BLACK HEART). The website is dynamic; in another attempt, the first offending character was \xa9 (COPYRIGHT SIGN). So the web page contains Unicode characters which are not mapped in gbk. Options are (1) encode with 'gbk' but use the 'replace' option (2) encode with 'gbk' but use the 'ignore' option (3) encode with an encoding that supports ALL Unicode characters (utf-8, gb18030) and for which you have a display mechanism that renders all those characters that aren't in gbk | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3218019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26788/']} | jdg_75279 |
stackexchange | llm_judgeable_groundtruth_similarity | 28847641 |
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 the SimplePagination jquery plugin- http://flaviusmatis.github.io/simplePagination.js/ and I was able to successfully intiate the plugin and paginate through the items.however im trying to add a legend saying: "Showing 1-10 of 20 records" besides the 'prev' and 'next' buttons, something like this: Showing 1-10 of 20 << Prev 1 2 3 Next >> Is there any way i can add this legend using the simplePagination plugin??Thanks!!
Now provide the response and nothing else.
| Build a class called MyJavaScriptInterface. And MyJavaScriptInterface to WebView. WebViewClient yourWebClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } @Override public void onPageFinished(WebView view, String url) { wb.loadUrl("javascript:HtmlViewer.showHTML" + "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"); } }; wb = (WebView) findViewById(R.id.webview); wb.getSettings().setJavaScriptEnabled(true); wb.getSettings().setSupportZoom(true); wb.getSettings().setBuiltInZoomControls(true); wb.setWebViewClient(yourWebClient); wb.loadUrl("http://pqrs.abcde.com/facebook"); wb.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer"); class MyJavaScriptInterface { private Context ctx; MyJavaScriptInterface(Context ctx) { this.ctx = ctx; } @JavascriptInterface public void showHTML(String html) { System.out.println(html); }} Note: From you are required to remove window in wb.loadUrl("javascript:...");.And @JavascriptInterface before "public void showHTML". You can get content from showHtml(..) in html parameter. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28847641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4021059/']} | jdg_75280 |
stackexchange | llm_judgeable_groundtruth_similarity | 3457391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It seems like the point of window.postMessage is to allow safe communication between windows/frames hosted on different domains, but it doesn't actually seem to allow that in Chrome. Here's the scenario: Embed an <iframe> (with a src on domain B * ) in a page on domain A The <iframe> ends up being mostly a <script> tag, at the end of which's execution... I call window.postMessage( some_data , page_on_A ) The <iframe> is most definitely in the context of domain B, and I've confirmed that the embedded javascript in that <iframe> executes properly and calls postMessage with the correct values. I get this error message in Chrome: Unable to post message to A . Recipient has origin B . Here's the code that registers a message event listener in the page on A: window.addEventListener( "message", function (event) { // Do something }, false); I've also tried calling window.postMessage(some_data, '*') , but all that does is suppress the error. Am I just missing the point here, is window.postMessage(...) not meant for this? Or am I just doing it horribly wrong? *Mime-type text/html, which it must remain.
Now provide the response and nothing else.
| Here is an example that works on Chrome 5.0.375.125. The page B (iframe content): <html> <head></head> <body> <script> top.postMessage('hello', 'A'); </script> </body></html> Note the use of top.postMessage or parent.postMessage not window.postMessage here The page A: <html><head></head><body> <iframe src="B"></iframe> <script> window.addEventListener( "message", function (e) { if(e.origin !== 'B'){ return; } alert(e.data); }, false); </script></body></html> A and B must be something like http://domain.example From another question , it looks the domains(A and B here) must have a / for the postMessage to work properly. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3457391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80572/']} | jdg_75281 |
stackexchange | llm_judgeable_groundtruth_similarity | 23687727 |
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 the Google Map APi v3 , there are style options such as : { featureType: 'transit.line', elementType: 'geometry', stylers: [ { hue: '#fc0101' }, { visibility: 'on' } ] } This works on map load, as can be seen in the API example: https://developers.google.com/maps/documentation/javascript/examples/maptype-styled-simple I need to add a click event to show or change a certain style, for example if I change the above codes hue value on a dom event. Example code: // a link to test map changesvar testDiv = document.getElementById("test");// add click event listener for mapgoogle.maps.event.addDomListener(testDiv, 'click', showTest);// the function for setZoom works function showTest() { map.setZoom(2); } I cannot find any documents for setting the style, there is no "set", https://developers.google.com/maps/documentation/javascript/reference#StyledMapType There is setOptions which includes a styles property but I cannot get it to work. An example that does not work: // turn off transit line visibility on clickfunction showTest() { map.setOptions({ styles : { featureType: 'transit.line', elementType: 'geometry', stylers: [ { hue: '#fc0101' }, { visibility: 'off' } ] } });} Working example with zoom event (just zooms out map): http://codepen.io/anon/pen/yfGxm Non Working example with style event (this is set to remove the transit line shown in black): http://codepen.io/anon/pen/CphbA Edit: The answer below is great and I didn't realize this is also documented here: https://developers.google.com/maps/documentation/javascript/styling?csw=1
Now provide the response and nothing else.
| http://codepen.io/jolsalazar/full/anKqG Here the example code: var map;var chicago = new google.maps.LatLng(41.850033, -87.650052);function initialize() { var roadAtlasStyles = [ { featureType: 'transit.line', elementType: 'geometry', stylers: [ { hue: '#ff0000' }, { visibility: 'on' }, { lightness: -70 } ], enableCloseButton: true, visible: false } ]; var mapOptions = { zoom: 12, center: chicago, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'usroadatlas'] } }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); var styledMapOptions = { name: 'US Road Atlas' }; var usRoadMapType = new google.maps.StyledMapType( roadAtlasStyles, styledMapOptions); map.mapTypes.set('usroadatlas', usRoadMapType); map.setMapTypeId('usroadatlas'); google.maps.event.addDomListener(document.getElementById('test'), 'click', function() { map.setMapTypeId(google.maps.MapTypeId.ROADMAP); });}jQuery(document).ready(function () { google.maps.event.addDomListener(window, 'load', initialize);}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23687727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555548/']} | jdg_75282 |
stackexchange | llm_judgeable_groundtruth_similarity | 14962468 |
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 use a full-height app using flexbox. I found what I want using old flexbox layout module ( display: box; and other things) in this link: CSS3 Flexbox full-height app and overflow This is a correct solution for browsers that only support the old version of the flexbox CSS properties. If I want to try using the newer flexbox properties, I'll try to use the second solution in the same link listed as a hack: using a container with height: 0px; . It makes to show a vertical scroll. I don't like it a lot because it introduces other problems and it is more a workaround than a solution. html, body { height: 100%; }#container { display: flex; flex-direction: column; height: 100%;}#container article { flex: 1 1 auto; overflow-y: scroll;}#container header { background-color: gray;}#container footer { background-color: gray;} <section id="container" > <header id="header" >This is a header</header> <article id="content" > This is the content that <br /> With a lot of lines. <br /> With a lot of lines. <br /> This is the content that <br /> With a lot of lines. <br /> <br /> This is the content that <br /> With a lot of lines. <br /> <br /> This is the content that <br /> With a lot of lines. <br /> </article> <footer id="footer" >This is a footer</footer></section> I have prepared a JSFiddle as well with a base example: http://jsfiddle.net/ch7n6/ It is a full-height HTML website and the footer is at the bottom because of the flexbox properties of the content element. I suggest you move the bar between CSS code and result to simulate different height.
Now provide the response and nothing else.
| Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer. The solution is setting a height to the vertical scrollable element. For example: #container article { flex: 1 1 auto; overflow-y: auto; height: 0px;} The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px; #container article { flex: 1 1 auto; overflow-y: auto; height: 100px; /* == min-height: 100px*/} So the best solution if you want a min-height in the vertical scroll: #container article { flex: 1 1 auto; overflow-y: auto; min-height: 100px;} If you just want full vertical scroll in case there is no enough space to see the article: #container article { flex: 1 1 auto; overflow-y: auto; min-height: 0px;} The final code: http://jsfiddle.net/ch7n6/867/ | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14962468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1604261/']} | jdg_75283 |
stackexchange | llm_judgeable_groundtruth_similarity | 654953 |
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 understand how to calculate it, but I am just curious, why actually it works? Do we have a proof that it always works?
Now provide the response and nothing else.
| Take $f\colon x\in\mathbb{R}\mapsto x^3$. Then $f^\prime(0)=0$, yet $0$ is not an extremum (only an inflection point). As DonAtonio said, the converse is true — if $x$ is an extremum of a differentiable function $f$, then $f^\prime(0)=0$. A way to see it is that the curve of $f$ goes from "going up" to "going down" (or vice-versa), so the slope (derivative) must be zero (horizontal) at the extremum. Or, to prove it, consider the definition of the derivative as the limit of$$\frac{f(x+h)-f(x)}{h}$$when $h\to 0$. If $f(x)$ is a maximum, then for $h < 0$ this is $\geq 0$ (so the limit when $h\nearrow 0$ is), while for $h > 0$ this is $\leq 0$ (so the limit when $h\searrow 0$ is). Hence the limit is $0$. (similarly if $f(x)$ is a minimum) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/654953', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2284/']} | jdg_75284 |
stackexchange | llm_judgeable_groundtruth_similarity | 3408191 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Along with half of the web developer community, I've been struggling to really and truly grok the REST style. More specifically, I've been trying to form some opinions on how practical a pure RESTful architecture really is between a web browser and an application server. As part of my learning endeavor, I've been taking a look at some online examples of REST, specifically Twitter in this case. In their API documentation , they discuss their various "REST API Methods". I'm struggling with rationalizing how exactly most of these are actually RESTful, beyond having a RESTful URL structure. Consider, for example, a simple GET request to http://twitter.com/favorites . In a pure implementation of REST, I would expect identical requests to that URL, regardless of the initiating client, to return identical responses. In this particular case, though, we would obviously all see different responses depending on our currently authenticated users, which implies that our requests are being connected to some form of client state on the server before a response can be generated. Hopefully that provides enough context for my question then - can that really be called "REST"? I get the impression that 90% of the so-called RESTful implementations between web browsers and application servers demonstrate this same inconsistency, where the restrictions on client state stored on the server are ignored.
Now provide the response and nothing else.
| Twitter breaks pretty much every REST constraint. Your example of http://twitter.com/favorites returning different results based on the authenticated user is an example of Twitter violating the "Resource Identification" constraint. Each interesting resource should have a unique identifier. My Twitter favorites and your Twitter favorites are two different resources and therefore should have two different URIs. This actually is not related to idempotency at all. Idempotency is about being able to make the same request multiple times and it have the same effect. Even Twitter respects idempotency. If I GET my favorites multiple times, I still get my favorites back. How many times I do GET does not affect the result. There are many other ways in which Twitter break the REST constraints. Many of these issues have been covered here on SO before. Update After perusing the Twitter api docs a bit more there is actually an alternative URI format that does properly identify the favourites resource. Here they show how to create an URL like: http://api.twitter.com/1/favorites/bob.json It still is a long way from being RESTful, but at least that's a step in the right direction. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3408191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376789/']} | jdg_75285 |
stackexchange | llm_judgeable_groundtruth_similarity | 16471767 |
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 get the div width and height as the user changes it and submit that number to another page. I can't seem to figure out how to get the width and height though. <script>$(function() { $( "#set div" ).draggable({ stack: "#set div", preventCollision: true, containment: $('#main_content'), stop: function(event, ui) { var mydiv = document.getElementById("set"); var pos_x = ui.offset.left; var pos_y = ui.offset.top; var width = mydiv.style.width; ----THIS DOESN'T WORK var height = mydiv.style.height; ----THIS DOESN'T WORK var window_width = window.innerWidth; var window_height = window.innerHeight; var need = ui.helper.data("need"); console.log(pos_x); console.log(pos_y); console.log(width); console.log(window_width); console.log(need); //Do the ajax call to the server $.ajax({ type: "POST", url: "updatecoords.php", data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height} }).done(function( msg ) { alert( "Data Saved: " + msg ); }); } });});</script> What's the proper way to do this?
Now provide the response and nothing else.
| It's quite wrong to use ele.style.width to get the element's width!!!!!! In native JavaScript, you can get a element's CSS through two ways: Standard Method window.getComputedStyle(ele) For example, var ele = document.getElementById("content"), // Do not use # eleStyle = window.getComputedStyle(ele);/* Below is the width of ele */var eleWidth = eleStyle.width; IE(IE 8 And Before) element.currentStyle For example, var ele = document.getElementById("content"), // Do not use # eleStyle = ele.currentStyle;/* Below is the width of ele */var eleWidth = eleStyle.width; Why Not Use ele.style ? ele.style is just get the attribule style of ele . If you use ele.style.width , you just get the width of ele.style , not the real width of ele . If you have done something like: ele.style.width = "55px" You get "55px" when using ele.style.width . If you haven't, you will get undefined. How To Do In jQuery? Use $ele.width() (if you want the "exact" width, use $ele.outWidth() ), jQuery has done everything for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16471767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2362601/']} | jdg_75286 |
stackexchange | llm_judgeable_groundtruth_similarity | 351179 |
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:
Assuming that model is correct, why does the residual series of an ARMA model resemble a white noise process?
Now provide the response and nothing else.
| If that's what your course said, it's wrong. While discrete distributions can have a finite number of possible outcomes, they are not required to; you can have a discrete distribution that has an infinite number of possible outcomes - the number of elements should be no more than countable. A common example would be a geometric distribution; consider the number of tosses of a fair coin until you get a head. There's no finite upper bound on the number of tosses that may be needed. It may take 1 toss, or 2, or 3, or 100, or any other number. A discrete distribution could be negative (consider the difference between two such geometrically-distributed random variables; it can be any positive or negative integer). A discrete distribution doesn't have to be over the integers, though, like in my example. That's just a common situation, not a requirement. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/351179', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/211506/']} | jdg_75287 |
stackexchange | llm_judgeable_groundtruth_similarity | 156205 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Shells like Bash and Zsh expand wildcard into arguments, as many arguments as match the pattern: $ echo *.txt1.txt 2.txt 3.txt But what if I only want the first match to be returned, not all the matches? $ echo *.txt1.txt I don't mind shell-specific solutions, but I would like a solution that works with whitespace in filenames.
Now provide the response and nothing else.
| One robust way in bash is to expand into an array, and output the first element only: pattern="*.txt"files=( $pattern )echo "${files[0]}" # printf is safer! (You can even just echo $files , a missing index is treated as [0].) This safely handles space/tab/newline and other metacharacters when expanding the filenames. Note that locale settings in effect can alter what "first" is. You can also do this interactively with a bash completion function : _echo() { local cur=${COMP_WORDS[COMP_CWORD]} # string to expand if compgen -G "$cur*" > /dev/null; then local files=( ${cur:+$cur*} ) # don't expand empty input as * [ ${#files} -ge 1 ] && COMPREPLY=( "${files[0]}" ) fi}complete -o bashdefault -F _echo echo This binds the _echo function to complete arguments to the echo command (overriding normal completion). An extra "*" is appended in the code above, you can just hit tab on a partial filename and hopefully the right thing will happen. The code is slightly convoluted, rather than set or assume nullglob ( shopt -s nullglob ) we check compgen -G can expand the glob to some matches, then we expand safely into an array, and finally set COMPREPLY so that quoting is robust. You can partly do this (programmatically expand a glob) with bash's compgen -G , but it's not robust as it outputs unquoted to stdout. As usual, completion is rather fraught, this breaks completion of other things, including environment variables (see the _bash_def_completion() function here for the details of emulating the default behaviour). You could also just use compgen outside of a completion function: files=( $(compgen -W "$pattern") ) One point to note is that "~" is not a glob, it's handled by bash in a separate stage of expansion, as are $variables and other expansions. compgen -G just does filename globbing, but compgen -W gives you all of bash's default expansion, though possibly too many expansions (including `` and $() ). Unlike -G , the -W is safely quoted (I can't explain the disparity). Since the purpose of -W is that it expands tokens, this means it will expand "a" to "a" even if no such file exists, so it's perhaps not ideal. This is easier to understand, but may have unwanted side-effects: _echo() { local cur=${COMP_WORDS[COMP_CWORD]} local files=( $(compgen -W "$cur") ) printf -v COMPREPLY %q "${files[0]}" } Then: touch $'curious \n filename' echo curious* tab Note the use of printf %q to safely quote the values. One final option is to use 0-delimited output with GNU utilities (see the bash FAQ ): pattern="*.txt"while IFS= read -r -d $'\0' filename; do printf '%q' "$filename"; break; done < <(find . -maxdepth 1 -name "$pattern" -printf "%f\0" | sort -z ) This option gives you a little more control over the sorting order (the order when expanding a glob will be subject to your locale/ LC_COLLATE and may or may not fold case), but is otherwise a rather large hammer for such a small problem ;-) | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/156205', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9041/']} | jdg_75288 |
stackexchange | llm_judgeable_groundtruth_similarity | 42739256 |
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 project that uses arrays of objects that I'm thinking of moving to es6 Sets or Maps. I need to quickly get a random item from them (obviously trivial for my current arrays). How would I do this?
Now provide the response and nothing else.
| Maps and Sets are not well suited for random access. They are ordered and their length is known, but they are not indexed for access by an order index. As such, to get the Nth item in a Map or Set, you have to iterate through it to find that item. The simple way to get a random item from a Set or Map would be to get the entire list of keys/items and then select a random one. // get random item from a Setfunction getRandomItem(set) { let items = Array.from(set); return items[Math.floor(Math.random() * items.length)];} You could make a version that would work with both a Set and a Map like this: // returns random key from Set or Mapfunction getRandomKey(collection) { let keys = Array.from(collection.keys()); return keys[Math.floor(Math.random() * keys.length)];} This is obviously not something that would perform well with a large Set or Map since it has to iterate all the keys and build a temporary array in order to select a random one. Since both a Map and a Set have a known size, you could also select the random index based purely on the .size property and then you could iterate through the Map or Set until you got to the desired Nth item. For large collections, that might be a bit faster and would avoid creating the temporary array of keys at the expense of a little more code, though on average it would still be proportional to the size/2 of the collection. // returns random key from Set or Mapfunction getRandomKey(collection) { let index = Math.floor(Math.random() * collection.size); let cntr = 0; for (let key of collection.keys()) { if (cntr++ === index) { return key; } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42739256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1791917/']} | jdg_75289 |
stackexchange | llm_judgeable_groundtruth_similarity | 8115550 |
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 a C++ interview test question not homework. #include <iostream>using namespace std;enum months_t { january, february, march, april, may, june, july, august, september, october, november, december} y2k; int main () { cout << "sizeof months_t is " << sizeof(months_t) << endl; cout << "sizeof y2k is " << sizeof(y2k) << endl; enum months_t1 { january, february, march, april, may, june, july, august, september, october, november, december} y2k1; cout << "sizeof months_t1 is " << sizeof(months_t1) << endl; cout << "sizeof y2k1 is " << sizeof(y2k1) << endl; } Output: sizeof months_t is 4 sizeof y2k is 4 sizeof months_t1 is 4 sizeof y2k1 is 4 Why is the size of all of these 4 bytes? Not 12 x 4 = 48 bytes? I know union elements occupy the same memory location, but this is an enum.
Now provide the response and nothing else.
| In your compiler, the size is four bytes because the enum is stored as an int . With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities. 0 0 0 0 January0 0 0 1 February0 0 1 0 March0 0 1 1 April0 1 0 0 May0 1 0 1 June0 1 1 0 July0 1 1 1 August1 0 0 0 September1 0 0 1 October1 0 1 0 November1 0 1 1 December1 1 0 0 ** unused **1 1 0 1 ** unused **1 1 1 0 ** unused **1 1 1 1 ** unused ** Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability. Other compilers could use a byte, int16, uint16 int or uint as long as the variable can contain all the values of the enum. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8115550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002288/']} | jdg_75290 |
stackexchange | llm_judgeable_groundtruth_similarity | 60698622 |
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 getting following error with Firebase services. E/FirebaseInstanceId: Topic sync or token retrieval failed on hard failure exceptions: FIS_AUTH_ERROR. Won't retry the operation. D/AndroidRuntime: Shutting down VM com.google.android.gms.tasks.RuntimeExecutionException: java.io.IOException: FIS_AUTH_ERROR at com.google.android.gms.tasks.zzu.getResult(Unknown Source:15) at com.myApp.MainActivity$2.onComplete(MainActivity.java:349) at com.google.android.gms.tasks.zzj.run(Unknown Source:4) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:237) at android.app.ActivityThread.main(ActivityThread.java:7804) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068) Caused by: java.io.IOException: FIS_AUTH_ERROR at com.google.firebase.iid.zzs.zza(com.google.firebase:firebase-iid@@20.1.0:82) at com.google.firebase.iid.zzs.zza(com.google.firebase:firebase-iid@@20.1.0:96) at com.google.firebase.iid.zzx.then(com.google.firebase:firebase-iid@@20.1.0:4) at com.google.android.gms.tasks.zzd.run(Unknown Source:5) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:919) Here is the part of the code where crash occurs: FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (task.getResult() != null && task.isSuccessful()) { // Get new Instance ID token firebaseToken = task.getResult().getToken(); prefs.edit().putString("firebaseToken", firebaseToken).apply(); registerToken(); } } }); The error occurs in onComplete. Here is firebase dependencies which I use: // FIREBASEimplementation 'com.google.firebase:firebase-analytics:17.2.3'implementation 'com.google.firebase:firebase-messaging:20.1.2'implementation 'com.google.firebase:firebase-appindexing:19.1.0'implementation 'com.google.firebase:firebase-ads:19.0.0'implementation 'com.google.firebase:firebase-crashlytics:17.0.0-beta01' I found this issue on Github related with my crash but there is no conclusive solution at all. Does anybody encountered this kind of issue? Thanks in advance. Note: I don't use Flutter however the error occurs without flutter too. Device is Samsung A51 with Android 10. Note 2: Firebase removed firebase-core. Problem can be related with that.
Now provide the response and nothing else.
| Temporary but working solution. Just downgrade com.google.firebase:firebase-messaging:20.1.2 to com.google.firebase:firebase-messaging:20.1.0 . Apperantly, there is some kind of bug in 20.1.1 and 20.1.2 versions. App doesn't crash anymore. UPDATE (11.04.2020): I tested in com.google.firebase:firebase-messaging:20.1.5 and apperantly problem has been fixed. UPDATE (26.04.2020): I found a permanent solution. First upgrade firebase dependencies to com.google.firebase:firebase-messaging:20.1.6 . After that download google-services.json from firebase. Replace it with the current one. After that build > clean project otherwise you can get API key expired. Please renew the API key error. There is no problem with the key, it's some kind of bug of Google. If you completed these steps, add following code into onCreate of your top Application class which is you declared in manifest at the application tag. FirebaseOptions options = new FirebaseOptions.Builder() .setApplicationId("APP ID") // Required for Analytics. .setProjectId("PROJECT ID") // Required for Firebase Installations. .setApiKey("GOOGLE API KEY") // Required for Auth. .build();FirebaseApp.initializeApp(this, options, "FIREBASE APP NAME"); You can found your app id in the firebase > project settings. Also if you're debugging, don't forget to add the debug SHA-256 key to firebase. Now I don't get crash anymore. Firebase services work perfectly. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/60698622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4606368/']} | jdg_75291 |
stackexchange | llm_judgeable_groundtruth_similarity | 3894775 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the standard way to get a typed, readonly empty list in C#, or is there one? ETA: For those asking "why?": I have a virtual method that returns an IList (or rather, post-answers, an IEnumerable ), and the default implementation is empty. Whatever the list returns should be readonly because writing to it would be a bug, and if somebody tries to, I want to halt and catch fire immediately, rather than wait for the bug to show up in some subtle way later.
Now provide the response and nothing else.
| Personally, I think this is better than any of the other answers: static readonly IList<T> EmptyList = new T[0]; Arrays implement IList<T> . You cannot add to an array. You cannot assign to an element in an empty array (because there is none). This is, in my opinion, a lot simpler than new List<T>().AsReadOnly() . You still get to return an IList<T> (if you want). Incidentally, this is what Enumerable.Empty<T>() actually uses under the hood, if I recall correctly. So theoretically you could even do (IList<T>)Enumerable.Empty<T>() (though I see no good reason to do that). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3894775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27358/']} | jdg_75292 |
stackexchange | llm_judgeable_groundtruth_similarity | 17867107 |
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 started working with NavigationDrawer using ActionBarSherlock and got good results, but my company approving this Open Source is not likely to come anytime soon, so I'm working to switch to ActionBarCompat. ActionBarCompat was just officially released yesterday (July 24th, 2013). Has anyone gotten both to work well with each other? I'm hoping I can answer my own question, but seeing if anyone has gotten this to work. The race is on! :-) YouTube on ActionBarCompat's release: https://www.youtube.com/watch?v=6TGgYqfJnyc UPDATE (working code, yes!): I've gotten the sample NavigationDrawer app from Google converted to use ActionBarCompat and it is working fine. You can find it here as a reference or start to your project: https://github.com/bcrider/NavigationDrawerActionBarCompat The 2.x version looks even better than the way it did with ActionBarSherlock, but I'll have to work with ActionBarCompat a lot more to see if I like it better.
Now provide the response and nothing else.
| NOTE: I'm too new to add more than one link in a post, etc., so am answering my own question instead of editing it (hope that's not against the rules?). Will edit the original once allowed. Simple way to add Navigation Drawer with ActionBarCompat: I found that converting my existing app wasn't as bad as I thought it was going to be. Google's sample led me to believe Fragments were a necessity but that wasn't the case... far from it. You can simply wrap your existing layouts with the DrawerLayout and plug in the ListView (or any layout containing the ListView for that matter) for the actual navigation. Then add the normal code to your existing Activity (extend ActionBarActivity) and build the navigation as you would have to anyway. Here's some sample code with which to wrap your existing layout: <?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" >[YOUR EXISTING LAYOUT GOES HERE] <ListView android:id="@+id/left_drawer" android:layout_width="300dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="#111" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" /></android.support.v4.widget.DrawerLayout> If you want to start with a sample app that does use fragments and go from there, here's my github repository based on the sample code: https://github.com/bcrider/NavigationDrawerActionBarCompat | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17867107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1786292/']} | jdg_75293 |
stackexchange | llm_judgeable_groundtruth_similarity | 225599 |
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:
Like many, most of my time is spent away from home: at work, the gym, out socializing, etc. I'd estimate I use my internet a few hours a night. I never turn my modem off unless I travel for longer than a few days, and I have not disabled SSID broadcasting, as I've read that doing so has little to no security benefits. But if my modem (and wi-fi) is off while I'm away, that would seem to nullify any security risks that do not include someone illegally accessing my physical devices, however minimal. Are there any significant benefits to turning off your modem before leaving home, or would doing so be practically useless to protect against threats?
Now provide the response and nothing else.
| Generally speaking, a vulnerable device/network doesn't become less vulnerable if it is turned off some of the time. Or if you have infected devices on the network, this won't make them any less infected. However, it may reduce the probability of your router or any exposed service from becoming infected any given day. I guess you could also argue that an already infected device will do less damage to others if it is powered off. But really, there are botnets and others constantly scanning the internet for potentially vulnerable devices, so if your device is vulnerable, it's only a matter of time before it is compromised. Instead, I'd focus on decreasing your attack surface and fixing weaknesses. Make sure your modem/router is up-to-date, and the same for other devices you have exposed to the internet. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/225599', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/209381/']} | jdg_75294 |
stackexchange | llm_judgeable_groundtruth_similarity | 25165817 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to get the last element of an std::unordered_map ? myMap.rbegin() and --myMap.end() are not possible.
Now provide the response and nothing else.
| There is no "last element" in a container that is unordered . You might want an ordered container, e.g. std::map and access the last element with mymap.rbegin()->first (Also see this post ) EDIT: To check if your iterator is going to hit the end, simply increment it (and possibly save it in a temporary) and check it against mymap.end() , or, even cleaner : if (std::next(it) == last) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25165817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348388/']} | jdg_75295 |
stackexchange | llm_judgeable_groundtruth_similarity | 16644232 |
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 vim to browse through different folders. (i.e., issue :tabe . command in vim) However, when I open the file either in split window (pressing 'o') or in vertical split window(pressing 'v'), the newly opened window size is really small. (while meanwhile, vim's file browser's windows stays pretty big which I don't really need). I know that I can manually change the window size by Ctrl+W with either -/+ or split, or for vertical split, or '=' to make the window sizes equal; but that's too troublesome. I want to check if there're existing ways to set the default size of the window opened using "o" or "v" to be bigger? Thanks a lot ;)
Now provide the response and nothing else.
| The new window should take half of the height or half of the width of the current window which can give you small windows pretty quickly. The option that defines that proportion can be found in :help netrw : let g:netrw_winsize = 75 Note that using this method will make any further split even smaller than before: let g:netrw_winsize = 50 (default)|-netrw--------------------------------------------||-netrw------------------|-file--------------------||-netrw------|-file------|-file--------------------|let g:netrw_winsize = 75|-netrw--------------------------------------------||-netrw------|-file--------------------------------||-netrw|-file|-file--------------------------------| The "problem", here is that netrw splits its own window, not the previous window. Netrw can be used to open the file under the cursor in the current window, in a split window or in another tab but the way it splits its own window makes it hard to use it the way you want. AFAIK, the most common usage is: open netrw with :Ex , navigate, hit <CR> to open the file under the cursor in the current window, edit, re-open netrw in its latest state with :Rex (for Peter Rincker), GOTO 2 An alternative is to use :Vex to open netrw in a vertical split and use P to open the file in the previous window. I'm afraid Netrw is not really designed to work like what you seem to want it to work. IMO, netrw is more like an "open…" dialog than the kind of file explorer pane you can see in most editors/IDEs. I'd suggest you either get used to it or try NERDTree which has only a subset of netrw's features but is designed to be more like those file explorer panes. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16644232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799550/']} | jdg_75296 |
stackexchange | llm_judgeable_groundtruth_similarity | 8627146 |
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 standard grouped table view. I would like to add a shadow around it (i.e. around the edge of each tableview section) - if you are not sure what I mean, then see the official twitter app (below) for an example. It's pretty subtle, but it's definitely a shadow as opposed to a border. How can I achieve this effect? Save for using images with built in shadows as each cell's background - which won't allow animated cell resizing like I need - I haven't figured out a way.
Now provide the response and nothing else.
| I have two solutions that might help. Because of the rounded corners, I think you will have to apply the shadow effect to the cells, and position them so that the shadows do not overlap on the y axis. So... Solution 1 (the complicated solution):This is the solution that I think could work if you are animating the cornerRadius, or are unsure of the exact shape of the section of cells. Have you tried using the shadowPath like Ecarrion suggests, but applying it to your custom UITableView cell? Imagine a path for the central cells (not the top and bottom) that is slightly wider than the cell on the x axis and shorter on the y axis. Then you have to make sure the shadow is cast at the top and bottom of the section without making each individual shadow overlap, right? So for the top and bottom cells you make the shadowPath larger on the y axis, let's say 4 points larger. Then you adjust the shadowOffset property for those cells, also by 4 points, on the y axis. If the shadowOffset of a central cell is (0,0), then the top cell is (0,-4) and the bottom cell is (0,4). If it was me, I would put the various size and offset adjustments in a plist so I could tinker with the small details without editing the code. Just load the plist into a dictionary or custom class and then set your properties using those values. Makes the little adjustments a lot less fidgety. EDIT: Going beyond using shadowPath, you can make a composite cell for the tableview with a transparent background layer a slightly smaller shadow layer, and yet a smaller layer for adding text and images. The shadow layer is based on the text/image layer, maybe slightly wider, taller, shorter etc. Apply a blur to that layer, and then mask it with a rectangular mask so that where one shadow layer ends the next begins. With the top and bottom layers, the mask must extend up or down to the highest/lowest point on the y axis that the shadow effect appears (you still have to mask the side that abuts the next cell). It depends on how far you're willing to go to achieve an exact effect... maybe this gives you some more ammunition. Solution 2 (the somewhat easier solution):If you know exactly what the cornerRadius will be on the top and bottom cells, and the only thing you don't necessarily know is the length and/or width of the cells, you can use the old "stretched one-pixel graphic" trick. First you Photoshop/Gimp an image for the corner shadow. If the width is always the same, this image can be the shadow for the whole top of the cell. The same image can be used for the other corners or the bottom of the cell by rotating it. Now the trick. Take a 1 x 5 section of the blur or gradient effect you used for the corner shadow. If your shadow effect is 3 pixels, make that 1x3, etc. Export to PNG or preferred format and check that if you place its edge against an edge of the corner image it lines up seamlessly (the blur or gradient has the same color values without a visible seam). All cells get a layer next to the visible part of the cell (to the left and right) with your 1x5 image as the layer contents. Could also be a stretched UIImageView, your choice. These line up the make the left and right shadows. Place your corner shadows on the first and last cells in the section -- they can be different custom cells, or you can design your cell so that it gets its index passed to it at creation and arranges itself appropriately. Align your side shadows so that they start where the corner shadow ends, and stretch down to the bottom of the cell. If you are also changing the width of cells, you'll do the same thing between the two corner images, stretching your gradient across the x axis. Ok, a picture says a thousand words, so since I seem to be pushing that many words here's an image to illustrate: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8627146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555619/']} | jdg_75297 |
stackexchange | llm_judgeable_groundtruth_similarity | 2345626 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can add bytes to a NSMutableData instance easily by using the appendData method, however I do not see any similar method for removing data? Am I overlooking something, or do I need to create a new object and copy over only the bytes I need?
Now provide the response and nothing else.
| Please see the documentation of the following method: - (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)replacementBytes length:(NSUInteger)replacementLength Apple clearly says the following: If the length of range is not equal to replacementLength, the receiver is resized to accommodate the new bytes. Any bytes past range in the receiver are shifted to accommodate the new bytes. You can therefore pass NULL for replacementBytes and 0 for replacementLength to delete bytes in the receiver in the range range. You can also replace a range (which might be zero-length) with more bytes than the length of the range, which has the effect of insertion (or “replace some and insert more”). To remove 10 byte from the end, use: [data setLength:[data length] - 10]; It could also be done via replaceBytesInRange, but it's in fact much faster, because the bytes are not really removed. Instead only the internal size variable is changed and NSMutableData will behave as if the bytes were removed. IOW, this is a O(1) operation (that means it will always take equally long to perform, regardless of how many bytes you remove), and it is very fast. To remove 10 byte from front, use: [data replaceBytesInRange:NSMakeRange(0, 10) withBytes:NULL length:0]; To remove 10 bytes in the middle (e.g. after 20 bytes), use: [data replaceBytesInRange:NSMakeRange(20, 10) withBytes:NULL length:0]; replaceBytesInRange is a O(n) operation, though. That means no matter how long it takes to remove 100 byte, it will take twice as long to remove 200 bytes and so on. It is still pretty fast and only limited by the throughput of your computer's memory (RAM). If you have 10 MB of data and you remove 1 MB from front, 9 MB are copied to fill the gap of the just removed MB. So the speed of the operation depends on how fast can your system move 9 MB of RAM from one address to another one. And this is usually fast enough, unless you deal with NSMutableData objects containing hundreds of MB. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2345626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127853/']} | jdg_75298 |
stackexchange | llm_judgeable_groundtruth_similarity | 17506053 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
with ggplot2, I make the following density plot: ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species)) The colour legend (for each Species value) appears as a box with a line through it, but the density plotted is a line. Is there a way to make the legend appear as just a colored line for each entry of Species, rather than a box with a line through it?
Now provide the response and nothing else.
| One possibility is to use stat_density() with geom="line" . Only in this case there will be only upper lines. ggplot(iris)+ stat_density(aes(x=Sepal.Width, colour=Species), geom="line",position="identity") If you need also the whole area (all lines) then you can combine geom_density() with show_guide=FALSE (to remove legend) and stat_density() than will add legend just with horizontal lines. ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE)+ stat_density(aes(x=Sepal.Width, colour=Species), geom="line",position="identity") | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17506053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_75299 |
stackexchange | llm_judgeable_groundtruth_similarity | 6428590 |
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 generating an Excel workbook using OpenXml and have been following the examples at http://msdn.microsoft.com/en-us/library/cc850837.aspx It would be really useful if I could freeze the top panes, but I can't find a way to do this. I realise that I can do this if I use http://closedxml.codeplex.com/ but for now I'd like to stick to the OpenXml SDK Any ideas?
Now provide the response and nothing else.
| I was trying to solve the same problem and ended up opening the Open XML SDK 2.0 Productivity Tool and using the Compare Files... feature to compare two spreadsheets, one with frozen panes and one without. When I did that, I was led to code that looked basically like this: WorkbookPart wbp = doc.WorkbookPart;WorksheetPart wsp = wbp.WorksheetParts.First();SheetViews sheetviews = wsp.Worksheet.GetFirstChild<SheetViews>();SheetView sv = sheetviews.GetFirstChild<SheetView>();Selection selection = sv.GetFirstChild<Selection>();Pane pane = new Pane(){ VerticalSplit = 1D, TopLeftCell = "A2", ActivePane = PaneValues.BottomLeft, State = PaneStateValues.Frozen };sv.InsertBefore(pane,selection);selection.Pane = PaneValues.BottomLeft; I added this to my program and it seemed to do the trick. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6428590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209530/']} | jdg_75300 |
stackexchange | llm_judgeable_groundtruth_similarity | 5063630 |
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 use ant for creating .jar files in Eclipse. I need to generate jar for my project which also contains source code along with the class file. How do we do it? Another question: what is a debug jar and how to create it using ant ? (have heard about it somewhere and trying to relate them both)
Now provide the response and nothing else.
| I would modify your jar task to include multiple filesets; one for the classes and one for the source files. <jar destfile="${target.dir}/my-app.jar"> <fileset dir="${target.dir}/classes" /> <fileset dir="${src.dir}" includes="**/*.java"/></jar> Packaging should be treated as a separate concern from compiling. This will give you more flexibility. For example, you may want to add other filesets to the jar (e.g. properties files), or you may want to package your sources in a jar file that is separate from your class files. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5063630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/501767/']} | jdg_75301 |
stackexchange | llm_judgeable_groundtruth_similarity | 22123266 |
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 draw multiple car objects onto the same window but it appears that they are overwriting each other. Here is my overridden paintComponent method in the Car class public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(wheelColor); g2.fill(leftWheel); g2.fill(rightWheel); g2.setColor(bodyColor); g2.fill(body); g2.fill(cab);} And in my Viewer Class: JFrame f = new JFrame();initializeFrame(f);Car x = new Car(100, 100);Car y = new Car(300, 300);f.add(x);f.add(y); Although the coordinates seem to be different, only the last car is being drawn. Any suggestions? Thanks
Now provide the response and nothing else.
| What you want to do is use a data structure of Car objects and loop through them in the paintComonent method. Something like List<Car> cars = new ArrayList<>();....@Overrideprotected void paintComponent(Graphics g) { super.paintComponent(g); for (Car car : cars) { car.drawCar(g); }} The drawCar method would come from your Car class public class Car { int x, y; public Car(int x, int y) { this.x = x; this.y = y; } public void drawCar(Graphics g) { g.setColor(Color.BLACK); // do everything here as you would in a paintComponent method }} See more examples here and here and here and here and here and here . UPDATE Here is a simple example use some "Ferraris" I whipped up, also using some animation, but with the same basic points I have above. import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import java.util.List;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.SwingUtilities;import javax.swing.Timer;public class DrawCar extends JPanel{ private static final int D_W = 400; private static final int D_H = 400; List<Car> cars; public DrawCar() { cars = new ArrayList<>(); cars.add(new Car(100, 300)); cars.add(new Car(200, 100)); Timer timer = new Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent e) { for (Car car : cars) { car.move(); repaint(); } } }); timer.start(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Car car : cars) { car.drawCar(g); } } @Override public Dimension getPreferredSize() { return new Dimension(D_W, D_H); } public class Car { private static final int INCREMENT = 5; int x, y; public Car(int x, int y) { this.x = x; this.y = y; } public void drawCar(Graphics g) { g.setColor(Color.BLUE); g.fillRect(x, y, 100, 30); g.setColor(Color.BLACK); // body g.fillOval(x + 15, y + 20, 15, 15); // wheel g.fillOval(x + 60, y + 20, 15, 15); // wheel g.fillRect(x + 15, y - 20, 60, 20); // top } public void move() { if (x == D_W) { x = 0; } else { x += INCREMENT; } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); frame.add(new DrawCar()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22123266', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2645162/']} | jdg_75302 |
stackexchange | llm_judgeable_groundtruth_similarity | 13958998 |
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 unpack the tuples I create by doing the following so he the result is just one simple list. I can get the desired result in 2-3 lines but surely there is a oneliner list.comp? x = range(10)y = [(i,j**2) for i,j in zip(x,x)]>>>y[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]>>> What I want is result = [0,0,1,1,2,4,3,9.....] Doing y = len(x)*[0]y[::2] = xy[1::2] = [i**2 for i in x] Gives what I want but what if I need the more general case: y = [(i, sqrt(i), i**3, some_operation_on_i, f(i), g(i)) for i in x] Eg I should be able to get a straight list like result where I only specified one operation (square) to follow each i but now with an arbitrary number of operations following each i.
Now provide the response and nothing else.
| Use a nested list comprehension: result = [a for tup in y for a in tup] Example: >>> x = range(10)>>> y = [(i,j**2) for i,j in zip(x,x)]>>> [a for tup in y for a in tup][0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81] This will work fine for your more general case as well, or you could do it all in one step: y = [a for i in x for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i))] In case the nested list comprehensions look odd, here is how this would look as a normal for loop: y = []for i in x: for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i)): y.append(a) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13958998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/948652/']} | jdg_75303 |
stackexchange | llm_judgeable_groundtruth_similarity | 48373126 |
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 HTML code using Bootstrap 4: <div class="row"> <div class="col-12 col-sm-4"> First, but unordered </div> <div class="col-12 col-sm-4"> Second, but unordered </div> <div class="col-12 col-sm-4 order-sm-1"> Third, but first </div></div> I am expecting the third div to be placed in first position on sm screens but it is not. Here is a JSFiddle What have I missed? Thanks!
Now provide the response and nothing else.
| you can use the following css to make it red when it is not checked, and black when it is checked .custom-control-label:before{ background-color:red;}.custom-checkbox .custom-control-input:checked~.custom-control-label::before{ background-color:black;} The color of the arrow can be changed by the following code .custom-checkbox .custom-control-input:checked~.custom-control-label::after{ background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='red' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E");} this code will make the tick red, you can change the color by changing the fill='red' value to a color of your choice. Edit: Note, if specifying RGB color, eg. #444444 use %23 for the hash, eg. %23444444 Or you could use any image you like instead. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous"><style> .custom-control-label:before{ background-color:red; } .custom-checkbox .custom-control-input:checked~.custom-control-label::before{ background-color:black; } .custom-checkbox .custom-control-input:checked~.custom-control-label::after{ background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='red' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E"); } .custom-control-input:active~.custom-control-label::before{ background-color:green; } /** focus shadow pinkish **/ .custom-checkbox .custom-control-input:focus~.custom-control-label::before{ box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem rgba(255, 0, 247, 0.25); }</style> <div class="custom-control form-control-lg custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label" for="customCheck1">Check this custom checkbox</label> </div> EDIT: added a focus color (pinkish) after a request from @cprcrack | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48373126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2469528/']} | jdg_75304 |
stackexchange | llm_judgeable_groundtruth_similarity | 3840024 |
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 code compiles successfully, but I think it should fail to compile. Also, when you run it you get a NullReferenceException . The missing code is the "new Bar" in the initialization of the Bar property. class Bar{ public string Name { get; set; }}class Foo{ public Bar Bar { get; set; }}class Program{ static void Main(string[] args) { var foo = new Foo { Bar = { Name = "Hello" } }; }} Is this a known bug?
Now provide the response and nothing else.
| Why do you think it should fail to compile? It is nested object initializer syntax, and it is the responsibility of the client code to provide a valid value for initialization. From the documentation: C# spec 7.5.10.2 "Object initializers" A member initializer that specifies an object initializer after the equals sign is a nested object initializer, i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3840024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463957/']} | jdg_75305 |
stackexchange | llm_judgeable_groundtruth_similarity | 26500755 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read the documentation available for Laravel 5's new Elixir. I have written this code and run gulp multiple times, however, the compiled/minified css and js are not coming in: var elixir = require('laravel-elixir');elixir(function(mix) { mix .styles([ "resources/assets/components/bootstrap/dist/css/bootstrap.css" ]) .scripts([ "resources/assets/components/jquery/dist/jquery.js" ]) .version('css/app.css');}); I've run npm install and gulp in the CLI and I get this output (which seems normal): [05:15:58] Starting 'default'...[05:15:58] Starting 'styles'...[05:16:00] Finished 'default' after 1.32 s[05:16:00] Finished 'styles' after 1.32 s[05:16:00] Starting 'scripts'...[05:16:00] Finished 'scripts' after 456 ms[05:16:00] Starting 'version'...[05:16:00] Finished 'version' after 2.6 msvagrant@homestead:~/Code/fixer$ What's the problem here? I also watched the Laracast and it seems I'm doing everything properly. It's difficult to find a good answer given this is new.
Now provide the response and nothing else.
| Elixir will assume that the stylesheets and scripts that you're concatenating are located in the public/ directory. To override that, set the base directory. elixir(function(mix) { mix .styles([ "components/bootstrap/dist/css/bootstrap.css" ], "resources/assets") .scripts([ "components/jquery/dist/jquery.js" ], "resources/assets") .version('css/app.css');}); (But also remember that you're trying to concatenate one file in each of those blocks... Maybe that was just for your code snippet.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26500755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_75306 |
stackexchange | llm_judgeable_groundtruth_similarity | 25325923 |
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 write some code to switch the view to another tab when the iOS app starts (so, for example, the second tab is shown by default rather than the first). I'm new to Swift, and have worked out the following: The code should probably go in the override func viewDidLoad() function of the ViewController of the first tab. The following code shows the second ViewController, but not with the tab bar at the bottom (vcOptions is the second ViewController tab item: let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("vcOptions")self.showViewController(vc as UIViewController, sender: vc) I think the answer may lie in using the UITabbarController.selectedIndex = 1, but not quite sure how to implement this.
Now provide the response and nothing else.
| If your window rootViewController is UITabbarController (which is in most cases) then you can access tabbar in didFinishLaunchingWithOptions in the AppDelegate file. func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. if let tabBarController = self.window!.rootViewController as? UITabBarController { tabBarController.selectedIndex = 1 } return true} This will open the tab with the index given (1) in selectedIndex . If you do this in viewDidLoad of your firstViewController , you need to manage by flag or another way to keep track of the selected tab. The best place to do this in didFinishLaunchingWithOptions of your AppDelegate file or rootViewController custom class viewDidLoad . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25325923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3944417/']} | jdg_75307 |
stackexchange | llm_judgeable_groundtruth_similarity | 11581419 |
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 add integration tests to my Gradle build (Version 1.0). They should run separately from my normal tests because they require a webapp to be deployed to localhost (they test that webapp). The tests should be able to use classes defined in my main source set. How do I make this happen?
Now provide the response and nothing else.
| Update for 2021: A lot has changed in 8ish years. Gradle continues to be a great tool. Now there's a whole section in the docs dedicated to configuring Integration Tests. I recommend you read the docs now. Original Answer: This took me a while to figure out and the online resources weren't great. So I wanted to document my solution. This is a simple gradle build script that has an intTest source set in addition to the main and test source sets: apply plugin: "java"sourceSets { // Note that just declaring this sourceset creates two configurations. intTest { java { compileClasspath += main.output runtimeClasspath += main.output } }}configurations { intTestCompile.extendsFrom testCompile intTestRuntime.extendsFrom testRuntime}task intTest(type:Test){ description = "Run integration tests (located in src/intTest/...)." testClassesDir = project.sourceSets.intTest.output.classesDir classpath = project.sourceSets.intTest.runtimeClasspath} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11581419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170587/']} | jdg_75308 |
stackexchange | llm_judgeable_groundtruth_similarity | 1827643 |
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:
There seems precious little around about the use of the material conditional in intuitionistic logic aside from the Wikipedia page https://en.wikipedia.org/wiki/Material_conditional and I can't seem to glean what I need from there. To quote wikipedia: "Whereas, in minimal logic (and therefore also intuitionistic logic) $p\rightarrow q$ only logically entails $\neg(p\land \neg q)$..." Right, so this gives me the following rule: $$\frac{p\rightarrow q}{\neg (p\land \neg q)}$$ However the use of the phrase 'logically entails' suggests that this is a theorem, not an axiom. Wikipedia then goes on: "...and in intuitionistic logic (but not minimal logic) $\neg p\lor q$ entails $p\rightarrow q$." From which I get the following rule: $$\frac{\neg p\lor q}{p\rightarrow q}$$ Here the use of the phrase 'entails' I read as different to rather than synonymous with the phrase 'logically entails', in the sense that this is an axiom rather than a theorem. Put another way, the wording suggests that I am to take this as the rule for the introduction of the material conditional. If so, why the qualification that this only holds in intuitionistic logic and not minimal logic? [A plea to logicians: please stick to the convention I've adopted here that $\rightarrow$ stands for the material conditional whereas $\Rightarrow$ stands for logical consequence! Admittedly I haven't used the latter but just in case you do. Otherwise things will just get impossible to fathom. Thank you!]
Now provide the response and nothing else.
| I believe that "logically entails" and "entails" mean the same thing, here. The point is that in minimal logic, $p\rightarrow q\vdash \neg(p\wedge\neg q)$ is a valid sequent (I'm using "$\vdash$" instead of "$\implies$" here, both for added clarity and to mesh with the standard notation in proof theory). Meanwhile, in intuitionistic logic, $\neg p\vee q\vdash p\rightarrow q$ is a valid sequent; but $\neg p\vee q\vdash p\rightarrow q$ is not a valid sequent in minimal logic. The "only" in the phrase "only logically entails" doesn't apply to "logically"; the point is that in minimal (and even in intuitionistic) logic, we only have $$p\rightarrow q\vdash \neg(p\wedge\neg q)$$ as a valid sequent, not also $$p\rightarrow q\vdash \neg p\vee q.$$ (Note that talking about valid sequents frees me from having to specify a proof system; in particular, I don't need to distinguish between assumed sequents - that is, logical axioms - and derived sequents.) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1827643', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/346335/']} | jdg_75309 |
stackexchange | llm_judgeable_groundtruth_similarity | 91271 |
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:
This is a general question, but what is meant when people refer to the S-Matrix of $\mathcal{N}=4$ Super Yang Mills? The way I understood it is the S-Matrix is only well defined for theories with a mass gap so we can consider the asymptotic states to be non interacting and then apply the LSZ formalism. The idea breaks down for general CFTs and the observables should just be the correlation functions. Based on what I've seen in the literature, this does not seem to be the case and people talk about the S-Matrix for $\mathcal{N}=4$ Super Yang Mills, a superconformal field theory. Is it that we consider a deformed CFT so there exists a gap in the spectrum and take the limit as the deformation goes to zero? Or is there a way to define an S-matrix in an exactly conformal theory? Edit: For anyone who finds this question the following reference (the introduction at least) is of use in showing how the normal logic breaks down: http://arxiv.org/abs/hep-th/0610251
Now provide the response and nothing else.
| As you note the construction of asymptotic states breaks down in a CFT since there is no mass gap. It is therefore necessary to introduce an IR regulator by using, eg, dimensional regularisation. The full scattering amplitude will then depend on this regulator. However, it is possible to construct physical observables that do not depend on the regulator. Furthermore, the amplitude contains subleading terms that also are independent of the regulator, and these will be the same in any regularisation scheme. As an example of this the four particle scattering amplitude takes the form$$\mathcal{A}_4 = \mathcal{A}_4^{\text{tree}} \exp\big[(\text{IR div.}) + \frac{f(\lambda)}{8} (\log(s/t))^2 + (\text{const}) \big]$$The coefficient $f(\lambda)$, the cusp anomalous dimension, is independent of the IR regulator and hence universal. The AdS/CFT dual of a field theory scattering amplitude is the expectation value of a polygonal light-like Wilson loop, see, eg, arxiv:0705.0303 , which also contains a bit of discussion about IR divergences and a bunch of useful references. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/91271', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/20640/']} | jdg_75310 |
stackexchange | llm_judgeable_groundtruth_similarity | 4334970 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hibernate throws this exception during SessionFactory creation: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags This is my test case: Parent.java @Entitypublic Parent { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy="parent", fetch=FetchType.EAGER) // @IndexColumn(name="INDEX_COL") if I had this the problem solve but I retrieve more children than I have, one child is null. private List<Child> children;} Child.java @Entitypublic Child { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @ManyToOne private Parent parent;} How about this problem? What can I do? EDIT OK, the problem I have is that another "parent" entity is inside my parent, my real behavior is this: Parent.java @Entitypublic Parent { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @ManyToOne private AnotherParent anotherParent; @OneToMany(mappedBy="parent", fetch=FetchType.EAGER) private List<Child> children;} AnotherParent.java @Entitypublic AnotherParent { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy="parent", fetch=FetchType.EAGER) private List<AnotherChild> anotherChildren;} Hibernate doesn't like two collections with FetchType.EAGER , but this seems to be a bug, I'm not doing unusual things... Removing FetchType.EAGER from Parent or AnotherParent solves the problem, but I need it, so real solution is to use @LazyCollection(LazyCollectionOption.FALSE) instead of FetchType (thanks to Bozho for the solution).
Now provide the response and nothing else.
| I think a newer version of hibernate (supporting JPA 2.0) should handle this. But otherwise you can work it around by annotating the collection fields with: @LazyCollection(LazyCollectionOption.FALSE) Remember to remove the fetchType attribute from the @*ToMany annotation. But note that in most cases a Set<Child> is more appropriate than List<Child> , so unless you really need a List - go for Set But remind that with using sets you won't eliminate the underlaying Cartesian Product as described by Vlad Mihalcea in his answer ! | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4334970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195176/']} | jdg_75311 |
stackexchange | llm_judgeable_groundtruth_similarity | 202643 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am running Raspbian on a Pi and installed cron to schedule a job. I wrote a Python script and I set it to run every 5 minutes. The job is happening every 5 minutes, no problems, but when I run crontab -l as root and pi , it says there are no jobs. When I run crontab -e as root and as pi they are blank. I honestly can't remember the exact details of when I set up the job. I know I wrote a line on a document that was formatted like a crontab and I am pretty sure it was done as root . I have discovered this as I was going to add some more jobs, and would like to locate the other one I made before I get going on adding more.
Now provide the response and nothing else.
| There are two lists of scheduled tasks (crontabs). Each user (including root) has a per-user crontab which they can list with crontab -l and edit with crontab -e . The usual Linux implementation of cron stores these files in /var/spool/cron/crontabs . You shouldn't modify these files directly (run crontab -e as the user instead), but it's safe to list them to see what's inside. You need to be root to list them. There is a system crontab as well. This one is maintained by root, and the jobs can run as any user. The system crontab consists of /etc/crontab and, on many systems, files in /etc/cron.d . These files have an additional column: after the 5 date/time fields, they have a “user” field, which is the user that the job will run as. It's common to set up /etc/crontab to run scripts from directories /etc/cron.hourly , /etc/cron.daily , etc. and that's how it's done on Raspbian. So look in all these places: /var/spool/cron/crontabs/* (you need to be root for this one), /etc/crontab , /etc/cron.* . You can also get information in the system logs. They won't tell you where the job was listed, but they tell you exactly what command is being executed, so you can search for the command text. For example, this is the entry that runs commands in /etc/cron.hourly every hour: May 11 07:17:01 darkstar CRON[2480]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly) | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/202643', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/114879/']} | jdg_75312 |
stackexchange | llm_judgeable_groundtruth_similarity | 9344159 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First, I setup up the keyboard for the UITextField to use the number with decimal style. So the user can only enter numbers and a single decimal. What I want to do is test the input as the user enters it and prevent multiple decimals from being entered and limit the decimal portion of the number to two places. I do not want to round off the number nor even treat the input as a number. I simply want to prevent the user from entering more then two digits to the right of the decimal place.
Now provide the response and nothing else.
| The solution ultimately turned out to be fairly trivial. Unfortunately a lot of the questions and answers related to this question are about validating or formatting numeric values, not controlling what a user could input. The following implementation of the shouldChangeCharactersInRange delegate method is my solution. As always, regular expressions rock in this situation. RegExLib.com is an excellent source for useful RegEx samples or solutions. I'm not a RegEx guru and always struggle a bit putting them together so any suggestions to improve it are welcome. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if (textField == self.quantityTextField) { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:nil]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])]; if (numberOfMatches == 0) return NO; } return YES;} The above code allows the user to input these kinds of values: 1, 1.1, 1.11, .1, .11. Notice that this implementation does not replace the text field's string, which would causes a recursion. This solution simply rejects the next character the user inputs if the 'newString' does not match the regex. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9344159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184666/']} | jdg_75313 |
stackexchange | llm_judgeable_groundtruth_similarity | 8751482 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't know much regex, but I need to match a simple pattern. The following should return true, Pattern.matches("{\"user_id\" : [0-9]*}", inputLine) when inputLine is {"user_id" : 34} However, I'm getting this exception: java.util.regex.PatternSyntaxException: Illegal repetition{"user_id" : 24} at java.util.regex.Pattern.error(Unknown Source) at java.util.regex.Pattern.closure(Unknown Source) at java.util.regex.Pattern.sequence(Unknown Source) at java.util.regex.Pattern.expr(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.<init>(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.matches(Unknown Source) at org.whispercomm.manes.server.http.IntegrationTest.createUser(IntegrationTest.java:173) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) What am I doing wrong?
Now provide the response and nothing else.
| The { and } are special in Java's regex dialect (and most other dialects for that matter): they are the opening and closing tokens for the repetition quantifier {n,m} where n and m are integers. Hence the error message: "Illegal repetition". You should escape them: "\\{\"user_id\" : [0-9]*\\}" . And since you seem to be trying to parse JSON, I suggest you have a look at Jackson . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8751482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/803801/']} | jdg_75314 |
stackexchange | llm_judgeable_groundtruth_similarity | 435699 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Undoubtedly one of the news that attracted the most attention this year was the result of Yitang Zhang on the Landau–Siegel zeros (see Consequences resulting from Yitang Zhang's latest claimed results on Landau-Siegel zeros ) Since it is not possible to be attentive to great results in all areas, In general terms, what have been important advances in 2022 in different mathematical disciplines?
Now provide the response and nothing else.
| I'd like to mention the resolution of the redshift conjecture for $E_{\infty}$ -rings. The latter are a homotopical refinement of usual commutative rings; at least if we restrict to connective ones, we can model them as topological spaces with an addition and multiplication which satisfy the usual ring axioms up to homotopy (but these homotopies have to satisfy higher axioms, resulting in higher homotopies etc.). As for usual commutative rings, we can take the algebraic K-theory of an $E_{\infty}$ -ring $R$ -- actually, the output can be viewed as an $E_{\infty}$ -ring $K(R)$ again of which the usual algebraic K-groups $K_i(R)$ are just the homotopy groups. It is a central tenet of chromatic homotopy theory to classify spaces (or $E_{\infty}$ -rings) by their height . Any discrete space (like $\mathbb{Z}$ ) has height at most $0$ , topological K-theory (or the space $BU\times \mathbb{Z}$ representing it) has height $1$ ; higher heights are bit more subtle to define: Technically speaking, the height of an $E_{\infty}$ -ring $R$ is the maximum $n$ such that $L_{K(n)}R$ is nonzero (or, if we view $R$ indeed as a space: the maximum $n$ such that the $n$ -th Bousfield Kuhn functor of $R$ is nonzero). It has long been known that $K(\mathbb{Z})$ has height $1$ and actually it almost agrees with its part of pure height $1$ (i.e. the map $K(\mathbb{Z})_p \to L_{K(1)}K(\mathbb{Z})$ is an equivalence above degree $0$ if I recall correctly; this is closely related to the Quillen-Lichtenbaum conjecture, proven by Voevodsky et al.). Motivated by this and (very few) other examples, (one version of) Rognes's redshift conjecture states: For any $E_{\infty}$ -ring, the height of $K(R)$ is always one higher than that of $R$ . This has been proven this year in the monumental paper The Chromatic Nullstellensatz by Burklund, Schlank and Yuan. I want to make a few more remarks: The work of Burklund-Schlank-Yuan is actually at its core about the role which Morava E-theory plays in chromatic stable homotopy theory and proves wonderful results about it. But combined with earlier work of Yuan about the algebraic K-theory of Morava E-theory, it proves the red-shift conjecture in the version above so-to-speak as a by-product. There has been other very important work on the redshift-conjecture and its variants recently. For example, Hahn and Wilson had shown before that the spectra $BP\langle n\rangle$ satisfy redshift (which was the first known example valid at all heights). Moreover, they show also a statement which roughly says that $K(BP\langle n\rangle)$ is well-approximated by its $K(n+1)$ -localization. Even more recently, Ausoni, Bayindir and Moulinos have shown redshift for the Morava K-theories $K(n)$ themselves, which are only associative; this implies redshift for many more ring spectra which are not $E_{\infty}$ . Note also the recent concrete calculations of Angelini-Knoll, Ausoni, Culver, Höning and Rognes in this context, and a new way to do similar calculations discovered in recent work of Hahn, Raksit and Wilson . There has been already other very interesting work in homotopy theory this year, among which I want to mention two papers by Burklund: one gives the first sublinear bound on the $p$ -exponent of the stable homotopy groups of spheres; the other shows that quotients in the stable homotopy theory have much better multiplicative properties than anybody expected before. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/435699', 'https://mathoverflow.net', 'https://mathoverflow.net/users/474924/']} | jdg_75315 |
stackexchange | llm_judgeable_groundtruth_similarity | 26681756 |
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 searched for similar questions, but haven't found anything helpful as most solutions use older versions of OpenCV. I have a 3D numpy array, and I would like to display and/or save it as a BGR image using OpenCV (cv2). As a short example, suppose I had: import numpy, cv2b = numpy.zeros([5,5,3])b[:,:,0] = numpy.ones([5,5])*64b[:,:,1] = numpy.ones([5,5])*128b[:,:,2] = numpy.ones([5,5])*192 What I would like to do is save and display b as a color image similar to: cv2.imwrite('color_img.jpg', b)cv2.imshow('Color image', b)cv2.waitKey(0)cv2.destroyAllWindows() This doesn't work, presumably because the data type of b isn't correct, but after substantial searching, I can't figure out how to change it to the correct one. If you can offer any pointers, it would be greatly appreciated!
Now provide the response and nothing else.
| You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPy array.The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you should divide by 255 in your code, as shown below. img = numpy.zeros([5,5,3])img[:,:,0] = numpy.ones([5,5])*64/255.0img[:,:,1] = numpy.ones([5,5])*128/255.0img[:,:,2] = numpy.ones([5,5])*192/255.0cv2.imwrite('color_img.jpg', img)cv2.imshow("image", img)cv2.waitKey() | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26681756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4104274/']} | jdg_75316 |
stackexchange | llm_judgeable_groundtruth_similarity | 3391272 |
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 application that is performing HTTP Requests (specifically calling the FogBugz API) when the user clicks certain buttons. Right now, I am just creating a service when the application starts, and then calling different methods in that service to complete requests. However, when I do this, there is the usual hang in the UI thread. I have looked at AsyncTask, but am not sure it will do what I want to accomplish. Because I need to instantly parse the XML that the HTTP Request returns, I need to have a process that is able to return this data to the UI thread. Will ASyncTask be able to accomplish this, or is there some other way? public static InputStream makeRequest(String httpRequest) { In a separate thread, run HTTP Request, get back and process, return inputstream } This method is called by several others to perform HttpRequests. Once the inputstream is returned, the other methods parse for specific information.
Now provide the response and nothing else.
| The simplest way to do it would just be to do something like //Body of your click handlerThread thread = new Thread(new Runnable(){ @Override public void run(){ //code to do the HTTP request }});thread.start(); That will cause the code inside the run() method to execute in a new thread of execution. You can look into an async task if you like although I've personally never used it. This is a quick and simple way to get things done. With regards to passing information back, I would use a Handler object which effectively allows you to set up a message queue for a given thread and pass messages to it which cause the execution of specific code. The reason you need to do this is because Android will not let any thread other than the UI thread update the actual UI. Does that address your question? I know my first pass didn't fully address all of your issues. Edit Basically, what you do is define a handler object in your Activity like private Handler handler_ = new Handler(){ @Override public void handleMessage(Message msg){ }}; You also create static int constants that help tell the handler what to do. You basically use those to allow for several different types of messages to be passed to one instance of a handler. If there is only going to be one message that is passed back, then you don't have to worry about that. For example private static final int UPDATE_UI = 1; To send a message to the handler you call handler_.sendMessage(Message.obtain(handler_, UPDATE_UI, inputStreamInstance)); From the handler: private Handler handler_ = new Handler(){ @Overridepublic void handleMessage(Message msg){ switch(msg.what){ case UPDATE_UI: InputStream is = (InputStream)msg.obj; //do what you need to with the InputStream break; } }}; Alternatively, where the inputStreamInstance is added to the Message object, you can pass any object you like so if you wanted to parse it into some kind of container object or something like that, you could do that as well. Just cast it back to that object from within the handler. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3391272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381508/']} | jdg_75317 |
stackexchange | llm_judgeable_groundtruth_similarity | 28183479 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to this whole audio processing area and I'm wondering how to extract Bass, Mid and treble from an FFT output. I'm currently using this to get the data: https://stackoverflow.com/a/20414331/2714577 which uses Naudio. But I'm using a fftlength of 1024 (require speed). I'm trying to get these 3 sections in a format such as 0-255 for colour purposes. I currently have this: double[] data = new double[512]; void FftCalculated(object sender, FftEventArgs e) { for (int j = 0; j < e.Result.Length / 2; j++) { double magnitude = Math.Sqrt(e.Result[j].X * e.Result[j].X + e.Result[j].Y * e.Result[j].Y); double dbValue = 20 * Math.Log10(magnitude); data[j] = dbValue; } double d = 0; for (int i = 20; i < 89; i++) { d += data[i]; } double m = 0; for (int i = 150; i < 255; i++) { m += data[i]; } double t = 0; for (int i = 300; i < 512; i++) { t += data[i]; } Debug.Message(""+d+" |||| "+m+" |||| "+t); } Which returns: Is this right? How do I get this data to something more usable?
Now provide the response and nothing else.
| Let me boil down your question to its essentials: Is there a way, using the TestScheduler , to execute a reactive pipeline and wait for its completion even when it contains asynchronous calls? I should warn you up front, there is no quick and easy answer here, no convenient "trick" that can be deployed. Asynchronous Calls and Schedulers To answer this question I think we need to clarify some points. The term "asynchronous call" in the question above seems to be used specifically to refer to methods with a Task or Task<T> signature - i.e. methods that use the Task Parallel Library (TPL) to run asynchronously. This is important to note because Reactive Extensions (Rx) takes a different approach to handling asynchronous operations. In Rx the introduction of concurrency is managed via a scheduler, a type implementing the IScheduler interface. Any operation that introduces concurrency should make a available a scheduler parameter so that the caller can decide an appropriate scheduler. The core library slavishly adheres to this principle. So, for example, Delay allows specification of a scheduler but Where does not. As you can see from the source , IScheduler provides a number of Schedule overloads. Operations requiring concurrency use these to schedule execution of work. Exactly how that work is executed is deferred completely to the scheduler. This is the power of the scheduler abstraction. Rx operations introducing concurrency generally provide overloads that allow the scheduler to be omitted, and in that case select a sensible default. This is important to note, because if you want your code to be testable via the use of TestScheduler you must use a TestScheduler for all operations that introduce concurrency. A rogue method that doesn't allow this, could scupper your testing efforts. TPL Scheduling Abstraction The TPL has it's own abstraction to handle concurrency: The TaskScheduler . The idea is very similar. You can read about it here. . There are two very important differences between the two abstractions: Rx schedulers have a first class representation of their own notion of time - the Now property. TPL schedulers do not. The use of custom schedulers in the TPL is much less prevalent, and there is no equivalent best practice of providing overloads for providing specific TaskSchedulers to a method introducing concurrency (returning a Task or Task<T> ). The vast majority of Task returning methods assume use of the default TaskScheduler and give you no choice about where work is run. Motivation for TestScheduler The motivation to use a TestScheduler is generally two-fold: To remove the need to "wait" for operations by speeding up time. To check that events occurred at expected points in time. The way this works depends entirely on the fact that schedulers have their own notion of time. Every time an operation is scheduled via an IScheduler , we specify when it must execute - either as soon as possible, or at a specific time in the future. The scheduler then queues work for execution and will execute it when the specified time (according to the scheduler itself) is reached. When you call Start on the TestScheduler , it works by emptying the queue of all operations with execution times at or before its current notion of Now - and then advancing its clock to the next scheduled work time and repeating until its queue is empty. This allows neat tricks like being able to test that an operation will never result in an event! If using real time this would be a challenging task, but with virtual time it's easy - once the scheduler queue is completely empty, then the TestScheduler concludes that no further events will ever happen - since if nothing is left on its queue, there is nothing there to schedule further tasks. In fact Start returns at this precisely this point. For this to work, clearly all concurrent operations to be measured must be scheduled on the TestScheduler . A custom operator that carelessly makes its own choice of scheduler without allowing that choice to be overriden, or an operation that uses its own form of concurrency without a notion of time (such as TPL based calls) will make it difficult, if not impossible, to control execution via a TestScheduler . If you have an asynchronous operation run by other means, judicious use of the AdvanceTo and AdvanceBy methods of the TestScheduler can allow you to coordinate with that foreign source of concurrency - but the extent to which this is achievable depends on the control afforded by that foreign source. In the case of the TPL, you do know when a task is done - which does allow the use of waits and timeouts in tests, as ugly as these can be. Through the use of TaskCompleteSources (TCS) you can mock tasks and use AdvanceTo to hit specific points and complete TCSs, but there is no one simple approach here. Often you just have to resort to ugly waits and timeouts because you don't have sufficient control over foreign concurrency. Rx is generally free-threaded and tries to avoid introducing concurrency wherever possible. Conversely, it's quite possible that different operations within an Rx call chain will need different types of scheduler abstraction. It's not always possible to simulate a call chain with a single test scheduler. Certainly, I have had cause to use multiple TestSchedulers to simulate some complex scenarios - e.g. chains that use the DispatcherScheduler and TaskScheduler sometimes need complex coordination that means you can't simply serialize their operations on to one TestScheduler . Some projects I have worked on have mandated the use of Rx for all concurrency specifically to avoid these problems. That is not always feasible, and even in these cases, some use of TPL is generally inevitable. One particular pain point One particular pain point of Rx that leaves many testers scratching their heads, is the fact that the TPL -> Rx family of conversions introduce concurrency. e.g. ToObservable , SelectMany 's overload accepting Task<T> etc. don't provide overloads with a scheduler and insidiously force you off the TestScheduler thread, even if mocking with TCS. For all the pain this causes in testing alone, I consider this a bug. You can read all about this here - dig through and you'll find Dave Sexton's proposed fix, which provides an overload for specifying a scheduler, and is under consideration for inclusion. You may want to look into that pull request. A Potential Workaround If you can edit your code to use it, the following helper method might be of use. It converts a task to an observable that will run on the TestScheduler and complete at the correct virtual time. It schedules work on the TestScheduler that is responsible for collecting the task result - at the virtual time we state the task should complete. The work itself blocks until the task result is available - allowing the TPL task to run for however long it takes, or until a real amount of specified time has passed in which case a TimeoutException is thrown. The effect of blocking the work means that the TestScheduler won't advance its virtual time past the expected virtual completion time of the task until the task has actually completed. This way, the rest of the Rx chain can run in full-speed virtual time and we only wait on the TPL task, pausing the rest of the chain at the task completion virtual time whilst this happens. Crucially, other concurrent Rx operations scheduled to run in between the start virtual time of the Task based operation and the stated end virtual time of the Task are not blocked and their virtual completion time will be unaffected. So set duration to the length of virtual time you want the task to appear to have taken. The result will then be collected at whatever the virtual time is when the task is started, plus the duration specified. Set timeout to the actual time you will allow the task to take. If it takes longer, a timeout exception is thrown: public static IObservable<T> ToTestScheduledObseravble<T>( this Task<T> task, TestScheduler scheduler, TimeSpan duration, TimeSpan? timeout = null){ timeout = timeout ?? TimeSpan.FromSeconds(100); var subject = Subject.Synchronize(new AsyncSubject<T>(), scheduler); scheduler.Schedule<Task<T>>(task, duration, (s, t) => { if (!task.Wait(timeout.Value)) { subject.OnError( new TimeoutException( "Task duration too long")); } else { switch (task.Status) { case TaskStatus.RanToCompletion: subject.OnNext(task.Result); subject.OnCompleted(); break; case TaskStatus.Faulted: subject.OnError(task.Exception.InnerException); break; case TaskStatus.Canceled: subject.OnError(new TaskCanceledException(task)); break; } } return Disposable.Empty; }); return subject.AsObservable();} Usage in your code would be like this, and your assert will pass: Observable .Return(1) .Select(i => Whatever().ToTestScheduledObseravble( scheduler, TimeSpan.FromSeconds(1))) .Concat() .Subscribe(_ => Interlocked.Increment(ref count)); Conclusion In summary, you haven't missed any convenient trick. You need to think about how Rx works, and how the TPL works and decide whether: You avoid mixing TPL and Rx You mock your interface between TPL and Rx (using TCS or similar), so you test each independently You live with ugly waits and timeouts and abandon the TestScheduler altogether You mix ugly waits and timeouts with TestScheduler to bring some modicum of control over your tests. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28183479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2714577/']} | jdg_75318 |
stackexchange | llm_judgeable_groundtruth_similarity | 38607149 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can use retrolambda to enable lambdas with Android API level <24.So this works myButton.setOnClickListener(view -> Timber.d("Lambdas work!")); This also works Runnable runLater = () -> Timber.d("Lambdas work!");runLater.run(); But this one does not Consumer<Integer> runLaterWithInt = (Integer i) -> Timber.d("i = " + i);runLaterWithInt.accept(3); The last one works on Android API Level 24, but on other devices this code causes a crash java.lang.NoClassDefFoundError: com.retrolambdatry.MainActivity$$Lambda$1 Instead of using retrolambda I tried to enable Java 8. First two code examples still work, although butterknife stopped working. https://developer.android.com/preview/j8-jack.html#configuration here ava.util.function is said to be supported, but I still get a crash when running the third one, this time it is a little different java.lang.NoClassDefFoundError: com.retrolambdatry.MainActivity$-void_onCreate_android_os_Bundle_savedInstanceState_LambdaImpl1
Now provide the response and nothing else.
| Not sure if you still need an answer to this question, but others (like myself) might. As version 3.0, Android Studio natively supports lambda functions and many other Java 8 functions on all API levels, but some (like Functional Interfaces and java.util.function ) are still restricted to APIs 24+. Until that support is expanded, android-retrostreams provides backport support for most of it. This project is an 'upgraded port' of the streamsupport library , which you can also use and has many of the functionalities in android-retrostreams. The streamsupport library supports down to Java 6/7, so you can use it even if you don't have AS 3.0+ or aren't targeting Java 8, but you're probably better off using android-retrostreams in most cases, if you can. You can go through the project's javadocs to see exactly what's offered, but highlights that I've used are java.util.function and java.util.Comparator . Note that java in the package names is replaced with java9 , and some of the class and/or method names may have been changed slightly. For example: java.util.function becomes java9.util.function , while java.util.Comparator becomes java9.util.Comparators (and with slightly different method names and call patterns - but the same functionality). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38607149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3426265/']} | jdg_75319 |
stackexchange | llm_judgeable_groundtruth_similarity | 15753864 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently whenever I try to register a user or login using the default membership services built into ASP.Net MVC4 on my host provider DiscountASP I receive the error To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider". This doesn't happen locally. Here is my InitializeSimpleMembershipAttribute.cs : [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute{ private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public override void OnActionExecuting(ActionExecutingContext filterContext) { // Ensure ASP.NET Simple Membership is initialized only once per app start LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); } private abstract class SimpleMembershipInitializer { protected SimpleMembershipInitializer() { Database.SetInitializer<UsersContext>(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // Create the SimpleMembership database without Entity Framework migration schema ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } } }} Here is a full screenshot of the error: Does anyone know how I can fix this or know an article that addresses it?
Now provide the response and nothing else.
| Try setting the following up in your web.config within the <system.web> node: <roleManager enabled="true" defaultProvider="SimpleRoleProvider"> <providers> <clear /> <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" /> </providers> </roleManager> <membership defaultProvider="SimpleMembershipProvider"> <providers> <clear /> <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" /> </providers> </membership> <sessionState mode="InProc" customProvider="DefaultSessionProvider"> <providers> <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" /> </providers> </sessionState> Sounds like SimpleMembership isn't recognized when you go to use it. Also, it may be worth including, the WebMatrix.webData library can be installed via NuGet: PM> Install-Package Microsoft.AspNet.WebPages.WebData | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15753864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218314/']} | jdg_75320 |
stackexchange | llm_judgeable_groundtruth_similarity | 29290588 |
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 it possible to develop Android apps using only the Android SDK, without any IDE like Android Studio?
Now provide the response and nothing else.
| Yes, see the Google SDK documentation . However, with the current toolchain and documentation it'll be an uphill struggle. I'm trying to do this too (for a dev who lives in Vim and Unix tools, Android Studio is needlessly slow and bloated). The main issues I've found so far: The SDK documentation gives instructions to create an Ant-driven project, but the SDK is now geared towards using Gradle. If you're working through the Google documentation in a linear fashion, you'll find subsequent lessons have you issue Gradle build instructions. For your Ant-built project. There is very little documentation on how to actually create a Gradle-built project from the command line. The command line I use is: android create project --target android-22 --name MyProjectName --path my_project/ --activity MyProject --package com.example.android.myproject --gradle --gradle-version 1.2.2 The --gradle-version actually refers to the Gradle Android plugin version, not the version of Gradle itself. Finding this out wasn't easy. Even if you get it to create a project properly, it probably won't build without further manipulation. One of the generated files ( project/build.gradle ) has an invalid directive name ( runProguard - I'm guessing it's now deprecated). That must be changed to minifyEnabled before the project will build. And using the Gradle plugin 1.2.2, the file project/gradle/wrapper/gradle-wrapper.properties has the Gradle distribution incorrectly listed as gradle-1.2.2-all.zip . This should be gradle-2.2.1-all.zip . These are files generated by the SDK with errors. The documentation is focussed on IDE-based development. Once you get past the initial few pages on creating and managing a project using the command line, it's very IDE-focussed. Instructions on things like changing an app Theme are difficult or impossible to follow as they omit steps that the IDE performs for you. In general, fully IDE-less development for Android (at least in Java, using the official SDK) is very painful. And my personal opinion is that IDE-based development is equally painful (slow, bloated, ugly on high-DPI screens under Linux and evidently full of magic that's a pain to replicate on the command line). Edit: I should add that the above refers to using SDK tools v24.2, SDK Platform-tools v22, SDK Build-tools v22.01 and Android API 22 (5.1.1). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29290588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3559581/']} | jdg_75321 |
stackexchange | llm_judgeable_groundtruth_similarity | 1522752 |
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 call a sproc on server B from server A in TSQL without linking the servers. Is it possible to use something like a connection string to execute this sproc? The return will be a single nvarchar value. Regards.
Now provide the response and nothing else.
| To avoid "linked servers", you'd normally use OPENDATASOURCE After comment: EXEC OPENDATASOURCE('SQLNCLI', 'Data Source=London\Payroll;Integrated Security=SSPI').remoteDB.remoteSchema.remoteProc @param1, @param2,... Simple 4 part naming convention. The whole OPENDATASOURCE simply replaces the linked server name... Note: you may have issues with " adhoc access " | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1522752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135952/']} | jdg_75322 |
stackexchange | llm_judgeable_groundtruth_similarity | 134845 |
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 following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.? function myJsFunc() { alert("myJsFunc");} <a href="#" onclick="myJsFunc();">Run JavaScript Code</a> or function myJsFunc() { alert("myJsFunc");} <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
Now provide the response and nothing else.
| I use javascript:void(0) . Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this: function doSomething() { //Some code return false;} But then they forget to use return doSomething() in the onclick and just use doSomething() . A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function. A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this: onclick="someFunc.call(this)" OR onclick="someFunc.apply(this, arguments)" Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside. So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state: Use href="#" , make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false . OR Use href="javascript:void(0)" The second is clearly much easier to communicate. | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/134845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8018/']} | jdg_75323 |
stackexchange | llm_judgeable_groundtruth_similarity | 221788 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What's common sense when it comes to minimising the risk of employees spreading critical information to rivalling companies? As of today, it's clear that not even the US government and military can be sure that their data stays safely within their doors. Thereby I understand that my question probably instead should be written as "What is common sense to make it harder for employees to spread business critical information?" If anyone would want to spread information, they will find a way. That's the way life work and always has. If we make the scenario a bit more realistic by narrowing our workforce by assuming we only have regular John Does onboard and not Linux-loving sysadmins , what should be good precautions to at least make it harder for the employees to send business-critical information to the competition? As far as I can tell, there's a few obvious solutions that clearly has both pros and cons: Block services such as Dropbox and similar, preventing anyone to send gigabytes of data through the wire. Ensure that only files below a set size can be sent as email (?) Setup VLANs between departments to make it harder for kleptomaniacs and curious people to snoop around. Plug all removable media units - CD/DVD, Floppy drives and USB Make sure that no configurations to hardware can be made (?) Monitor network traffic for non-linear events (how?) What is realistic to do in a real world? How does big companies handle this? Sure, we can take the former employer to court and sue, but by then the damage has already been caused... Thanks a lot
Now provide the response and nothing else.
| There are a variety of things that can be done. The are entire industries created around the very idea of "how do I keep information from leaking". The ubiquity of static data-storage and wireless networks (both wifi and 3G/4G) make wired network-perimeter security less of the barrier than it was even 5 years ago. As with all security, managing the exceptions can be very tricky. Yes, you can disable all USB ports, but that leaves USB keyboards, mice, and printers in the dark. You can disable all access to Facebook, but the Public Relations office will definitely need access. The extremely paranoid can ban all phones with cameras (lest someone phone-cam a doc and mail it to a competitor) but that's really hard to make stick these days. And then there is the old fashioned method of taking home printouts to fax. If someone really wants to leak information, it's generally easy. I can't stress enough the impact that municipal scale high-bandwidth networks have on security posture. With nearly everyone with a camera in their pocket and a phone-plan able to accommodate pictures, 1-5 page documents can be sent with ease without ever touching the corporate LAN. If USB connections are enabled, many smartphones can expose local storage to a workplace computer and have files saved on it which can then be sent from the phone directly if not sneakernetted home and sent from there. The phone-cam 'attack' is particular insidious since it leaves no log-traces on company equipment the way that USB-mounts potentially can. The ironic thing about Internet-access restrictions blocking social networking sites and all known webmail providers is that it forces people onto their phones for the same service. Big companies handle this by ignoring the hard to manage threats (see above for a good example of one) and managing the risks they can mange cheaply. That means: Blocking web-sites of any suspicious class (social media and webmail sites are big ban targets) and known web-proxy sites Recording all outbound email Enforce a captive-portal for internet access, requiring logon with corporate credentials before access is given Monitoring outbound email for private data using varying complexities of filters (big industry with this one) Ensuring least-privilege on the local network so people don't have access to secrets they don't need Using asset-inventorying software to monitor corporate hardware for change events Use event-log monitoring software to track hardware events such as use of removable media Set Group Policies to ban certain behaviors deemed unneeded in the workplace Using strong encryption on any WLANs in use These days the network perimeter is not just at the WAN/LAN demarc, it touches every point of the network where data is released into analog form of any kind and the tools for exploiting such analog holes are getting ever better and ever more common. And other such things. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/221788', 'https://serverfault.com', 'https://serverfault.com/users/38710/']} | jdg_75324 |
stackexchange | llm_judgeable_groundtruth_similarity | 58494201 |
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 successfully installed selenium using pip3 install selenium and pip3 install requests .I use Mac and ran this on terminal and got success message. I even tried sudo pip3 install selenium After that, I tried running my python file (also in local folder) but getting this error message that I can't find a solution. File "file.py", line 1, in <module> from selenium import webdriverImportError: No module named selenium What do I need to do to fix this issue? Thank you for the help in advance!
Now provide the response and nothing else.
| You need to adjust the frame yourself in this case. That requires capturing what the frame is, and then applying the adjustment. First, to capture the existing frame, create a preference , which is a system for passing data from child views to their parents: private struct SizeKey: PreferenceKey { static let defaultValue: CGSize = .zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }}extension View { func captureSize(in binding: Binding<CGSize>) -> some View { overlay(GeometryReader { proxy in Color.clear.preference(key: SizeKey.self, value: proxy.size) }) .onPreferenceChange(SizeKey.self) { size in binding.wrappedValue = size } }} This creates a new .captureSize(in: $binding) method on Views. Using that, we can create a new kind of View that rotates its frame: struct Rotated<Rotated: View>: View { var view: Rotated var angle: Angle init(_ view: Rotated, angle: Angle = .degrees(-90)) { self.view = view self.angle = angle } @State private var size: CGSize = .zero var body: some View { // Rotate the frame, and compute the smallest integral frame that contains it let newFrame = CGRect(origin: .zero, size: size) .offsetBy(dx: -size.width/2, dy: -size.height/2) .applying(.init(rotationAngle: CGFloat(angle.radians))) .integral return view .fixedSize() // Don't change the view's ideal frame .captureSize(in: $size) // Capture the size of the view's ideal frame .rotationEffect(angle) // Rotate the view .frame(width: newFrame.width, // And apply the new frame height: newFrame.height) }} And for convenience, an extension to apply it: extension View { func rotated(_ angle: Angle = .degrees(-90)) -> some View { Rotated(self, angle: angle) }} And now your code should work as you expect: struct TextAloneView: View { var body: some View { VStack { Text("Horizontal text") Text("Vertical text").rotated() } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58494201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10486421/']} | jdg_75325 |
stackexchange | llm_judgeable_groundtruth_similarity | 37970 |
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:
Call a real valued function $f$ a piecewise polynomial if there exists a partition of the real line into non degenerate intervals such that the restriction of $f$ to each interval is a polynomial. Let $g$ be a continuous function mapping rationals to rationals. Must $g$ be a piecewise polynomial?
Now provide the response and nothing else.
| Enumerate the rationals $r_1,r_2,\dots$ and let $$g(x)=a_1(x-r_1)+a_2(x-r_1)(x-r_2)+\dots$$ where $a_1,a_2,\dots$ are rationals heading rapidly to zero. Then clearly $g(x)$ is rational for rational $x$, and if the $a_i$ go to zero fast enough then $g$ is analytic. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/37970', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8619/']} | jdg_75326 |
stackexchange | llm_judgeable_groundtruth_similarity | 1770055 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can one find the inverse of functions like $f(x) = x^3 + x$? I know how to do it for explicit quadratic functions; how do I express $x$ as a function of $y$ here?
Now provide the response and nothing else.
| In general, the inverse of a invertible closed-form function need not itself have a closed form. Simple examples of this include $x \mapsto x^5 + x$ and a suitable restriction of $x \mapsto x^x$ . Since the function $f$ is a cubic polynomial function, we can find an explicit inverse of the given function, $f(x) := x^3 + x$ , by writing $y = x^3 + x$ using Cardano's Formula or the equivalent to solve for $x$ and hence inverting the given function. The (somewhat unpleasant) result is: $$\color{#bf0000}{\boxed{f^{-1}(y) = \frac{1}{6} \left(108 y+12 \sqrt{81 y^2+12}\right)^{1/3} - \frac{2}{\left(108 y+12 \sqrt{81 y^2+12}\right)^{1/3}}}} .$$ See Jack D'Aurizio's nice answer for a more compact way to write this function, using $\sinh$ and $\operatorname{arsinh}$ . Like all quadratic polynomial functions, some cubic polynomial functions are not one-to-one and hence do not admit a (global) inverse. A cubic polynomial $a x^3 + b x^2 + c x + d$ , $a \neq 0$ , is invertible iff its derivative does not have two real roots (which would correspond to local extrema of the cubic polynomial), and this is the case iff the discriminant of the derivative is nonpositive, or equivalently, iff $$b^2 \leq 3 a c .$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1770055', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78963/']} | jdg_75327 |
stackexchange | llm_judgeable_groundtruth_similarity | 1447598 |
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 slightly confused when to use CALayer on the iPhone or Mac and when not to use it? CoreAnimation works just fine on my UIView based objects without having to use CALayer. When is the appropriate time to dig into this class?
Now provide the response and nothing else.
| In my benchmarks, UIView and CALayer provide about the same level of performance on the iPhone. As rpetrich mentions in his comment, UIViews are a thin wrapper around CALayers. On the Mac, CALayers are much more lightweight than NSViews. As Ben points out, you can go beyond the capabilities of implicit animations by working directly with CALayers, even providing some 3-D effects through CATransform3D. In many cases, you can do this even with your standard views by accessing the backing layer (if the view is layer-backed). Another concern is cross-platform (Mac / iPhone) code. My iPhone application uses an all-CALayer interface for its primary view in large part because I can use the exact same code for drawing that interface in its Mac counterpart. For another example of this, I direct you to the Core Plot framework , which draws graphs entirely using CALayers and works on both Mac and iPhone. CALayers are pretty much the same on both platforms, where UIView and NSView have very different interfaces. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1447598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175836/']} | jdg_75328 |
stackexchange | llm_judgeable_groundtruth_similarity | 36679 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have around 1,400 jpegs that have been corrupted somehow and have lost the backup images. They all seem to have the same gridded pattern of lines over each (i.e. the gridding does not shift from image to image. Here's what one of these images looks like: Are there any image filtering techniques in Matlab particulary or otherwise that will remove or smooth this gridding pattern?
Now provide the response and nothing else.
| You can use a standard inpainting algorithm. These algorithms replace marked pixels in an image with the pixel values that surround these marked pixels. The challenge here is to detect the grid (my tests seem to show that it is not a completely regular grid). So, I came up with this solution: from PIL import Imageimport requestsfrom io import BytesIOimport cv2url = "http://i.stack.imgur.com/Ahrnl.jpg"response = requests.get(url)img = Image.open(BytesIO(response.content))plt.imshow(img)A = np.array(img)A2 = A.copy()A_gray = cv2.cvtColor(A, cv2.COLOR_RGB2GRAY)# Do some rough edge detection to find the gridsX = cv2.Sobel(A_gray, cv2.CV_64F, 1, 0, ksize=3)sY = cv2.Sobel(A_gray, cv2.CV_64F, 0, 1, ksize=3)sX[sX<0] = 0sY[sY<0] = 0plt.subplot(221)plt.imshow(sX)plt.subplot(222)plt.imshow(sY)plt.subplot(223)# the sum operation projects the edges to the X or Y-axis. # The 0.2 damps the high peaks a littleeX = (sX**.2).sum(axis=0) eX = np.roll(eX, -1) # correct for the 1-pixel offset due to Sobel filteringplt.plot(eX)plt.subplot(224)eY = (sY**.2).sum(axis=1)eY = np.roll(eY, -1)plt.plot(eY)mask = np.zeros(A2.shape[:2], dtype=np.uint8)mask[eY>480,:] = 1mask[:, eX>390] = 1A2[mask.astype(bool),:] = 255plt.figure()plt.subplot(221)plt.imshow(A)plt.subplot(222)plt.imshow((A2))restored = cv2.inpaint(A, mask, 1, cv2.INPAINT_NS)plt.subplot(223)plt.imshow(restored) The program output is as follows: To detect the grid I did a quick-and-dirty solution. It can be improved a lot, but it shows the initial idea. The general flow is: detect the grid create a mask that describes which pixels are corrupted by the grid inpaint the corrupted pixels. For inpainting I used OpenCV inpaint operation. For detecting the grid, I performed edge detection in X and Y direction using a Sobel filter. Then I add all edge values in the X-direction and Y-direction to find peaks, where the grid lines are. Then, I choose the highest peaks as the coordinates where the grid lines are estimated. It's not working perfect (e.g. strong edges in the image are falsely detected as grid lines), but it shows the idea. It can be improved by e.g. Hough transformation to find lines, kicking out very strong edges etc. Alternatively, if the grid is really the same for all images, then you can perform the grid detection jointly for all images, which would yield a much better accuracy (just do the technique above, but before choosing the peaks, sum up the results from all pictures). In more detail, you would calculate eX for all images and add all these eX together into a single vector. This vector will have a much clearer peak structure and the thresholding can be done easier. | {} | {'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/36679', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/25732/']} | jdg_75329 |
stackexchange | llm_judgeable_groundtruth_similarity | 43466 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Wikipedia claims that the group of units of Z24 (1,5,7,11,13,17,19,23), which all have order 2, and are isomorphic to (Z/2Z)^3 have an important connection to Monstrous Moonshine theory, however, I cannot find any other reference besides Wikipedia that claims this --- It was recommended on sci.math that I pose this question here. Perhaps it's a mistake? And he meant that the primes of the Monster, which continue to 71, are what are considered in Moonshine. Paul Hjelmstad, B.M, B.A. [ Edit (PLC): Here is the relevant passage from wikipedia:] 24 is the highest number $n$ with the property that every element of the group of units $(\mathbb{Z}/n\mathbb{Z})^{\times}$ of the commutative ring $\mathbb{Z}/n\mathbb{Z}$, apart from the identity element, has order $2$; thus the multiplicative group $(\mathbb{Z}/24\mathbb{Z})^{\times} = \{1,5,7,11,13,17,19,23\}$ is isomorphic to the additive group $(\mathbb{Z}/2\mathbb{Z})^3$. This fact plays a role in monstrous moonshine.
Now provide the response and nothing else.
| I think the claim goes back to the 1979 paper "Monstrous Moonshine" by Conway and Norton, where they discuss the "defining property of 24": If $n$ is a positive integer such that $xy \equiv 1$ mod $n$ implies $x \equiv y$, then $n|24$. This fact is used in Atkin's determination of the normalizer of $\Gamma_0(N)$ in $SL_2(\mathbb{R})$. The number 24 plays a special role here, in the sense that the normalizer is $\Gamma_0(n|h)+$, where: $h$ is the largest divisor of 24 such that $h^2|N$ $n = N/h$ $\Gamma_0(n|h) = \left\{ \begin{pmatrix} a & b/h \\ cN & d \end{pmatrix} \mid a,b,c,d \in \mathbb{Z}, ad-bcn/h = 1 \right\}$. The notation is meant to suggest that the group is conjugate to $\Gamma_0(n/h)$, and contains $\Gamma_0(nh)$. The $+$ means we adjoin all possible Atkin-Lehner involutions. If $n/h$ has $k$ prime factors, then this extends $\Gamma_0(n|h)$ by an elementary abelian 2-group of rank $k$. The connection between your observation and moonshine does not seem particularly strong to me, but that may be because I was too young to have experienced firsthand the heady days of numerical exploration. It involves the normalizers of $\Gamma_0(N)$ in the following way: There is a graded representation $V^\natural = \bigoplus V^\natural_m$ of the monster, such that for each element $g$ of the monster, the McKay-Thompson series $T_g(\tau) = \sum_{m \geq -1} Tr(g|V^\natural_m)q^m$ is the $q$-expansion of a modular function invariant under some genus zero group $\Gamma$ that contains and normalizes some $\Gamma_0(N)$, and therefore lies in some $\Gamma_0(n|h)+$ , where $n = |g|$. This fact was essentially the main conjecture in the Conway-Norton paper, although the paper enhances this claim with an explicit list of the candidate functions and their invariance groups. My understanding of the solution process is: Atkin, Fong, and Smith gave a computational proof of existence (1980). Frenkel, Lepowsky, and Meurman constructed a candidate representation $V^\natural$ (1984), and showed that it had a vertex operator algebra structure (1988). Borcherds proved that the candidate representation was satisfactory (1992). Wikipedia and sundry expository books by Gannon, du Sautoy, Ronan, and others can say more about the precise history than I can. I should mention that the number 24 is important as the central charge of $V^\natural$ in Borcherds's solution to the Monstrous Moonshine conjecture, but the paper does not make explicit use of the number 24 in the "group of units" role. One might reasonably argue (through a somewhat convoluted path) that these are the same 24, though. There may be other connections, but I am unaware of them. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/43466', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10350/']} | jdg_75330 |
stackexchange | llm_judgeable_groundtruth_similarity | 1452995 |
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 do : award_dict = { "url" : "http://facebook.com", "imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png", "count" : 1,}def award(name, count, points, desc_string, my_size, parent) : if my_size > count : a = { "name" : name, "description" : desc_string % count, "points" : points, "parent_award" : parent, } a.update(award_dict) return self.add_award(a, siteAlias, alias).award But if felt really cumbersome in the function, and I would have rather done : return self.add_award({ "name" : name, "description" : desc_string % count, "points" : points, "parent_award" : parent, }.update(award_dict), siteAlias, alias).award Why doesn't update return the object so you can chain? JQuery does this to do chaining. Why isn't it acceptable in python?
Now provide the response and nothing else.
| Python's mostly implementing a pragmatically tinged flavor of command-query separation : mutators return None (with pragmatically induced exceptions such as pop ;-) so they can't possibly be confused with accessors (and in the same vein, assignment is not an expression, the statement-expression separation is there, and so forth). That doesn't mean there aren't a lot of ways to merge things up when you really want, e.g., dict(a, **award_dict) makes a new dict much like the one you appear to wish .update returned -- so why not use THAT if you really feel it's important? Edit : btw, no need, in your specific case, to create a along the way, either: dict(name=name, description=desc % count, points=points, parent_award=parent, **award_dict) creates a single dict with exactly the same semantics as your a.update(award_dict) (including, in case of conflicts, the fact that entries in award_dict override those you're giving explicitly; to get the other semantics, i.e., to have explicit entries "winning" such conflicts, pass award_dict as the sole positional arg, before the keyword ones, and bereft of the ** form -- dict(award_dict, name=name etc etc). | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1452995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90025/']} | jdg_75331 |
stackexchange | llm_judgeable_groundtruth_similarity | 47787577 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't save an image file in android oreo(8.0) api 26. The code is working perfectly in api level 25 (7.0) and I didn't find any changes in the documentation " Android 8.0 Behavior Changes " Here is my code String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();File myrootDir = new File(root);if (!myrootDir.exists()) { myrootDir.mkdir();}File myDir = new File(root + "/Myimages");if (!myDir.exists()) { myDir.mkdir();}final String fname = System.currentTimeMillis()+"myimage.png";File file = new File(myDir, fname);if (file.exists()) file.delete();try { FileOutputStream out = new FileOutputStream(file); b.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close();}catch (Exception e){ Log.e("MYAPP", "exception", e);} Exception is FileNotFoundException, No such file or directory. (But Why not in android n ?) java.io.FileNotFoundException: /storage/emulated/0/Pictures/Myimages/1513151272243myimage.png (No such file or directory)12-13 13:17:52.243 5839-5839/com.package.package W/System.err: at java.io.FileOutputStream.open0(Native Method)12-13 13:17:52.243 5839-5839/com.package.package W/System.err: at java.io.FileOutputStream.open(FileOutputStream.java:287)12-13 13:17:52.243 5839-5839/com.package.package W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:223)12-13 13:17:52.243 5839-5839/com.package.package W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:171)12-13 13:17:52.243 5839-5839/com.package.package W/System.err: at com.package.package.DetailPage$12.run(DetailPage.java:737)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at android.os.Handler.handleCallback(Handler.java:789)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at android.os.Handler.dispatchMessage(Handler.java:98)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at android.os.Looper.loop(Looper.java:164)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6541)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at java.lang.reflect.Method.invoke(Native Method)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)12-13 13:17:52.244 5839-5839/com.package.package W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Now provide the response and nothing else.
| There is, in fact, a slight, subtle change in Permissions for apps running on and targeting API 26. Previously, apps were automatically granted all permissions in a given group if at least one permission in that group had been granted by the user. This means that an app that had been granted the READ_EXTERNAL_STORAGE would've had WRITE_EXTERNAL_STORAGE immediately granted to it as well, regardless of whether WRITE_EXTERNAL_STORAGE had been explicitly requested. As of Oreo, for apps targeting API 26+, this has been corrected, and only those permissions that are explicitly requested will be granted. If the user has already granted a permission in the same group, then there will be no prompt for the new permission, but it still must be requested. That was the problem, in this case. When the READ_EXTERNAL_STORAGE permission was granted to your app on Nougat or below, you were automatically getting WRITE_EXTERNAL_STORAGE , too, without having to request that one specifically. When you try the same file save procedure in Oreo, you aren't getting WRITE_EXTERNAL_STORAGE automatically, so the write ultimately fails. Simply add a specific request for WRITE_EXTERNAL_STORAGE . If the user has already granted READ_EXTERNAL_STORAGE , they won't be bothered with another prompt. Alternatively, you could request solely WRITE_EXTERNAL_STORAGE from the start, which implicitly includes READ_EXTERNAL_STORAGE , and would save you the need for two separate requests. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47787577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5668447/']} | jdg_75332 |
stackexchange | llm_judgeable_groundtruth_similarity | 15596955 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that if I have multiple instance of the same class all of them are gonna share the same class variables, so the static properties of the class will use a fixed amount of memory no matter how many instance of the class I have. My question is: If I have a couple subclasses inheriting some static field from their superclass, will they share the class variables or not? And if not, what is the best practice/pattern to make sure they share the same class variables?
Now provide the response and nothing else.
| If I have a couple subclasses inheriting some static field from their superclass, will they share the class variables or not? Yes They will share the same class variables throughout the current running Application in single Classloader. For example consider the code given below, this will give you fair idea of the sharing of class variable by each of its subclasses.. class Super { static int i = 90; public static void setI(int in) { i = in; } public static int getI() { return i; }}class Child1 extends Super{}class Child2 extends Super{}public class ChildTest{ public static void main(String st[]) { System.out.println(Child1.getI()); System.out.println(Child2.getI()); Super.setI(189);//value of i is changed in super class System.out.println(Child1.getI());//same change is reflected for Child1 i.e 189 System.out.println(Child2.getI());//same change is reflected for Child2 i.e 189 }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15596955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/951075/']} | jdg_75333 |
stackexchange | llm_judgeable_groundtruth_similarity | 74723 |
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 problem has been afflicting me for quite a while and it's been really annoying. Every time I login after a reboot/power cycle the explorer takes some time to show up.I've taken the step of waiting for all the services to boot up and then I login, but it doesn't make any difference.The result is always the same: Some of the icons do not show up even if the applications have started. I've dug a bit on the code that makes one application "stick" an icon in there, but is there an API call that one can perform so explorer re-reads all that icon info? Like invalidate or redraw or something of the sort? Apparently, it looks like Jon was right and it's not possible to do it. I've followed Bob Dizzle and Mark Ransom code and build this (Delphi Code): procedure Refresh;var hSysTray: THandle;begin hSysTray := GetSystrayHandle; SendMessage(hSysTray, WM_PAINT, 0, 0);end;function GetSystrayHandle: THandle;var hTray, hNotify, hSysPager: THandle;begin hTray := FindWindow('Shell_TrayWnd', ''); if hTray = 0 then begin Result := hTray; exit; end; hNotify := FindWindowEx(hTray, 0, 'TrayNotifyWnd', ''); if hNotify = 0 then begin Result := hNotify; exit; end; hSyspager := FindWindowEx(hNotify, 0, 'SysPager', ''); if hSyspager = 0 then begin Result := hSyspager; exit; end; Result := FindWindowEx(hSysPager, 0, 'ToolbarWindow32', 'Notification Area');end; But to no avail. I've even tried with InvalidateRect() and still no show. Any other suggestions?
Now provide the response and nothing else.
| Take a look at this blog entry: REFRESHING THE TASKBAR NOTIFICATION AREA . I am using this code to refresh the system tray to get rid of orphaned icons and it works perfectly.The blog entry is very informative and gives a great explanation of the steps the author performed to discover his solution. #define FW(x,y) FindWindowEx(x, NULL, y, L"")void RefreshTaskbarNotificationArea(){ HWND hNotificationArea; RECT r; GetClientRect( hNotificationArea = FindWindowEx( FW(FW(FW(NULL, L"Shell_TrayWnd"), L"TrayNotifyWnd"), L"SysPager"), NULL, L"ToolbarWindow32", // L"Notification Area"), // Windows XP L"User Promoted Notification Area"), // Windows 7 and up &r); for (LONG x = 0; x < r.right; x += 5) for (LONG y = 0; y < r.bottom; y += 5) SendMessage( hNotificationArea, WM_MOUSEMOVE, 0, (y << 16) + x);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/74723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8167/']} | jdg_75334 |
stackexchange | llm_judgeable_groundtruth_similarity | 3247207 |
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:
Problem Let $f(x)$ be a differentiable function with $f(0)=1$ and $f(1)=2$ . For any $a,x$ where $a \neq 0$ , it holds $$\frac{1}{2a}\int_{x-a}^{x+a}f(t)dt=f(x).$$ Find $f(x)$ . Attempt Since $$f(x)=\frac{\displaystyle\int_{x-a}^{x+a}f(t)dt}{2a}$$ holds for all $x \in \mathbb{R}$ and $a \neq 0$ . One can fix $x$ and take the limit as $a \to 0$ . Thus $$\lim_{a \to 0}f(x)=\lim_{a \to 0}\frac{\displaystyle\int_{x-a}^{x+a}f(t)dt}{2a}=\frac{f(x+a)+f(x-a)}{2},$$ where we applied L'Hopital's rule. Thus $$f(x)=\frac{f(x+a)+f(x-a)}{2}.$$ How to go on from here?
Now provide the response and nothing else.
| The answer is that $f(x)=1+x$ . By differentiating both sides you get $$\frac{f(x+a)-f(x-a)}{2a}=f'(x)$$ and this holds for every $a$ , so differentiating by $a$ : $$(f'(x+a)+f'(x-a))2a-2(f(x+a)-f(x-a))=0$$ Dividing by $a$ you get: $$f'(x+a)+f'(x-a)=\frac{f(x+a)-f(x-a)}{a}=2f'(x)$$ Differentiating by $a$ again gives $$f''(x+a)-f''(x-a)=0$$ and since $x,a$ are arbitrary, this implies that $f''(x)$ is constant. Therefore, $f(x)=\alpha+\beta x+\gamma x^2$ for some $\alpha,\beta,\gamma$ . Invoking the initial data we deduce that $f(x)=1+\beta x+(1-\beta)x^2$ for some $\beta$ . Integrating around zero, we get $$1=f(0)=\frac{1}{2a}\int_{-a}^a(1+\beta t+(1-\beta)t^2)\,dt=1-\frac{a^2}{3}(\beta-1)$$ which implies that $\beta=1$ , and so the function $f(x)$ must be equal to $1+x$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3247207', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/560634/']} | jdg_75335 |
stackexchange | llm_judgeable_groundtruth_similarity | 30299671 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to match strings with a wildcard (*), where the wildcard means "any". For example: *X = string must end with XX* = string must start with X*X* = string must contain X Also, some compound uses such as: *X*YZ* = string contains X and contains YZX*YZ*P = string starts with X, contains YZ and ends with P. Is there a simple algorithm to do this? I'm unsure about using regex (though it is a possibility). To clarify, the users will type in the above to a filter box (as simple a filter as possible), I don't want them to have to write regular expressions themselves. So something I can easily transform from the above notation would be good.
Now provide the response and nothing else.
| Often, wild cards operate with two type of jokers: ? - any character (one and only one) * - any characters (zero or more) so you can easily convert these rules into appropriate regular expressio n: // If you want to implement both "*" and "?"private static String WildCardToRegular(String value) { return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; }// If you want to implement "*" onlyprivate static String WildCardToRegular(String value) { return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$"; } And then you can use Regex as usual: String test = "Some Data X"; Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X")); Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*")); Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*")); // Starts with S, ends with X, contains "me" and "a" (in that order) Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X")); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30299671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416274/']} | jdg_75336 |
stackexchange | llm_judgeable_groundtruth_similarity | 7777913 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read lots of information about getting depth with fragment shader. such as http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=234519 but I still don't know whether or not the gl_FragCoord.z is linear. GLSL specification said its range is [0,1] in screen sapce without mentioning it's linear or not. I think linearity it is vital since I will use the rendered model to match depth map from Kinect. Then if it is not linear, how to linearlize it in the world space?
Now provide the response and nothing else.
| but I still don't know whether or not the gl_FragCoord.z is linear. Whether gl_FragCoord.z is linear or not depends on, the projection matrix.While for Orthographic Projection gl_FragCoord.z is linear, for Perspective Projection it is not linear. In general, the depth ( gl_FragCoord.z and gl_FragDepth ) is calculated as follows (see GLSL gl_FragCoord.z Calculation and Setting gl_FragDepth ): float ndc_depth = clip_space_pos.z / clip_space_pos.w;float depth = (((farZ-nearZ) * ndc_depth) + nearZ + farZ) / 2.0; The projection matrix describes the mapping from 3D points of a scene, to 2D points of the viewport. It transforms from eye space to the clip space, and the coordinates in the clip space are transformed to the normalized device coordinates (NDC) by dividing with the w component of the clip coordinates Orthographic Projection At Orthographic Projection the coordinates in the eye space are linearly mapped to normalized device coordinates. Orthographic Projection Matrix: r = right, l = left, b = bottom, t = top, n = near, f = far 2/(r-l) 0 0 00 2/(t-b) 0 00 0 -2/(f-n) 0-(r+l)/(r-l) -(t+b)/(t-b) -(f+n)/(f-n) 1 At Orthographic Projection, the Z component is calculated by the linear function : z_ndc = z_eye * -2/(f-n) - (f+n)/(f-n) Perspective Projection At Perspective Projection the projection matrix describes the mapping from 3D points in the world as they are seen from of a pinhole camera, to 2D points of the viewport. The eye space coordinates in the camera frustum (a truncated pyramid) are mapped to a cube (the normalized device coordinates). Perspective Projection Matrix: r = right, l = left, b = bottom, t = top, n = near, f = far2*n/(r-l) 0 0 00 2*n/(t-b) 0 0(r+l)/(r-l) (t+b)/(t-b) -(f+n)/(f-n) -1 0 0 -2*f*n/(f-n) 0 At Perspective Projection, the Z component is calculated by the rational function : z_ndc = ( -z_eye * (f+n)/(f-n) - 2*f*n/(f-n) ) / -z_eye Depth buffer Since the normalized device coordinates are in range (-1,-1,-1) to (1,1,1) the Z-coordinate has to be mapped to the depth buffer range [0,1]: depth = (z_ndc + 1) / 2 Then if it is not linear, how to linearize it in the world space? To convert form the depth of the depth buffer to the original Z-coordinate, the projection (Orthographic or Perspective), and the near plane and far plane has to be known. Orthographic Projection n = near, f = farz_eye = depth * (f-n) + n; Perspective Projection n = near, f = farz_ndc = 2.0 * depth - 1.0;z_eye = 2.0 * n * f / (f + n - z_ndc * (f - n)); If the perspective projection matrix is known this can be done as follows: A = prj_mat[2][2]B = prj_mat[3][2]z_eye = B / (A + z_ndc) See also the answer to How to recover view space position given view space depth value and ndc xy | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7777913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/921082/']} | jdg_75337 |
stackexchange | llm_judgeable_groundtruth_similarity | 37411633 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to generate a random integer as with np.random.randint() , but with a normal distribution around 0. np.random.randint(-10, 10) returns integers with a discrete uniform distribution np.random.normal(0, 0.1, 1) returns floats with a normal distribution What I want is a kind of combination between the two functions.
Now provide the response and nothing else.
| One other way to get a discrete distribution that looks like the normal distribution is to draw from a multinomial distribution where the probabilities are calculated from a normal distribution. import scipy.stats as ssimport numpy as npimport matplotlib.pyplot as pltx = np.arange(-10, 11)xU, xL = x + 0.5, x - 0.5 prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3)prob = prob / prob.sum() # normalize the probabilities so their sum is 1nums = np.random.choice(x, size = 10000, p = prob)plt.hist(nums, bins = len(x)) Here, np.random.choice picks an integer from [-10, 10]. The probability for selecting an element, say 0, is calculated by p(-0.5 < x < 0.5) where x is a normal random variable with mean zero and standard deviation 3. I chose a std. dev. of 3 because this way p(-10 < x < 10) is almost 1. The result looks like this: | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37411633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1545917/']} | jdg_75338 |
stackexchange | llm_judgeable_groundtruth_similarity | 2386860 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This conjecture is tested for all odd natural numbers less than $10^8$: If $n>1$ is an odd natural number, then there are natural numbers $a,b$ such that $n=a+b$ and $a^2+b^2\in\mathbb P$. $\mathbb P$ is the set of prime numbers. I wish help with counterexamples, heuristics or a proof. Addendum: For odd $n$, $159<n<50,000$, there are $a,b\in\mathbb Z^+$ such that $n=a+b$ and both$a^2+b^2$ and $a^2+(b+2)^2$ are primes. As hinted by pisco125 in a comment, there is a weaker version of the conjecture: Every odd number can be written $x+y$ where $x+iy$ is a Gaussian prime. Which give arise to a function: $g:\mathbb P_G\to\mathbb O'$, given by $g(x+iy)=x+y$, where $\mathbb O'$ is the odd integers with $0,\pm 2$ included. The weaker conjecture is then equivalent with that $g$ is onto. The reason why the conjecture is weaker is that any prime of the form $p=4n-1$ is a Gaussian prime. The reason why $0,\pm 2$ must be added is that $\pm 1 \pm i$ is a Gaussian prime.
Now provide the response and nothing else.
| Here are some heuristics. As Hans Engler defines, let $k(n)$ be the number of pairs $(a,b)$ with $a<b$ for which $a+b=n$ and $a^2+b^2$ is prime. In other words,$$k(n) = \#\{ 1\le a < \tfrac n2 \colon a^2 + (n-a)^2 = 2a^2 - 2an + n^2 \text{ is prime} \}.$$Ignoring issues of uniformity in $n$, the Bateman–Horn conjecture predicts that the number of prime values of an irreducible polynomial $f(a)$ up to $x$ is asymptotic to$$\frac x{\log x} \prod_p \bigg( 1-\frac1p \bigg)^{-1} \bigg( 1-\frac{\sigma(p)}p \bigg),$$where $\log$ denotes the natural logarithm and$$\sigma(p) = \#\{ 1\le t\le p\colon f(t) \equiv 0 \pmod p \}.$$ We now calculate $\sigma(p)$ for $f(a) = 2a^2 - 2an + n^2$.Note that the discriminant of $f$ is $(-2n)^2 - 4\cdot2n^2 = -4n^2$. Therefore if $p$ does not divide $-4n^2$, the number of solutions is given by the Legendre symbol$$\sigma(p) = 1 + \bigg (\frac{-4n^2}p\bigg) = 1 + \bigg (\frac{-1}p\bigg) = \begin{cases}2, &\text{if } p\equiv1\pmod 4, \\0, &\text{if } p\equiv3\pmod 4.\end{cases}$$Furthermore, we can check by hand that if $p=2$ then $\sigma(p)=0$, while if $p$ divides $n$ then $\sigma(p)=1$. Therefore our prediction becomes$$k(n) \approx \frac{n/2}{\log(n/2)} \cdot 2 \prod_{\substack{p\equiv1\pmod 4 \\ p\nmid n}} \frac{p-2}{p-1} \prod_{\substack{p\equiv3\pmod 4 \\ p\nmid n}} \frac p{p-1}.$$(We're abusing notation: those two products don't individually converge, but their product converges when the primes are taken in their natural order.)In principle that constant could be cleverly evaluated to several decimal places. But for the purposes of experiment, perhaps it's valuable to note that $k(n)$ should be approximately $n/\log n$, times some universal constant, times$$\prod_{\substack{p\equiv1\pmod 4 \\ p\mid n}} \frac{p-1} {p-2}\prod_{\substack{p\equiv3\pmod 4 \\ p\mid n}} \frac {p-1}p;$$and so the data can be normalized by that function of $n$ to test for consistency. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2386860', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171248/']} | jdg_75339 |
stackexchange | llm_judgeable_groundtruth_similarity | 10002918 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Trying to understand vectors a bit more. What is the need for normalizing a vector? If I have a vector, N = (x, y, z) What do you actually get when you normalize it - I get the idea you have to divide x/|N| y/|N| & z/|N|. My question is, why do we do this thing, I mean what do we get out of this equation? What is the meaning or 'inside' purpose of doing this. A bit of a maths question, I apologize, but I am really not clear in this topic.
Now provide the response and nothing else.
| For any vector V = (x, y, z) , |V| = sqrt(x*x + y*y + z*z) gives the length of the vector. When we normalize a vector, we actually calculate V/|V| = (x/|V|, y/|V|, z/|V|) . It is easy to see that a normalized vector has length 1. This is because: | V/|V| | = sqrt((x/|V|)*(x/|V|) + (y/|V|)*(y/|V|) + (z/|V|)*(z/|V|)) = sqrt(x*x + y*y + z*z) / |V| = |V| / |V| = 1 Hence, we can call normalized vectors as unit vectors (i.e. vectors with unit length). Any vector, when normalized, only changes its magnitude, not its direction. Also, every vector pointing in the same direction, gets normalized to the same vector (since magnitude and direction uniquely define a vector). Hence, unit vectors are extremely useful for providing directions. Note however, that all the above discussion was for 3 dimensional Cartesian coordinates (x, y, z) . But what do we really mean by Cartesian coordinates? Turns out, to define a vector in 3D space, we need some reference directions. These reference directions are canonically called i , j , k (or i, j, k with little caps on them - referred to as "i cap", "j cap" and "k cap"). Any vector we think of as V = (x, y, z) can actually then be written as V = xi + yj + zk . (Note: I will no longer call them by caps, I'll just call them i, j, k). i, j, and k are unit vectors in the X, Y and Z directions and they form a set of mutually orthogonal unit vectors. They are the basis of all Cartesian coordinate geometry. There are other forms of coordinates (such as Cylindrical and Spherical coordinates), and while their coordinates are not as direct to understand as (x, y, z) , they too are composed of a set of 3 mutually orthogonal unit vectors which form the basis into which 3 coordinates are multiplied to produce a vector. So, the above discussion clearly says that we need unit vectors to define other vectors, but why should you care? Because sometimes, only the magnitude matters. That's when you use a "regular" number (something like 4 or 1/3 or 3.141592653 - nope, for all you OCD freaks, I am NOT going to put Pi there - that shall stay a terminating decimal, just because I am evil incarnate). You would not want to thrown in a pesky direction, would you? I mean, does it really make sense to say that I want 4 kilograms of watermelons facing West? Unless you are some crazy fanatic, of course. Other times, only the direction matters. You just don't care for the magnitude, or the magnitude just is too large to fathom (something like infinity, only that no one really knows what infinity really is - All Hail The Great Infinite, for He has Infinite Infinities... Sorry, got a bit carried away there). In such cases, we use normalization of vectors. For example, it doesn't mean anything to say that we have a line facing 4 km North. It makes more sense to say we have a line facing North. So what do you do then? You get rid of the 4 km. You destroy the magnitude. All you have remaining is the North (and Winter is Coming). Do this often enough, and you will have to give a name and notation to what you are doing. You can't just call it "ignoring the magnitude". That is too crass. You're a mathematician, and so you call it "normalization", and you give it the notation of the "cap" (probably because you wanted to go to a party instead of being stuck with vectors). BTW, since I mentioned Cartesian coordinates, here's the obligatory XKCD: | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10002918', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1289288/']} | jdg_75340 |
Subsets and Splits