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 | 903038 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am sorry for asking two questions in one but they are strongly related. What is an example of (affine?) schemes $X=(|X|,\mathcal{O}_X)$ and $Y=(|Y|,\mathcal{O}_Y)$ and a map of topological spaces $|f|\colon|X|\to |Y|$ that cannot be promoted into a map $f\colon X\to Y$ of schemes? I guess something like $exp:\mathbb{R}\to\mathbb{R}$ is an example but I cannot prove that it is an example. What is an example of (affine?) schemes $X=(|X|,\mathcal{O}_X)$ and $Y=(|Y|,\mathcal{O}_Y)$ and a map of topological spaces $|f|\colon|X|\to |Y|$ that can be promoted into a map $f_1\colon X\to Y$ of schemes and into a map $f_2\colon X\to Y$ a map of schemes with $f_1\neq f_2$?
Now provide the response and nothing else.
| Just take $X=\mathrm{Spec}(K)$ and $Y=\mathrm{Spec}(L)$ for two fields $K,L$. There is a unique map $|X| \to |Y|$. The morphisms $X \to Y$ correspond to field homomorphisms $L \to K$. There may be no such homomorphisms, but there may be also many of them. (For example, consider $\mathbb{Q}(\sqrt{2}) \to \mathbb{Q}$ or $\mathbb{Q}(\sqrt{2}) \to \mathbb{Q}(\sqrt{2})$). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/903038', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112173/']} | jdg_76141 |
stackexchange | llm_judgeable_groundtruth_similarity | 18868128 |
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 php calender which will show one week at a time.Here is the code i have created <?php $week = date("W"); $year = (isset($_GET['year']))?$_GET['year']:date("Y"); $week = (isset($_GET['week']))?$_GET['week']:Date('W'); if($week>53){ $year+= 1; $week=1; } ?> <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a> <!--Next week--> <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> <!--Previous week--> <table border="1px"> <tr> <td>Employee</td> <?php for($day=1; $day<=7; $day++) { $d = strtotime($year."W".$week.$day); echo "<td>".date('l',$d )."<br>"; echo date('d M',$d)."</td>"; } ?> </tr> when i am trying to go to the next week it is working correctly. But when the year is changing it is not working for the next year.
Now provide the response and nothing else.
| Leave the week calculation to the DateTime::setIsoDate() method. Here is the simplest and best solution for your problem : <?php$dt = new DateTime;if (isset($_GET['year']) && isset($_GET['week'])) { $dt->setISODate($_GET['year'], $_GET['week']);} else { $dt->setISODate($dt->format('o'), $dt->format('W'));}$year = $dt->format('o');$week = $dt->format('W');?><a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> <!--Previous week--><a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a> <!--Next week--><table> <tr> <td>Employee</td><?phpdo { echo "<td>" . $dt->format('l') . "<br>" . $dt->format('d M Y') . "</td>\n"; $dt->modify('+1 day');} while ($week == $dt->format('W'));?> </tr></table> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18868128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2790769/']} | jdg_76142 |
stackexchange | llm_judgeable_groundtruth_similarity | 11333354 |
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 there is a Robolectric.shadowOf(Fragment) method and a ShadowFragment class, thought they aren't listed on the docs, but I can't make it work. myFragment = new MyFragment();myFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null);myFragment.onAttach(activity);myFragment.onActivityCreated(null); I'm working with API level 13 (Honeycomb). Thanks.
Now provide the response and nothing else.
| Edit #4 & #5 : In Robolectric 3.* , they split up the fragment starting functions. For support fragments, you will need to add a dependency to your build.gradle : testCompile "org.robolectric:shadows-supportv4:3.8" Import: org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment; For platform fragments, you don't need this dependency. Import: import static org.robolectric.util.FragmentTestUtil.startFragment; They both use the same name of startFragment() . import static org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment;@RunWith(RobolectricTestRunner.class)@Config(constants = BuildConfig.class)public class YourFragmentTest{ @Test public void shouldNotBeNull() throws Exception { YourFragment fragment = YourFragment.newInstance(); startFragment( fragment ); assertNotNull( fragment ); }} Edit #3 : Robolectric 2.4 has an API for support and regular fragments . You can either use the newInstance() pattern or use the constructor when constructing your Fragment 's. import org.junit.Test;import org.junit.runner.RunWith;import static org.junit.Assert.assertNotNull;import static org.robolectric.util.FragmentTestUtil.startFragment;@RunWith(RobolectricGradleTestRunner.class)public class YourFragmentTest{ @Test public void shouldNotBeNull() throws Exception { YourFragment fragment = new YourFragment(); startFragment( fragment ); assertNotNull( fragment ); }} Edit #2 : There's a new helper if you're using support fragments ( one that supports regular activities/fragments should be in the next release ): import static org.robolectric.util.FragmentTestUtil.startFragment;@Beforepublic void setUp() throws Exception{ fragment = YourFragment.newInstance(); startFragment( fragment );} Edit : If you upgraded to Robolectric 2.0: public static void startFragment( Fragment fragment ){ FragmentActivity activity = Robolectric.buildActivity( FragmentActivity.class ) .create() .start() .resume() .get(); FragmentManager fragmentManager = activity.getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add( fragment, null ); fragmentTransaction.commit();} Original answer As the other commenter suggested, you do need to use the fragment manager (instead of calling the lifecycle methods you listed above). @RunWith(MyTestRunner.class)public class YourFragmentTest{ @Test public void shouldNotBeNull() throws Exception { YourFragment yourFragment = new YourFragment(); startFragment( yourFragment ); assertNotNull( yourFragment ); } I create a test runner and have a function that starts up a fragment for me so I can use it everywhere. public class MyTestRunner extends RobolectricTestRunner{ public MyTestRunner( Class<?> testClass ) throws InitializationError { super( testClass ); } public static void startFragment( Fragment fragment ) { FragmentManager fragmentManager = new FragmentActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add( fragment, null ); fragmentTransaction.commit(); }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11333354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397244/']} | jdg_76143 |
stackexchange | llm_judgeable_groundtruth_similarity | 34317 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have learnt that elements on the left-hand side of the periodic table such as sodium and magnesium prefer to lose electrons to form a cation because this requires less energy to obtain a stable octet, and vice-versa for the right-hand side of the periodic table e.g. fluorine. However, using this reasoning I am not sure why all transition metals tend to lose electrons rather than gain them.
Now provide the response and nothing else.
| See the outer configuration of some transition elements: Sc: $\mathrm{[Ar]~3d^1 4s^2}$ Cr: $\mathrm{[Ar]~3d^5 4s^\color{red}{1}}$ Co: $\mathrm{[Ar]~3d^7 4s^2}$ Cu: $\mathrm{[Ar]~3d^{10} 4s^\color{red}{1}}$ Zn: $\mathrm{[Ar]~3d^{10} 4s^2}$ If you are wondering about configuration of Cu and Cr read why this happens! As you may notice, they can form ions by either losing or gaining electron in 4s orbital. In the chemistry of the transition elements, the 4s orbital behaves as the outermost, highest energy orbital. When these metals form ions, the 4s electrons are always lost first, leading to a positive charge on ion. Gaining any electron in 4s orbital would decrease the stability of anion thus formed. So, they form only cations (positive ions) . In general, the outer electronic configuration of transition elements is $n~\mathrm{s}^2~(n-1)\mathrm{d}^{1-10}$. Because of reasons above, the electron removes from the $\ce{ns}$ orbital, where n = principal quantum number of atom. See $\ce{Zn^{2+}}$ configuration: $\mathrm{[Ar] (3d)^{10}}$ as an example. The electron exits from 4s orbital, leading to the formation of a positively charged ion. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/34317', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/16851/']} | jdg_76144 |
stackexchange | llm_judgeable_groundtruth_similarity | 4365745 |
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 call protected constructor? public class Foo{ public Foo(a lot of arguments){} protected Foo(){}}var foo=??? This obviously fails test: public class FooMock:Foo{}var foo=new FooMock();Assert(typeof(Foo), foo.GetType());
Now provide the response and nothing else.
| You can only call that from a subclass, basically. Your FooMock class will already be calling the protected constructor, because it's equivalent to: public class FooMock : Foo{ public FooMock() : base() // Call the protected base constructor { }} However, your assertion will fail because the type of object referred to be foo is FooMock , not Foo . An assertion of the form foo is Foo will pass though. You can't construct an instance of just Foo by calling the protected constructor directly. The point of it being protected instead of public is to ensure that it's only called by subclasses (or within the text of Foo itself). It's possible that you could call it with reflection within a full trust context, but I'd urge you not to do so. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4365745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82062/']} | jdg_76145 |
stackexchange | llm_judgeable_groundtruth_similarity | 35308273 |
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 multiple tables on my web page and each one is a DataTable, it is working fine. I want to enable the export to excel functionality on each of the datatable but the button should be outside the table DOM (and each table should have its own button to export). I can genrate the HTML5 button inside the table DOM using: $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ] } ); But i want someway by which i can attach a button outside the table DOM to act as a export to excel for specific table.
Now provide the response and nothing else.
| Initialize each tables buttons via a constructor , by that you can place the button elements in any container you want. If you want to place the buttons in a <div id="buttons"></div> element outside the table, do this var buttons = new $.fn.dataTable.Buttons(table, { buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ]}).container().appendTo($('#buttons')); demo -> https://jsfiddle.net/qoqq3okg/ I dont know your multiple tables setup, but now you just have to insert some elements along each <table> element and inject buttons for each table into that element as described above. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35308273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1496715/']} | jdg_76146 |
stackexchange | llm_judgeable_groundtruth_similarity | 6588674 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What does bundle exec rake db:migrate mean? Or just bundle exec rake <command> in general? I understand that bundle takes care of maintaining things in the Gemfile. I know what the word "exec" means. I understand that rake maintains all the different scripty things you can do, and I know that db:migrate is one of those. I just don't know what all these words are doing together. Why should bundle be used to execute rake to execute a database migrate?
Now provide the response and nothing else.
| bundle exec is a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile ). rake db:migrate is the script where db is the namespace and migrate is the task name defined. So bundle exec rake db:migrate executes the rake script with the command db:migrate in the context of the current bundle. As to the "why?" I'll quote from the bundler page : In some cases, running executables without bundle exec may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle. However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/6588674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348056/']} | jdg_76147 |
stackexchange | llm_judgeable_groundtruth_similarity | 145621 |
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:
Here is the question: You roll a fair 6-sided dice iteratively until the sum of the dice rolls is greater than or equal to M. What is the mean and standard deviation of the sum minus M when M=300? Should I write a code to answer these kind of questions? Please give me some hints on that. thanks!
Now provide the response and nothing else.
| You can certainly use code, but I wouldn't simulate. I'm going to ignore the "minus M" part (you can do that easily enough at the end). You can compute the probabilities recursively very easily, but the actual answer (to a very high degree of accuracy) can be calculated from simple reasoning. Let the rolls be $X_1, X_2, ...$. Let $S_t=\sum_{i=1}^t X_i$. Let $\tau$ be the smallest index where $S_\tau\geq M$. $P(S_\tau=M)=P(\text{got to }M-6\text{ at }\tau-1\text{ and rolled a }6) \\\qquad\qquad\qquad+ P(\text{got to }M-5\text{ at }\tau-1\text{ and rolled a }5)\\\qquad\qquad\qquad +\:\: \vdots\\\qquad\qquad\qquad+\:P(\text{got to }M-1\text{ at }\tau-1\text{ and rolled a }1)\\\qquad\qquad\quad=\frac{1}{6}\sum_{j=1}^6 P(S_{\tau-1}=M-j)$ similarly $P(S_\tau=M+1)=\frac{1}{6}\sum_{j=1}^5 P(S_{\tau-1}=M-j)$ $P(S_\tau=M+2)=\frac{1}{6}\sum_{j=1}^4 P(S_{\tau-1}=M-j)$ $P(S_\tau=M+3)=\frac{1}{6}\sum_{j=1}^3 P(S_{\tau-1}=M-j)$ $P(S_\tau=M+4)=\frac{1}{6}\sum_{j=1}^2 P(S_{\tau-1}=M-j)$ $P(S_\tau=M+5)=\frac{1}{6} P(S_{\tau-1}=M-1)$ Equations similar to the first one above could then (at least in principle) be run back until you hit any of the initial conditions to get an algebraic relationship between the initial conditions and the probabilities we want (which would be tedious and not especially enlightening), or you can construct the corresponding forward equations and run them forward from the initial conditions, which is easy to do numerically (and which is how I checked my answer). However, we can avoid all that. The points' probabilities are running weighted averages of previous probabilities; these will (geometrically quickly) smooth out any variation in probability from the initial distribution (all probability at point zero in the case of our problem). The To an approximation (a very accurate one) we can say that $M-6$ to $M-1$ should be almost equally probable at time $\tau-1$ (really close to it), and so from the above we can write down that the probabilities will be very close to being in simple ratios, and since they must be normalized, we can just write down probabilities. Which is to say, we can see that if the probabilities of starting from $M-6$ to $M-1$ were exactly equal, there are 6 equally likely ways of getting to $M$, 5 of getting to $M+1$, and so on down to 1 way of getting to $M+5$. That is, the probabilities are in the ratio 6:5:4:3:2:1, and sum to 1, so they're trivial to write down. Computing it exactly (up to accumulated numerical round off errors) by running the probability recursions forward from zero (I did it in R) gives differences on the order of .Machine$double.eps ($\approx$ 2.22e-16 on my machine) from the above approximation (which is to say, simple reasoning along the above lines gives effectively exact answers, since they're as close to the answers computed from recursion as we'd expect the exact answers should be). Here's my code for that (most of it's just initializing the variables, the work is all in one line). The code starts after the first roll (to save me putting in a cell 0, which is a small nuisance to deal with in R); at each step it takes the lowest cell which could be occupied and moves forward by a die roll (spreading the probability of that cell over the next 6 cells): p = array(data = 0, dim = 305) d6 = rep(1/6,6) i6 = 1:6 p[i6] = d6 for (i in 1:299) p[i+i6] = p[i+i6] + p[i]*d6 (we could use rollapply (from zoo ) to do this more efficiently - or a number of other such functions - but it will be easier to translate if I keep it explicit) Note that d6 is a discrete probability function over 1 to 6, so the code inside the loop in the last line is constructing running weighted averages of earlier values. It's this relationship that makes the probabilities smooth out (until the last few values we're interested in). So here's the first 50-odd values (the first 25 values marked with circles). At each $t$, the value on the y-axis represents the probability that accumulated in the hindmost cell before we rolled it forward into the next 6 cells. As you see it smooths out (to $1/\mu$, the reciprocal of the mean of the number of steps each die roll takes you) quite quickly and stays constant. And once we hit $M$, those probabilities drop away (because we're not putting the probability for values at $M$ and beyond forward in turn) So the idea that the values at $M-1$ to $M-6$ should be equally likely because the fluctuations from the initial conditions will get smoothed out is clearly seen to be the case. Since the reasoning doesn't depend on anything but that $M$ is large enough that the initial conditions wash out so that $M-1$ to $M-6$ are nearly equally probable at time $\tau-1$, the distribution will be essentially the same for any large $M$, as Henry suggested in comments. In retrospect, Henry's hint (which is also in your question) to work with the sum minus M would save a little effort, but the argument would follow very similar lines. You could proceed by letting $R_t=S_t-M$ and writing similar equations relating $R_0$ to the preceding values, and so on. From the probability distribution, the mean and the variance of the probabilities are then simple. Edit: I suppose I should give the asymptotic mean and standard deviation of the final position minus $M$: The asymptotic mean excess is $\frac{5}{3}$ and the standard deviation is $\frac{2\sqrt 5}{3}$. At $M=300$ this is accurate to a much greater degree than you're likely to care about. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/145621', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/73186/']} | jdg_76148 |
stackexchange | llm_judgeable_groundtruth_similarity | 1163473 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know why my require_once () or die(); is not working. It's always shown the Fatal error instead of the error message that I key in into the die(). See below for my code: require_once ('abc.php') or die("oops"); Error message display as below "Fatal error: controller::require_once() [function.require]: Failed opening required '1' (include_path='....." instead of the message ( "oops" ) I key in.
Now provide the response and nothing else.
| or has a higher precedence than require/require_once. Therefore php evaluates ('abc.php') or die("oops") before passing the result to require_once. Or takes two boolean operands. ('abc.php') evaluates to true therefore the whole expression is true and require_once true; is invoked. require_once takes a string, bool(true)->string => 1 => Failed opening required ' 1 ' You don't need the or die(...) there. If the file can't be read require_once will stop the php instance anyway. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1163473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52745/']} | jdg_76149 |
stackexchange | llm_judgeable_groundtruth_similarity | 4289548 |
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 was asked to find a group where $a^{3} = e$ $ \forall a \in G$ , G being the group. I came across the Heisenberg group(which from my understand is the group of all $3 \times 3$ matrices which has one along its diagonals and 0s in the bottom half, and real numbers in the top half). But when I multiplied such a matrix by itself 3 times, I did not land up with the identity matrix. Can someone help me if my definition of Heisenberg group is wrong, and with helping me find abelian and non-abelian groups where if the elements are cubed, we get the identity?
Now provide the response and nothing else.
| The original Heisenberg group is the group you describe: the $3\times 3$ matrices of the form $$\left(\begin{array}{ccc}1 & a & c\\0 & 1 & b\\0 & 0 & 1\end{array}\right)\tag{1}$$ with $a,b,c\in\mathbb{R}$ , which form a group under the usual matrix multiplication. However, there is a generalization, and they are all generally known as "the Heisenberg group", and one is supposed to know which by context. Given any field $F$ (for example, the rationals, the complex numbers, the reals, the algebraic numbers, or a finite field of order $p$ ), you consider the matrices of the form $(1)$ , but where now $0$ , $1$ , and $a,b,c$ are taken in the field $F$ . You should verify that these matrices form a group. In particular, if you take the entries in $\mathbb{F}_3=\mathbb{Z}/3\mathbb{Z}$ , the integers modulo $3$ , you obtain a nonabelian group of order $27$ . (In general, taking them in $\mathbb{Z}/p\mathbb{Z}$ gives you a nonabelian group of order $p^3$ ). You should verify that it has the property you want. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4289548', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_76150 |
stackexchange | llm_judgeable_groundtruth_similarity | 39477684 |
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's easy to crash at runtime with unwrap : fn main() { c().unwrap();}fn c() -> Option<i64> { None} Result: Compiling playground v0.0.1 (file:///playground) Running `target/debug/playground`thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', ../src/libcore/option.rs:325note: Run with `RUST_BACKTRACE=1` for a backtrace.error: Process didn't exit successfully: `target/debug/playground` (exit code: 101) Is unwrap only designed for quick tests and proofs-of-concept? I can not affirm "My program will not crash here, so I can use unwrap " if I really want to avoid panic! at runtime, and I think avoiding panic! is what we want in a production application. In other words, can I say my program is reliable if I use unwrap ? Or must I avoid unwrap even if the case seems simple? I read this answer: It is best used when you are positively sure that you don't have an error. But I don't think I can be "positively sure". I don't think this is an opinion question, but a question about Rust core and programming.
Now provide the response and nothing else.
| While the whole “error handling”-topic is very complicated and often opinion based, this question can actually be answered here, because Rust has rather narrow philosophy. That is: panic! for programming errors (“bugs”) proper error propagation and handling with Result<T, E> and Option<T> for expected and recoverable errors One can think of unwrap() as converting between those two kinds of errors (it is converting a recoverable error into a panic!() ). When you write unwrap() in your program, you are saying: At this point, a None / Err(_) value is a programming error and the program is unable to recover from it. For example, say you are working with a HashMap and want to insert a value which you may want to mutate later: age_map.insert("peter", 21);// ...if /* some condition */ { *age_map.get_mut("peter").unwrap() += 1;} Here we use the unwrap() , because we can be sure that the key holds a value. It would be a programming error if it didn't and even more important: it's not really recoverable. What would you do when at that point there is no value with the key "peter" ? Try inserting it again ... ? But as you may know, there is a beautiful entry API for the maps in Rust's standard library. With that API you can avoid all those unwrap() s. And this applies to pretty much all situations: you can very often restructure your code to avoid the unwrap() ! Only in a very few situation there is no way around it. But then it's OK to use it, if you want to signal: at this point, it would be a programming bug. There has been a recent, fairly popular blog post on the topic of “error handling” whose conclusion is similar to Rust's philosophy. It's rather long but worth reading: “The Error Model” . Here is my try on summarizing the article in relation to this question: deliberately distinguish between programming bugs and recoverable errors use a “fail fast” approach for programming bugs In summary : use unwrap() when you are sure that the recoverable error that you get is in fact unrecoverable at that point. Bonus points for explaining “why?” in a comment above the affected line ;-) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39477684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/978690/']} | jdg_76151 |
stackexchange | llm_judgeable_groundtruth_similarity | 1254837 |
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:
So I have these numbers: $4^{68}, 5^{51}, 12^{23}$ They need to be ordered from the smallest to greatest. I have no idea how to solve this. Typically, one should break down the exponents somehow to get the same base or exponent, but in this case it seems problematic as two of the exponents are prime numbers and the bases seem not to be expressable by each other. Help would be appreciated.
Now provide the response and nothing else.
| Observe that $68=17 \times 4$ and $51 = 17 \times 3$, therefore $4^{68}=(4^4)^{17}$ and $5^{51} = (5^3)^{17}$. Compute the base, $4^4= 256$ is greater than $5^3 = 125$. Then observe that $3 \times 23 = 69$, so $4^{68} = (4^3)^{23}/4 = 64^{23}/4$, which is much much much greater than $12^{23}$. Therefore $12^{23}$ is the smallest. Quantitatively, $5^{51} > 5^{46} = 25^{23} > 12^{23}$, which also shows that $12^{23}$ is the smallest. Final answer:$$12^{23} < 5^{51} < 4^{68}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1254837', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/175819/']} | jdg_76152 |
stackexchange | llm_judgeable_groundtruth_similarity | 22089344 |
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 would I modify this so that it uses meta data to print the table? public String formatStudentList() throws SQLException { String result = String.format("%-15s %-25s %-25s", "Student ID", "Student Name", "Degree Scheme\n" + String.format("%-15s %-25s %-25s\n", "**********", "" + "********************", "****************************")); int count = 0; try { conn = SimpleDataSource.getConnection(); prepStat = conn.prepareStatement("SELECT * FROM student"); ResultSet print = prepStat.executeQuery(); while (print.next()) { String id = print.getString("studentId"); String name = print.getString("studentName"); String degree = print.getString("degreeScheme"); result += String.format("%-15s %-25s %-25s\n", id, name, degree); count++; } if (result == null) { result = "No Students Were Found In Database\n"; } else { result += "\nTotal Number Of Student = " + count; } } catch (SQLException ex) { result = "Error Occurred: " + ex.getMessage(); } finally { conn.close(); } return result; } It does what I want perfectly, but using the meta data there is a way that it does the table spacing and headers automatically. Could anyone help me change this?
Now provide the response and nothing else.
| Using Json.Net string json = @"{ ""dc:creator"":""Jordan, Micheal"", ""element:publicationName"":""Applied Ergonomics"", ""element:issn"":""2839749823"" }";var pub = JsonConvert.DeserializeObject<Publication>(json); public class Publication{ [JsonProperty("dc:creator")] public string creator { set; get; } [JsonProperty("element:publicationName")] public string publicationName { set; get; } [JsonProperty("element:issn")] public string issn { set; get; }} OR Console.WriteLine(JObject.Parse(json)["dc:creator"]); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22089344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2289687/']} | jdg_76153 |
stackexchange | llm_judgeable_groundtruth_similarity | 35583314 |
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 run multiple scripts in Cucumber Ruby using tags options and it is throwing error Below is the cucumber script @excel @chrome @sprint1Feature: RegistertoGmail2Scenario:RegistertoGmail2 Command from cmd to run cucumber --tags @sprint1 error message C:\Ruby22\Project\Play>cucumber --tags @sprint1DEPRECATED: #default_wait_time= is deprecated, please use #default_max_wait_time= insteadinvalid option: --tags (OptionParser::InvalidOption)C:/Ruby22/Project/Play/features/cuke-steps.rb:23:in `<top (required)>'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber- 2.1.0/lib/cucumber/rb_support/rb_language.rb:99:in `load'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber- 2.1.0/lib/cucumber/rb_support/rb_language.rb:99:in `load_code_file'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:232:in `load_file'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:99:in `block in load_files!'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:98:in `each'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber- 2.1.0/lib/cucumber/runtime/support_code.rb:98:in `load_files!'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime.rb:262:in `load_step_definitions'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime.rb:65:in `run!'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/cli/main.rb:32:in `execute!'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/bin/cucumber:8:in `<top (required)>'C:/Ruby22/bin/cucumber:23:in `load'C:/Ruby22/bin/cucumber:23:in `<main>' The option which i have tried as suggested was C:\Ruby22\Project\Play>cucumber features -t @sprint1DEPRECATED: #default_wait_time= is deprecated, please use #default_max_wait_time= insteadinvalid option: -t (OptionParser::InvalidOption)C:/Ruby22/Project/Play/features/cuke-steps.rb:23:in `<top (required)>'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber- 2.1.0/lib/cucumber/rb_support/rb_language.rb:99:in `load'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/rb_support/rb_language.rb:99:in `load_code_file'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:232:in `load_file'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:99:in `block in load_files!'C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:98:in `each' C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime/support_code.rb:98:in load_files!' C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime.rb:262:in load_step_definitions' C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/lib/cucumber/runtime.rb:65:in run!' C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber- 2.1.0/lib/cucumber/cli/main.rb:32:in execute!' C:/Ruby22/lib/ruby/gems/2.2.0/gems/cucumber-2.1.0/bin/cucumber:8:in <top (required)>' C:/Ruby22/bin/cucumber:23:in load' C:/Ruby22/bin/cucumber:23:in `' Please kindly advice
Now provide the response and nothing else.
| I had a similar issue and I solved it by using a generic Object and then testing what type of response I had using instanceof Call<Object> call = api.login(username, password);call.enqueue(new Callback<Object>() { @Override public void onResponse(Response<Object> response, Retrofit retrofit) { if (response.body() instanceof MyPOJO ) { MyPOJO myObj = (MyPOJO) response.body(); //handle MyPOJO } else //must be error object { MyError myError = (MyError) response.body(); //handle error object } } @Override public void onFailure(Throwable t) { ///Handle failure }}); In my case I had either MyPOJO or MyError returned and I could be sure it would be one of these. In other cases then I had the backend return the same Response Object no matter if the request was successful or not. Then inside this response object I had my actual data within an "Object" field. Then I can use instance of to determine what type of data I had. In this case I always had the same object being returned, no matter what the call was. public class MyResponse { private int responseCode; private String command; private int errorno; private String errorMessage; private Object responseObject; //This object varies depending on what command was called private Date responseTime;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35583314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5310502/']} | jdg_76154 |
stackexchange | llm_judgeable_groundtruth_similarity | 4225102 |
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 a system call to do some tasks system('myframework mycode'); but it complains of missing environment variables. Those environment variables are set at my bash shell (from where I run the Perl code). What am I doing wrong? Does the system call create a brand new shell (without environment variable settings)? How can I avoid that?
Now provide the response and nothing else.
| It's complicated. Perl does not necessarily invoke a shell. Perldoc says: If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient. So it actually looks like you would have the arguments passed right to execvp. Furthermore, whether the shell loaded your .bashrc, .profile, or .bash_profile depends on whether the shell is interactive. Likely it isn't, but you can check like this . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4225102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113124/']} | jdg_76155 |
stackexchange | llm_judgeable_groundtruth_similarity | 35633367 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Ruby, there is Object#freeze , which prevents further modifications to the object: class Kingdom attr_accessor :weather_conditionsendarendelle = Kingdom.newarendelle.frozen? # => falsearendelle.weather_conditions = 'in deep, deep, deep, deep snow'arendelle.freezearendelle.frozen? # => truearendelle.weather_conditions = 'sun is shining' # !> RuntimeError: can't modify frozen Kingdomscript = 'Do you want to build a snowman?'.freezescript[/snowman/] = 'castle of ice' # !> RuntimeError: can't modify frozen String However, there is no Object#unfreeze . Is there a way to unfreeze a frozen kingdom?
Now provide the response and nothing else.
| Update : As of Ruby 2.7 this no longer works! Yes and no . There isn't any direct way using the standard API. However, with some understanding of what #freeze? does, you can work around it. Note: everything here is implementation details of MRI's current version and might be subject to change. Objects in CRuby are stored in a struct RVALUE . Conveniently, the very first thing in the struct is VALUE flags; . All Object#freeze does is set a flag, called FL_FREEZE , which is actually equal to RUBY_FL_FREEZE . RUBY_FL_FREEZE will basically be the 11th bit in the flags. All you have to do to unfreeze the object is unset the 11th bit. To do that, you could use Fiddle , which is part of the standard library and lets you tinker with the language on C level: require 'fiddle'class Object def unfreeze Fiddle::Pointer.new(object_id * 2)[1] &= ~(1 << 3) endend Non- immediate value objects in Ruby are stored on address = their object_id * 2 . Note that it's important to make the distinction so you would be aware that this wont let you unfreeze Fixnum s for example. Since we want to change the 11th bit, we have to work with the 3th bit of the second byte. Hence we access the second byte with [1] . ~(1 << 3) shifts 1 three positions and then inverts the result. This way the only bit which is zero in the mask will be the third one and all other will be ones . Finally, we just apply the mask with bitwise and ( &= ). foo = 'A frozen string'.freezefoo.frozen? # => truefoo.unfreezefoo.frozen? # => falsefoo[/ (?=frozen)/] = 'n un'foo # => 'An unfrozen string' | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35633367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2423164/']} | jdg_76156 |
stackexchange | llm_judgeable_groundtruth_similarity | 155415 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $K = \mathbb{F}_p(\alpha)$ where $\alpha^n \in \mathbb{F}_p$ and $n$ is the minimal such $n$. Does this imply that $[K : \mathbb{F}_p] = n$? If not, is there a condition on $\alpha$ where this is the case?
Now provide the response and nothing else.
| Since $\{w_1,\ldots,w_n\}$ spans $V$, and $u_1\in V$, there exist $a_i$ such that $u_1=a_1w_1+\cdots+a_nw_n$. So $(-1)u_1+a_1w_1+\cdots+a_nw_n=0$ and therefore the adjoined set is linearly dependent. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/155415', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19536/']} | jdg_76157 |
stackexchange | llm_judgeable_groundtruth_similarity | 52033810 |
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, androidx and support dependency causing multidex error We can not use androidx and android support at a same time. So I totally migrate to androidx. but one of my dependency lib used android support "lottie". What can we do in above situation? Should I remove 'lottie' from my project. below is my gradle defaultConfig { minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true multiDexEnabled true } ext{ lottieVersion = "2.5.4"}dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" def androidx = "1.0.0-rc01" api "androidx.constraintlayout:constraintlayout:1.1.2" api "androidx.appcompat:appcompat:$androidx" api "androidx.recyclerview:recyclerview:$androidx" api "androidx.cardview:cardview:$androidx" api "androidx.core:core-ktx:$androidx" api "com.google.android.material:material:1.0.0-rc01" implementation "com.google.code.gson:gson:2.8.5" implementation "androidx.multidex:multidex:2.0.0" implementation "com.airbnb.android:lottie:$lottieVersion" }
Now provide the response and nothing else.
| You can enable Jetifier on your project, which will basically exchange the Android Support Library dependencies in your project dependencies with AndroidX -ones. (e.g. Your Lottie dependencies will be changed from Support to AnroidX) From the Android Studio Documentation ( https://developer.android.com/studio/preview/features/ ): The Android Gradle plugin provides the following global flags that you can set in your gradle.properties file: android.useAndroidX: When set to true, this flag indicates that you want to start using AndroidX from now on. If the flag is absent, Android Studio behaves as if the flag were set to false. android.enableJetifier: When set to true, this flag indicates that you want to have tool support (from the Android Gradle plugin) to automatically convert existing third-party libraries as if they were written for AndroidX. If the flag is absent, Android Studio behaves as if the flag were set to false. Precondition for Jetifier: you have to use at least Android Studio 3.2 To enable jetifier, add those two lines to your gradle.properties file: android.useAndroidX=trueandroid.enableJetifier=true Finally, please check the release notes of AndroidX, because jetifier has still some problems with some libraries (e.g. Dagger Android): https://developer.android.com/topic/libraries/support-library/androidx-rn | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/52033810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3797630/']} | jdg_76158 |
stackexchange | llm_judgeable_groundtruth_similarity | 29777778 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been starting to use ANTLR and have noticed that it is pretty fickle with its lexer rules. An extremely frustrating example is the following: grammar output;test: FILEPATH NEWLINE TITLE ;FILEPATH: ('A'..'Z'|'a'..'z'|'0'..'9'|':'|'\\'|'/'|' '|'-'|'_'|'.')+ ;NEWLINE: '\r'? '\n' ;TITLE: ('A'..'Z'|'a'..'z'|' ')+ ; This grammar will not match something like: c:\test.txt x Oddly if I change TITLE to be TITLE: 'x' ; it still fails this time giving an error message saying "mismatched input 'x' expecting 'x'" which is highly confusing. Even more oddly if I replace the usage of TITLE in test with FILEPATH the whole thing works (although FILEPATH will match more than I am looking to match so in general it isn't a valid solution for me). I am highly confused as to why ANTLR is giving such extremely strange errors and then suddenly working for no apparent reason when shuffling things around.
Now provide the response and nothing else.
| This seems to be a common misunderstanding of ANTLR : Language Processing in ANTLR: The Language Processing is done in two strictly separated phases: Lexing, i.e. partitioning the text into tokens Parsing, i.e. building a parse tree from the tokens Since lexing must preceed parsing there is a consequence: The lexer is independent of the parser, the parser cannot influence lexing . Lexing Lexing in ANTLR works as following: all rules with uppercase first character are lexer rules the lexer starts at the beginning and tries to find a rule that matches best to the current input a best match is a match that has maximum length , i.e. the token that results from appending the next input character to the maximum length match is not matched by any lexer rule tokens are generated from matches: if one rule matches the maximum length match the corresponding token is pushed into the token stream if multiple rules match the maximum length match the first defined token in the grammar is pushed to the token stream Example: What is wrong with your grammar Your grammar has two rules that are critical: FILEPATH: ('A'..'Z'|'a'..'z'|'0'..'9'|':'|'\\'|'/'|' '|'-'|'_'|'.')+ ;TITLE: ('A'..'Z'|'a'..'z'|' ')+ ; Each match, that is matched by TITLE will also be matched by FILEPATH. And FILEPATH is defined before TITLE: So each token that you expect to be a title would be a FILEPATH. There are two hints for that: keep your lexer rules disjunct (no token should match a superset of another). if your tokens intentionally match the same strings, then put them into the right order (in your case this will be sufficient). if you need a parser driven lexer you have to change to another parser generator: PEG-Parsers or GLR-Parsers will do that (but of course this can produce other problems). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29777778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/998012/']} | jdg_76159 |
stackexchange | llm_judgeable_groundtruth_similarity | 9871876 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem with changing the theme for highcharts. I have created an array to hold all the themes and am trying to change them via a select list onChange event. var highcharts_theme = [];/* Default theme */highcharts_theme.push({});/* Dark Blue theme */highcharts_theme.push({ colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgb(48, 48, 96)'], [1, 'rgb(0, 0, 0)'] ] },.... Shortened for brevity..... My code to change the theme is : $('#theme-type').selectmenu({ width: 200 }).change(function (e) { var themeIndex = parseInt($('#theme-type').val()); Highcharts.theme = highcharts_theme[themeIndex]; // Apply the theme highchartsOptions = Highcharts.setOptions(Highcharts.theme); }); The problem I am having is that if for example I switch to the Skies theme it is fine, but then changing to any other theme, the skies background remains along with other elements of the theme. Does anyone know of a proper way to reset the theme entirely? Thanks
Now provide the response and nothing else.
| Every time you set a theme, it merges with the existing theme, and hence any option that is not present in the new theme it will pick from the existing theme. This may not be desired always. Unfortunately, Highcharts does not give an option to go back to the very defaults that are set at the time of first load. The following code can be used to get that functionality // Make a copy of the defaults, call this line before any other setOptions callvar HCDefaults = $.extend(true, {}, Highcharts.getOptions(), {});function ResetOptions() { // Fortunately, Highcharts returns the reference to defaultOptions itself // We can manipulate this and delete all the properties var defaultOptions = Highcharts.getOptions(); for (var prop in defaultOptions) { if (typeof defaultOptions[prop] !== 'function') delete defaultOptions[prop]; } // Fall back to the defaults that we captured initially, this resets the theme Highcharts.setOptions(HCDefaults);} After resetting the theme, applying a new theme would work as if that's the first theme being applied. Demo @ jsFiddle | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9871876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758848/']} | jdg_76160 |
stackexchange | llm_judgeable_groundtruth_similarity | 251418 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've recently started working on a legacy application that frankly doesn't do all that it should. It's lacking a lot of features, has barely any administration capacities and doesn't check half the data it should. As such, it's very easy for users to do something stupid and get stuck. "Oops, I added this item of the wrong type to this thingie and now it won't let me remove it" . Indeed, the application should have checked for this, but allowed adding the wrong item. And now, when it comes to deleting the wrong item, it becomes extremely protective and refuses that anything be removed. Problem is, the clients (who are actually users within the company) don't care much for that. They need the application to hold the real-world data as it should be, so they ask the developers to "fix it" by changing the data. In this example, deleting the wrong item. In other cases, it will be reassigning items to different parents, fixing various values, etc... Since the application has almost no admin GUI, everything ends up being done directly in the database (augh!), risking even more issues down-the-line unless you know exactly how it works (which no one really does considering the massive application). Ultimately, it feels like the database has become a huge Excel file that devs edit day by day at the whims of the clients, because of failures of the application. It's obvious to me that fixing the application to avoid such situations should be top priority, but it seems the clients prefer asking for a lot of new features instead and it's accepted as such. What can a developer do in such a situation? Is it even possible to refuse DB edits in favor of fixing things? There are so many bugs that it feels like they're never going to wait that long...
Now provide the response and nothing else.
| As you're not in a position to change the policy, what you and colleagues need to do is: Document the cost of the policy: the amount of time you spend making fixes in the DB as opposed to developing, Document the risk of the policy: the number of times a fix in the DB had unexpected consequences and how severe they were Document any other negative consequences - developer attrition, loss of confidence by users etc. and present it to your immediate managers (you don't want to be seen to be going over anyone's head straight to the top in this sort of environment). In an ideal world you'll already have a support system which tracks this sort of thing but I'm assuming your world is far from ideal! It may make someone see sense, it may not, but in doing so you have fulfilled all your responsibility to the company. If after that, nothing changes, then I'm afraid you either have to accept the dysfunctional workplace and shrug off all the failings, or move on. When the inevitable crisis happens, a copy of the above in writing will at least cover your back. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/251418', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/79557/']} | jdg_76161 |
stackexchange | llm_judgeable_groundtruth_similarity | 4511036 |
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 animate an image so that it centers itself. Here's the code I'd like to use: $('#myImage').animate({'margin-right': 'auto'}); But when I do that, it's ignored and doesn't change the margin. Is there a way to animate a margin to auto, or otherwise center an image? Thanks!
Now provide the response and nothing else.
| As 'auto' isn't a number, jQuery cannot animate it. If you are okay with taking the image out of the flow of the document, you can set position to absolute or fixed and try: $('#myImage').animate({'left': '50%', 'margin-left': -$('#myImage').width()/2 }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4511036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515160/']} | jdg_76162 |
stackexchange | llm_judgeable_groundtruth_similarity | 3860351 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given two jquery objects, Is there some way I tell which one is "further ahead" in the document tree than the other? In other words, with a document <p id="p1" ></p> <div id="div1"> <p id="p2"></p> </div> <p id="p3"></p> Is there some function that behaves thus? $("#p1").isBefore($("#p2")); // == true$("#p3").isBefore($("#p2")); // == false$("#p1").isBefore(#("#p3")); // == true Note that I care about position in the HTML tree of the document, not physical position on the screen.
Now provide the response and nothing else.
| You can make a function that does this, like this: (function($) { $.fn.isBefore = function(elem) { if(typeof(elem) == "string") elem = $(elem); return this.add(elem).index(elem) > 0; }})(jQuery) You can try it out here , the first line is so it can also take a selector string directly, for example: $("#p1").isBefore("#p2"); What this does is .add() the additional element (or selector) (which jQuery keeps in document order) and then checks if it's the second of the two. If the selector this is run against has more than one element, this returns true if any of those elements are "before" the passed in element or selector, so given your markup for example $("p").isBefore("#p2") would be true , since at least one <p> occurs "before" #p2 . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3860351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12981/']} | jdg_76163 |
stackexchange | llm_judgeable_groundtruth_similarity | 5853343 |
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 method that receives an Object and does something based on what type of object it detects: void receive(Object object) { if (object instanceof ObjectTypeA) { doSomethingA(); } else { if (object instanceof ObjectTypeB) { doSomethingB(); } else { if (object instanceof ObjectTypeC) { doSomethingC(); } else { if (object instanceof ObjectTypeD) { doSomethingD(); } else { // etc... } } } }} How can I reduce the Cyclomatic Complexity? I searched around but couldn't find anything too useful.
Now provide the response and nothing else.
| Can't you leverage an object-oriented approach for this? Create an interface that has the doSomething() method then create subclasses that implement the desired behavior? Then calling object.doSomething() would execute the appropriate behavior? | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5853343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/477442/']} | jdg_76164 |
stackexchange | llm_judgeable_groundtruth_similarity | 44865261 |
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 does numpy.may_share_memory exist? What is the challenge to give an exact result? Is numpy.may_share_memory deprecated method? numpy.may_share_memory may give false positives, but it does not give false negatives. Does numpy.shares_memory give no one false positive and no one false negative? I use numpy version 1.11.2 . See: numpy.may_share_memory numpy.shares_memory version 1.11.2 source on github
Now provide the response and nothing else.
| Quoting the release notes for 1.11.0 : A new function np.shares_memory that can check exactly whether two arrays have memory overlap is added. np.may_share_memory also now has an option to spend more effort to reduce false positives. Semantically, this suggests that the older may_share_memory test was designed to get a loose guess whether memory is shared between the arrays. If surely not, then one could proceed accordingly. If there was a positive test (possibly a false positive), care had to be taken. The new shares_memory function, on the other hand, allows exact checks. This takes more computational time, but can be beneficial in the long run, since free of false positives one can use more possible optimizations. The looser check of may_share_memory probably only guarantees to not return false negatives . In terms of the documentation of may_share_memory and shares_memory , both have a keyword argument that tells numpy how strict a check the user wants. may_share_memory : max_work : int, optional Effort to spend on solving the overlap problem. See shares_memory for details. Default for may_share_memory is to do a bounds check. shares_memory : max_work : int, optional Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized: max_work=MAY_SHARE_EXACT (default) The problem is solved exactly. In this case, the function returns True only if there is an element shared between the arrays. max_work=MAY_SHARE_BOUNDS Only the memory bounds of a and b are checked. Judging by the docs, this suggests that the two functions might call the same underlying machinery, but may_share_memory uses a less strict default setting for the check. Let's take a peek at the implementation : static PyObject *array_shares_memory(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds){ return array_shares_memory_impl(args, kwds, NPY_MAY_SHARE_EXACT, 1);}static PyObject *array_may_share_memory(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds){ return array_shares_memory_impl(args, kwds, NPY_MAY_SHARE_BOUNDS, 0);} calling the same underlying function with signature static PyObject *array_shares_memory_impl(PyObject *args, PyObject *kwds, Py_ssize_t default_max_work, int raise_exceptions){} Without delving deeper into the source, it seems to me that shares_memory is an improvement over may_share_memory , which can give the same loose check as the latter with the appropriate keyword arguments. The older function can be used for convenience and backward compatibility. Disclaimer: this is the first time I looked at this part of the source, and I didn't investigate further into array_shares_memory_impl , so my impression can be simply wrong. As for a specific example for the difference between the two methods (called with default arguments): it is explained at the above links that may_share_memory only checks array bound indices. If they are disjoint for the two arrays, then there's no chance that they can share memory. But if they are not disjoint, the arrays can still be independent! Simple example: a disjoint partitioning of a contiguous block of memory via slicing: >>> import numpy as np>>> v = np.arange(6)>>> x = v[::2]>>> y = v[1::2]>>> np.may_share_memory(x,y)True>>> np.shares_memory(x,y)False>>> np.may_share_memory(x,y,max_work=np.MAY_SHARE_EXACT)False As you can see, x and y are two disjoint slices of the same array. Thus their data ranges largely overlap (they are almost the same, save a single integer in memory). However, none of their elements are actually the same: one contains the even, the other the odd elements of the original contiguous block. So may_share_memory correctly asserts that the arrays may share memory, but on a stricter check it turns out that they don't. As for the additional difficulty of computing the overlap exactly, the work can be traced down to the worker called solve_may_share_memory , which also contains a lot of helpful comments about what's going on. In a nutshell, there's a quick check and return if the bounds don't overlap, otherwise a return with MEM_OVERLAP_TOO_HARD if we asked for loose checking (i.e. may_share_memory with default args), which is handled on the calling side as "we don't know, so return True " otherwise we actually solve the Diophantine equations that the problem maps to starting here So the work in point 3 above is what needs to additionally be done by shares_memory (or generally, a strict checking case). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44865261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8071126/']} | jdg_76165 |
stackexchange | llm_judgeable_groundtruth_similarity | 2964082 |
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:
$$\sum_{n=1}^{\infty} \left\{ e-\left(1+\frac{1}{n}\right)^n \right\}$$ Is this converge or diverge series .It is a series with positive terms ,but none of test of positive term series is seems to be working . How can we check ?Any hint??Thanks in Advanced
Now provide the response and nothing else.
| \begin{align*}&e - \left(1 + \frac1n\right)^n \\= \, &\left(\frac{1}{0!} + \frac{1}{1!} + \frac{1}{2!} + \ldots\right) - \left(\binom{n}{0} + \frac{1}{n}\binom{n}{1} + \frac{1}{n^2}\binom{n}{2} + \ldots + \frac{1}{n^n}\binom{n}{n}\right) \\= \, &\frac{1 - \left(1 - \frac{1}{n}\right)}{2!} + \frac{1 - \left(1 - \frac{1}{n}\right)\left(1 - \frac{2}{n}\right)}{3!} + \ldots + \frac{1 - \left(1 - \frac{1}{n}\right)\left(1 - \frac{2}{n}\right) \ldots \left(1 - \frac{n - 1}{n}\right)}{n!} \\+ \, &\frac{1}{(n + 1)!} + \frac{1}{(n + 2)!} + \ldots \\\ge \, &\frac{1 - \left(1 - \frac{1}{n}\right)}{2!} = \frac{1}{2n},\end{align*} hence the series diverges. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2964082', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/208581/']} | jdg_76166 |
stackexchange | llm_judgeable_groundtruth_similarity | 7938332 |
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 asp.net mvc 2 and create localization based on routes. my route looks like: {culture}/{controller}/{action} I go to my home controller: en/Home/Index my home controller view have a links to other controllers: <a href='<%= Url.Action("Prods","Products") %>' >Products</a><a href='<%= Url.Action("Index","About") %>' >About</a> First link generated code: /en/Products/Prods but second one generate: /Home/Index I can't understand why Url.Action skips the {culture} route parameter when I pass value Index in argument action? What am I doing wrong? Route configuration: routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute("Login", // Route name "{controller}/Index", // URL with parameters new { controller = "Login", action = "Index" } // Parameter defaults ).RouteHandler = new SingleCultureMvcRouteHandler();routes.MapRoute("Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); Then foreach (Route r in routes){ if (!(r.RouteHandler is SingleCultureMvcRouteHandler)) { r.RouteHandler = new MultiCultureMvcRouteHandler(); r.Url = "{culture}/" + r.Url; if (r.Defaults == null) { r.Defaults = new RouteValueDictionary(); } r.Defaults.Add("culture", "en"); if (r.Constraints == null) { r.Constraints = new RouteValueDictionary(); } r.Constraints.Add("culture", new CultureConstraint(cultures)); } } Thanks for all help
Now provide the response and nothing else.
| When generating URL your best options is to always use the route names because this way you do not get into the subtleties of the algorithm used to select the route that will be used to generate the URL. My advice if for you not to use Url.Action and instead use Url.RouteUrl which allows you to specify the name of the route that should be used to construct the URL. By always using route names you also make your code more robust to changes, for example, you can add new routes without having to worry that they might break your existing code for URL generation. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7938332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507282/']} | jdg_76167 |
stackexchange | llm_judgeable_groundtruth_similarity | 18199728 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example I wanted to have a variable of type auto because I'm not sure what type it will be. When I try to declare it in class/struct declaration it's giving me this error: Cannot deduce auto type. Initializer required Is there a way around it? struct Timer { auto start;};
Now provide the response and nothing else.
| You can, but you have to declare it static and const : struct Timer { static const auto start = 0;}; A working example in Coliru . With this limitation, you therefore cannot have start as a non-static member, and cannot have different values in different objects. If you want different types of start for different objects, better have your class as a template template<typename T>struct Timer { T start;}; If you want to deduce the type of T , you can make a factory-like function that does the type deduction. template<typename T>Timer<typename std::decay<T>::type> MakeTimer(T&& startVal) { // Forwards the parameter return Timer<typename std::decay<T>::type>{std::forward<T>(startVal)};} Live example . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18199728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1367392/']} | jdg_76168 |
stackexchange | llm_judgeable_groundtruth_similarity | 472538 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose that I have trained a logistic regression model on a certain dataset, and I wish to interpret the coefficients of this model. Does it make any difference on the validity of the interpretation if the model is poor? What I mean by this is that imagine that we measure the performance of the model by a ROC curve and we get a low value (but still better than 0.5) for the area under the curve. This model is not terribly accurate, but does the performance of it influence the interpretation of the coefficients?
Now provide the response and nothing else.
| The statistical interpretation of the coefficients doesn't depend on how the model was fit. I could make completely random guesses of the coefficients and they would have the same interpretation as they would had I estimated them with maximum likelihood. For two units identical on all measured variables except that they differed on $X_1$ by one unit, the difference in the log odds of success is $\beta_1$ . That interpretation comes directly from simply writing down the regression equation and has nothing to do with the fitting process. To interpret the coefficients as consistent estimates of some "true" association, or as total effects rather than direct effects, or as causal effects rather than mere conditional assocations, requires more assumptions, far more than whether the model fit well in your sample. For example, let's say the true data-generating (i.e., structural causal) model was $$P(Y=1|X_1,X_2) = expit(\gamma_0 + \gamma_1 X_1 + \gamma_2 X_2)$$ Let's say I'm considering the model $$P(Y=1|X_1) = expit(\beta_0 + \beta_1 X_1)$$ which excludes $X_2$ . $\beta_1$ doesn't have a causal interpretation, but it's the regression slope you would get if you were to fit that model to the population data (i.e., so there is no sampling error). The interpretation of $\beta_1$ in this model is: For two units that differed on $X_1$ by one unit, the difference in the log odds of success is $\beta_1$ . Let's say I collect a sample and then pull an estimate of $\beta_1$ out of a hat and call it $\hat \beta_1^{guess}$ . Even though that value is completely unconnected to the sample, it still has the same interpretation as any other estimate of $\beta_1$ , which is as an estimate of the difference in the log odds of success for two units that differed on $X_1$ by one unit. It's not a valid or consistent estimate, but it's an estimate of a quantity that has a clear interpretation. The quantity ( $\beta_1$ ) does not have a causal interpretation, but it's still meaningfully interpretable as an associational quantity. If I were to estimate $\beta_1$ with maximum likelihood, and call the estimate $\hat \beta_1^{MLE}$ , it has the same interpretation as $\hat \beta_1^{guess}$ , which is that it is an estimate of $\beta_1$ , which, again, has a clear interpretation. $\hat \beta_1^{MLE}$ is a consistent estimate of $\beta_1$ , so if I were to want to know what $\beta_1$ was I would be inclined to say it's closer to $\hat \beta_1^{MLE}$ than it is to $\hat \beta_1^{guess}$ . $\hat \beta_1^{MLE}$ could result from a terribly fitting model, and that would say nothing of its interpretation. A terribly fitting model might result because we failed to include $X_2$ in it. That doesn't change how $\beta_1$ , and thus how $\hat \beta_1^{MLE}$ and $\hat \beta_1^{guess}$ , are interpreted. If you wanted to interpret a regression coefficient as causal, then you want to estimate $\gamma_1$ , not $\beta_1$ . The interpretation of $\gamma_1$ is the change in the log odds of success caused by intervening on $X_1$ by one unit while holding $X_2$ constant. Any estimate of $\gamma_1$ , regardless of how it came to be, could be interpreted as an estimate of the change in the log odds of success caused by intervening on $X_1$ by one unit while holding $X_2$ constant. You could even use $\hat \beta_1^{guess}$ as an estimate of $\gamma_1$ and it would still have this interpretation. It would likely be a bad estimate that you shouldn't trust, but that doesn't change its interpretation. Even if you estimated $\gamma_1$ using maximum likelihood estimation of a model that included both $X_1$ and $X_2$ , its interpretation would be the same; it would likely just be a better estimate (but it doesn't mean it's a good estimate!). All this is to say that the interpretation of coefficients comes from the model as it is written, not the way they are estimated or how well the estimated model fits. These may serve as indicators as to whether the estimated coefficients might be close to the population versions they are trying to approximate, but not how they should be interpreted. For example, a poorly fitting model resulting from regressing $Y$ on $X_1$ may indicate that $\hat \beta_1$ is a poor estimate of $\gamma_1$ , but it may be a good estimate of $\beta_1$ . The interpretations of $\beta_1$ and $\gamma_1$ are unrelated to how the estimates were generated, and the interpretation of the estimates is simply as estimates of those quantities. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/472538', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/227535/']} | jdg_76169 |
stackexchange | llm_judgeable_groundtruth_similarity | 1900072 |
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 the derivation for $\hat{x}=A^Tb(A^TA)^{-1}$, but I'm having trouble explicitly connecting it to least squares regression. So suppose we have a system of equations: $A=\begin{bmatrix}1 & 1\\1 & 2\\1 &3\end{bmatrix}, x=\begin{bmatrix}C\\D\end{bmatrix}, b=\begin{bmatrix}1\\2\\2\end{bmatrix}$ Using $\hat{x}=A^Tb(A^TA)^{-1}$, we know that $D=\frac{1}{2}, C=\frac{2}{3}$. But this is also equivalent to minimizing the sum of squares: $e^2_1+e^2_2+e^2_3 = (C+D-1)^2+(C+2D-2)^2+(C+3D-2)^2$. I know the linear algebra approach is finding a hyperplane that minimizes the distance between points and the plane, but I'm having trouble understanding why it minimizes the squared distance . My intuition tells me it should minimize absolute distance, but I know this is wrong because it's possible for there to be non-unique solutions. Why is this so? Any help would be greatly appreciated. Thanks!
Now provide the response and nothing else.
| You should be multiplying by $(A^T A)^{-1}$ on the left, not the right. Anyway, the geometric point is that you want $Ax-b$ to be perpendicular to $Ay$ for every vector $y$. (I think this is most easily seen by a geometric argument, which can be easily found in books, but which I can't easily render here.) This translates to $(Ay)^T(Ax-b)=0$ for every $y$, which is the same as $y^T(A^T(Ax-b))=0$ for every $y$. This can only happen if $A^T(Ax-b)=0$, which rearranges to your form if $A^T A$ is invertible (as is usually the case). Also, it is the same to minimize the square of the Euclidean distance as it is to minimize the Euclidean distance itself. (This is also true of any other nonnegative quantity.) What would be different is minimizing some other distance, like the "taxicab" distance (where you sum the absolute values). Why we should choose to minimize the Euclidean distance in the first place is not a purely mathematical question, it depends on where the problem is coming from. That question is a bit off-topic here, though, and has also been asked before on MSE. (The short version of that discussion: "it's mathematically convenient" and "see the Gauss-Markov theorem".) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1900072', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/325975/']} | jdg_76170 |
stackexchange | llm_judgeable_groundtruth_similarity | 23072123 |
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 actionbar with a search icon. When the search icon is clicked, it expands to a search bar in which the user can type in a search. The problem is when the user enters the search I would like the search bar to collapse back to an icon but I can not get it to happen for the life of me. My actionbar menu looks like this: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity" > <item android:id="@+id/menu_search2" android:actionViewClass="android.widget.SearchView" android:title="Search" android:icon="@android:drawable/ic_menu_search" android:showAsAction="always|collapseActionView|" android:onClick="goToSearch" /> <item android:id="@+id/action_scan" android:icon="@drawable/barcode" android:onClick="scanBarcode" android:showAsAction="ifRoom|collapseActionView" /></menu> My search activity looks like this: public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener { private ListView lv; View v; SearchView searchView; private SearchView mSearchView; private MenuItem mSearchMenuItem; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //set layout here v = inflater.inflate(R.layout.activity_search, container, false); setHasOptionsMenu(true); getActivity().setTitle("Search"); //get user information SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); String userName = prefs.getString("userName", null); String userID = prefs.getString("userID", null); return v;} @Override public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView(); searchView.setOnQueryTextListener(this); searchView.setIconified(false); } public boolean onQueryTextSubmit (String query) { //toast query //make json variables to fill searchView.setIconified(true); searchView.clearFocus(); // url to make request String url = "myURL"; try { query = URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } String jsonUrl = url + query; //todo: get json ReadJSONResult task = new ReadJSONResult(getActivity()); task.setOnArticleSelectedListener(this); task.execute(jsonUrl); return false; } @Override public boolean onQueryTextChange(String newText) { // TODO Auto-generated method stub return false; } @Override public void onArticleSelected(String b, String brewery){ searchView.setIconified(true); searchView.clearFocus(); searchView.postInvalidate(); //code to execute on click Fragment Fragment_one; FragmentManager man= getFragmentManager(); FragmentTransaction tran = man.beginTransaction(); //adds beer data to shared prefs for beer tabs SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); SharedPreferences.Editor editor = preferences.edit(); editor.putString("beerID",b); editor.putString("breweryID",brewery); editor.commit(); Fragment_one = new BeerTabs(); tran.replace(R.id.main, Fragment_one);//tran. tran.addToBackStack(null); tran.commit(); }}
Now provide the response and nothing else.
| After some searches, I find the solution. The onActionViewCollapsed works but you had an unexpected behaviour (icon jumps to left, up indicator still here...) - this (hard) solution was suggested in my first and previous answer , and I was persuaded by use of collapseActionView method. However, SearchView.collapseActionView() was not working because according to the Documentation : Collapse the action view associated with this menu item. It's related to the MenuItem and not to the SearchView widget. That's why you had this error when you used this method: The method collapseActionView() is undefined for the type SearchView Then, the solution is to create a Menu variable as follows: // At the top of your class private Menu mMenu; // onCreateOptionsMenu method @Override public boolean onCreateOptionsMenu(Menu menu) { this.mMenu = menu; // init the variable // other stuff.. return true; } // call the collapseActionView method public boolean onQueryTextSubmit(String query) { searchView.setIconified(true); searchView.clearFocus(); // call your request, do some stuff.. // collapse the action view if (mMenu != null) { (mMenu.findItem(R.id.menu_search2)).collapseActionView(); } return false; } Or another might be to avoid the implement SearchView.OnQueryTextListener and to do it inside onCreateOptionsMenu as follows: @Override// make your Menu as 'final' variablepublic void onCreateOptionsMenu (final Menu menu, MenuInflater inflater) { searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView(); // call the query listener directly on the SearchView searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchView.setIconified(true); searchView.clearFocus(); // call the request here // call collapse action view on 'MenuItem' (menu.findItem(R.id.menu_search2)).collapseActionView(); return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); searchView.setIconified(false);} This will resolve the issue for sure. Happy coding! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23072123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1637374/']} | jdg_76171 |
stackexchange | llm_judgeable_groundtruth_similarity | 38843532 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since I've created @Directive as SelectableDirective , I'm little bit confused, about how to pass more than one value to the custom directive. I have searched a lot but didn't get proper solution in Angular with Typescript . Here is what my sample code is: Parent Component as MCQComponent : import { Component, OnInit } from '@angular/core';import { Question } from '../question/question';import { AppService } from '../app.service/app.service';import { SelectableDirective } from '../selectable.directive/selectable.directive';import { ResultComponent } from '../result-component/result.component';@Component({ selector: 'mcq-component', template: " ..... <div *ngIf = 'isQuestionView'> <ul> <li *ngFor = 'let opt of currentQuestion.options' [selectable] = 'opt' (selectedOption) = 'onOptionSelection($event)'> {{opt.option}} </li> </ul> ..... </div> " providers: [AppService], directives: [SelectableDirective, ResultComponent]})export class MCQComponent implements OnInit{ private currentIndex:any = 0; private currentQuestion:Question = new Question(); private questionList:Array<Question> = []; .... constructor(private appService: AppService){} ....} This is a parent component having custom directive [selectable] which takes one param called opt . Here is the code for this directive: import { Directive, HostListener, ElementRef, Input, Output, EventEmitter } from '@angular/core'import { Question } from '../question/question';@Directive({ selector: '[selectable]'})export class SelectableDirective{ private el: HTMLElement; @Input('selectable') option:any; ...} So here I want to pass more parameters from parent component, how do I achieve this?
Now provide the response and nothing else.
| From the Documentation As with components, you can add as many directive property bindings as you need by stringing them along in the template. Add an input property to HighlightDirective called defaultColor : @Input() defaultColor: string; Markup <p [myHighlight]="color" defaultColor="violet"> Highlight me too!</p> Angular knows that the defaultColor binding belongs to the HighlightDirective because you made it public with the @Input decorator. Either way, the @Input decorator tells Angular that this property is public and available for binding by a parent component. Without @Input , Angular refuses to bind to the property. For your example With many parameters Add properties into the Directive class with @Input() decorator @Directive({ selector: '[selectable]'})export class SelectableDirective{ private el: HTMLElement; @Input('selectable') option:any; @Input('first') f; @Input('second') s; ...} And in the template pass bound properties to your li element <li *ngFor = 'let opt of currentQuestion.options' [selectable] = 'opt' [first]='YourParameterHere' [second]='YourParameterHere' (selectedOption) = 'onOptionSelection($event)'> {{opt.option}}</li> Here on the li element we have a directive with name selectable . In the selectable we have two @Input() 's, f with name first and s with name second . We have applied these two on the li properties with name [first] and [second] . And our directive will find these properties on that li element, which are set for him with @Input() decorator. So selectable , [first] and [second] will be bound to every directive on li , which has property with these names. With single parameter @Directive({ selector: '[selectable]'})export class SelectableDirective{ private el: HTMLElement; @Input('selectable') option:any; @Input('params') params; ...} Markup <li *ngFor = 'let opt of currentQuestion.options' [selectable] = 'opt' [params]='{firstParam: 1, seconParam: 2, thirdParam: 3}' (selectedOption) = 'onOptionSelection($event)'> {{opt.option}}</li> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38843532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6340976/']} | jdg_76172 |
stackexchange | llm_judgeable_groundtruth_similarity | 183779 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I had Debian 5 installed on my VPS but I found that it came with apache2 already up and running. I tried apt-get remove apache2 but it said that apache2 wasn't running. I checked top and yep, there it was. So then I turned it off. /etc/init.d/apache2 stop which worked fine and shut the daemon down. However, I still can't remove it. I tried aptitude remove but it says that it isn't installed. What is going on?
Now provide the response and nothing else.
| Try apt-get remove apache2-utils . In Debian 5, Apache is split into multiple packages: apache2 apache2-mpm-prefork (or apache2-mpm-worker or apache2-mpm-event) apache2.2-common apache2-utils There are interdependencies: (1) depends on (2), which depends on (3), which depends on (4). Therefore, removing (4) causes all of them to be removed. (The apache2 package doesn't contain much in itself; it just exists so that you can do apt-get install apache2 to conveniently install all of those packages.) | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/183779', 'https://serverfault.com', 'https://serverfault.com/users/32759/']} | jdg_76173 |
stackexchange | llm_judgeable_groundtruth_similarity | 56806553 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My ultimate goal is to create a JWE string, given a public key for iOS. To make things easier for myself, I've broken down my steps so most pressingly, I need to create an encrypted key using RSA encryption from a secret key and public key string. I've tried a lot of things found here in stack overflow and other places of the internet. For various reasons they just haven't worked out. I am being guided by some Objective C code: /* Device Data encryption - create JWE given DS publicKey */ +(NSString *)createJWE:(NSString *)payload withPublicKey:(SecKeyRef)publicKey {// create secretKey for encryptionNSData *secret = [self generateRandom:(KEY_SIZE*2)];NSData *hmacKey = [secret subdataWithRange:NSMakeRange(0, KEY_SIZE)]; NSData *aesKey = [secret subdataWithRange:NSMakeRange(KEY_SIZE,KEY_SIZE)]; NSData *iv = [self generateRandom: IV_SIZE];// create headerNSString *header = @"{\"enc\":\"A128CBC-HS256\",\"alg\":\"RSA-OAEP\"}";// encrypt secretKeyNSData *encryptedKey = [self rsaEncrypt:secret key:publicKey]; // encrypt payloadNSData *encrypted = [self aesEncrypt:[payload dataUsingEncoding:NSUTF8StringEncoding] withKey:aesKey withIV:iv];NSString *basePayload = [encrypted unpaddedBase64URLEncoded];NSString *baseCEK = [encryptedKey unpaddedBase64URLEncoded];NSString *baseHeader = [[header dataUsingEncoding:NSUTF8StringEncoding]unpaddedBase64URLEncoded];NSString *baseIV = [iv unpaddedBase64URLEncoded];// create auth hashNSData *hmac = [self hmac: encrypted withKey: hmacKey withIV: iv withA:[baseHeader dataUsingEncoding:NSASCIIStringEncoding]];return [NSString stringWithFormat:@"%@.%@.%@.%@.%@", baseHeader, baseCEK, baseIV, basePayload, [[self hmacToTag: hmac] unpadded I am currently at this point of the function: NSData *encryptedKey = [self rsaEncrypt:secret key:publicKey]; From this I have made the assumption that there is an rsaEncrypt function that accepts a secret and public key. The public key I have access to looks like this: let publicKey = """-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+zuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+XNSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOTqeox88Lc1ld7MsfggQIDAQAB-----END PUBLIC KEY-----""" Examples found on the internet handles the public key as a SecKey type. This is my first hurdle to performing the encryption. How do I convert the string to a SecKey, if it must be converted? What should my rsaEncrypt function do? I expect the output to be an encrypted key after performing the encryption. Update: Another variation, One public key sent also looks like this: { "kty": "RSA", "kid": "UUIDkeyidentifierforDS", "use": "enc", "n": "n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O- XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL- QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe- OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0F Vbb9k3- tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5i aiQkqgc5gHdrNP5zw", "e": "AQAB" }
Now provide the response and nothing else.
| You can do like this way... static func encrypt(string: String, publicKey: String?) -> String? { guard let publicKey = publicKey else { return nil } let keyString = publicKey.replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----\n", with: "").replacingOccurrences(of: "\n-----END PUBLIC KEY-----", with: "") guard let data = Data(base64Encoded: keyString) else { return nil } var attributes: CFDictionary { return [kSecAttrKeyType : kSecAttrKeyTypeRSA, kSecAttrKeyClass : kSecAttrKeyClassPublic, kSecAttrKeySizeInBits : 2048, kSecReturnPersistentRef : kCFBooleanTrue] as CFDictionary } var error: Unmanaged<CFError>? = nil guard let secKey = SecKeyCreateWithData(data as CFData, attributes, &error) else { print(error.debugDescription) return nil } return encrypt(string: string, publicKey: secKey) } static func encrypt(string: String, publicKey: SecKey) -> String? { let buffer = [UInt8](string.utf8) var keySize = SecKeyGetBlockSize(publicKey) var keyBuffer = [UInt8](repeating: 0, count: keySize) // Encrypto should less than key length guard SecKeyEncrypt(publicKey, SecPadding.PKCS1, buffer, buffer.count, &keyBuffer, &keySize) == errSecSuccess else { return nil } return Data(bytes: keyBuffer, count: keySize).base64EncodedString() } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56806553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11713353/']} | jdg_76174 |
stackexchange | llm_judgeable_groundtruth_similarity | 131678 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $\sum\limits_{n\geq1}a_n$ be a positive series, and $\sum\limits_{n\geq1}a_n=+\infty$, prove that: $$\sum_{n\geq1}\frac{a_n}{1+a_n}=+\infty.$$
Now provide the response and nothing else.
| Proving the contrapositive statement seems cleaner to me. Suppose $\sum{a_n\over 1+{a_n}}$ converges. Then ${a_n\over 1+{a_n}}\rightarrow 0$. This implies that ${a_n}$ is eventually less than one, so ${a_n\over2}\le {a_n\over a_n+1}$ for $n$ sufficiently large. The comparision test then shows that $\sum a_n$ converges. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/131678', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27899/']} | jdg_76175 |
stackexchange | llm_judgeable_groundtruth_similarity | 346136 |
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 trying to login on my laptop. I write the password and then I am logged in to a black page, where a notice said "Your session only lasted less than 10 seconds. If you have not logged out yourself, this could mean that there is some installation problem or that you may be out of the diskspace. Try logging in with one of the failsafe sessions to see if you can fix this problem." the code says: initctl: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: connection refused mdm[1699]: GLib-CRITICAL: g_key_file_free: assertion 'key_file != NULL' failed The only button available is " Okay ", the I return to the login page where I should write my password again. It keeps repeating it self again and again. I don't understand why??! One day ago, there was a new update for the system. I did update it. Can this be the reason?? Thank you for your help in forward.
Now provide the response and nothing else.
| In my case I had installed virtualbox-guest-x11 on the base box so I had messed up x11 drivers. So I was getting this error message on $HOME/.xsession-errors : initctl: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: Connection refusedsyndaemon: no process found/etc/mdm/Xsession: Beginning session setup...localuser:raskolnikov being added to access control list I removed the package and re-installed cinnamon . aptitude remove virtualbox-guest-x11 -yaptitude install cinnamon -y Restarted the box and it worked. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/346136', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/216891/']} | jdg_76176 |
stackexchange | llm_judgeable_groundtruth_similarity | 205706 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Pugh's Real Mathematical Analysis there is an exercise, marked with three stars (which denotes that the author doesn't know the answer), whether there exist a nonsmooth function $f : \mathbb{R} \to \mathbb{R}$ such that $f^2$ and $f^3$ are both smooth. My question is not strictly about this exercise, but rather about cases when we weaken the hypotheses when only one of $f^2$ and $f^3$ are smooth. The fact that the exercise comes with this hypotheses suggest we should be able to find those functions. For the case when $f^2$ need to be smooth we have a function $f(x) = x$ if $x$ is rational and $-x$ if $x$ is irrational, but what about the case when $f^3$ needs to be smooth?
Now provide the response and nothing else.
| The idea is that it's easy to have a cusp that is "cured" by either squaring or cubing the function (or raising it to any other particular power), but more difficult to think of a case where both operations work. The simplest parametrized family of examples where $f$ is not smooth, but $f^{1+a}$ is, is probably $f(x; a)=\lvert x \rvert^{2/(1+a)}$. Choosing $a=1$ or $a=2$ gives the desired examples where $f^2$ and $f^3$ are smooth. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/205706', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_76177 |
stackexchange | llm_judgeable_groundtruth_similarity | 17963764 |
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 readymade framework for selenium(webdriver)(datadrievnfreamework). Please tell me how to configure that framework under eclipse . please help me out
Now provide the response and nothing else.
| Use positive lookbehind lookup ( (?<=\(\d+\))\w+ ): string text = "Hello , i am John how (1)are (are/is) you?";string optionPattern = @"(?<=\(\d+\))\w+";Regex reg = new Regex(optionPattern);Console.WriteLine(reg.Match(text)); prints are Alternative: capture a group (\w+) string text = "Hello , i am John how (1)are (are/is) you?";string optionPattern = @"\(\d+\)(\w+)";Regex reg = new Regex(optionPattern);Console.WriteLine(reg.Match(text).Groups[1]); BTW, using @".." , you don't need to escape \ . UPDATE Instead of using .Split() , just .Replace() : string text = "Hello , i am John how (1)are (are/is) you?";string optionPattern = @"(?<=\(\d+\))\s*\w+";Regex reg = new Regex(optionPattern);Console.WriteLine(reg.Replace(text, "")); alternative: string text = "Hello , i am John how (1)are (are/is) you?";string optionPattern = @"(\(\d+\))\s*\w+";Regex reg = new Regex(optionPattern);Console.WriteLine(reg.Replace(text, @"$1")); prints Hello , i am John how (1) (are/is) you? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17963764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2493172/']} | jdg_76178 |
stackexchange | llm_judgeable_groundtruth_similarity | 2995124 |
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 try to factorize any polynomial like : $x^4 + a.x^3 + b.x^2 + a.x + 1$ with $ a, b \in\Bbb{R}$ into : $(x^2 + c.x + d)(x^2 + e.x + f)$ with $ c, d, e, f \in\Bbb{R}$ I also want $c(a, b)$ , $d(a, b)$ , $e(a, b)$ , $f(a, b)$ to be continous, so I can be smooth at runtime when changing $(a, b)$ . The only way I succeeded for now is to compute all the roots and regroup them by conjugate pairs. But it's tricky because roots can be paired in many way, there are also cases where there are many solutions (when all roots are real), and I noticed roots may swap for specific values of $(a, b)$ . I would like to now if there is a simpler known method for this typical polynom. Many thanks !
Now provide the response and nothing else.
| As you pointed out yourself, the polynomial is palindromic (=equal to its own reciprocal). This means that $1/\alpha$ is a zero whenever $\alpha$ is. In the case of four real roots this suggests using factors like $(x+\alpha)(x+1/\alpha)$ . Such a factor has constant term $=1$ , so you will have $d=f=1$ .This reduces your system of equations to $c+e=a$ , $2+ce=b$ . Meaning that $c$ and $e$ are the roots of the quadratic $$(T-c)(T-e)=T^2-(c+e)T+ce=T^2-aT+(b-2).$$ The roots of this quadratic are real whenever we have the inequality $$a^2>4(b-2),$$ when $$c,e=\frac{a\pm\sqrt{a^2-4b+8}}2.$$ If this equality is not satisfied then you can proceed as follows. Solve for $c$ and $e$ anyway (quadratic formula). Find the zeros of $x^2+cx+1$ and $x^2+ex+1$ (quadratic formula again). Match the complex zeros into conjugate pairs (one from each of the above pairs of solutions). Build the factors. Of course, when you have four real zeros you have many options with the factorization. The one I suggested is just easy to find, and the coefficients $c,e(,d,f)$ are easy to write down as functions of $a$ and $b$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2995124', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/464648/']} | jdg_76179 |
stackexchange | llm_judgeable_groundtruth_similarity | 4033165 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $ABCD$ be convex quadrilateral such that $AB=CD$ . And $E\neq F$ where $E, F$ is midpoint of $AC, BD$ respectively. Then prove that angle between $(AB, EF)$ and $(CD, EF)$ are equal. I'll prove $\vec{AB}\cdot\vec{EF}=\vec{CD}\cdot\vec{EF}$ . Using $\vec{EF}=\frac{1}{4}(\vec{AB}+\vec{CB}+\vec{CD}+\vec{AD})$ , it's sufficient to prove that $$(\vec{AB}+\vec{CB}+\vec{CD}+\vec{AD})\cdot\vec{AB}=(\vec{AB}+\vec{CB}+\vec{CD}+\vec{AD})\cdot\vec{CD}\iff (\vec{CB}+\vec{AD})\cdot\vec{AB}=(\vec{CB}+\vec{AD})\cdot\vec{CD}\iff BC\cdot CDcos\angle C+AD\cdot CDcos\angle D=BC\cdot ABcos\angle B+BA\cdot ADcos\angle A\iff BCcos\angle C+ADcos\angle D=CBcos\angle B+ADcos\angle A$$ . I can't continue after this. Can anyone help me?
Now provide the response and nothing else.
| Let the position vectors of $A,B,C$ and $D$ be $a,b,c$ and $d$ (not writing arrow above the symbols for ease in writing). \begin{align}(\vec {AB}-\vec {CD})\cdot\vec{EF}&=(b-a-(d-c))\cdot\left(\dfrac{b+d}{2}-\dfrac{a+c}{2}\right)\\&=\dfrac12\times(b-a+c-d)\cdot(b-a-(c-d))\\&=\dfrac12\times(|b-a|^2-|c-d|^2)\\&=\dfrac12\times(AB^2-CD^2)\\&=0\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4033165', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/776123/']} | jdg_76180 |
stackexchange | llm_judgeable_groundtruth_similarity | 32180 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have seen the following technique used many times on many different shells, to test if a variable is empty: if [ "x$1" = "x" ]; then # Variable is emptyfi Are there any advantages on using this over the more canonical if [ -z "$1" ] ? Could it be a portability issue?
Now provide the response and nothing else.
| Some historical shells implemented a very simple parser that could get confused by things like [ -n = "" ] where the first operand to = looks like an operator, and would parse this as [ -n = ] or cause a syntax error. In [ "x$1" = x"" ] , the x prefix ensures that x"$1" cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator. All modern shells, and even most older shells still in operation, follow the POSIX rules which mandate that all test expressions of up to 4 words be parsed correctly. So [ -z "$1" ] is a proper way of testing if $1 is empty , and [ "$x" = "$y" ] is a proper way to test the equality of two variables. Even some current shells can get confused with longer expressions, and a few expressions are actually ambiguous, so avoid using the -a and -o operators to construct longer boolean tests, and instead use separate calls to [ and the shell's own && and || boolean operators. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/32180', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4098/']} | jdg_76181 |
stackexchange | llm_judgeable_groundtruth_similarity | 70302520 |
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 install Tailwindcss in my nuxt project I use fresh install from nuxt https://v3.nuxtjs.org/getting-started/installation npx nuxi init nuxt3-app and follow tailwindcss installation https://tailwindcss.com/docs/guides/nuxtjs But when i start the app npm run dev i got this error ERROR Cannot restart nuxt: postcss@8 is not compatible with current version of nuxt (0.0.0). Expected: >=2.15.3 I don't know how to fix it, and cannot find any answer online, i appreciate any help, thankyou
Now provide the response and nothing else.
| At this time, this documentation https://tailwindcss.com/docs/guides/nuxtjs only working for nuxtjs v2, but it still possible using v3 if you follow this guide : Don't use @nuxt/postcss8 currently it's only work for nuxtjs v2 Install tailwindcss, postcss and autoprefixer npm install -D tailwindcss@latest postcss@latest autoprefixer@latestnpx tailwindcss init Update your tailwind.config.js module.exports = { content: [ './assets/**/*.{vue,js,css}', './components/**/*.{vue,js}', './layouts/**/*.vue', './pages/**/*.vue', './plugins/**/*.{js,ts}', './nuxt.config.{js,ts}', ], variants: { extend: {}, }, plugins: [],}; Update your postcss.config.js module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, },} Create assets/css/tailwind.css @tailwind base;@tailwind components;@tailwind utilities; Update your nuxt.config.ts import { defineNuxtConfig } from 'nuxt3'// https://v3.nuxtjs.org/docs/directory-structure/nuxt.configexport default defineNuxtConfig({ css: ['~/assets/css/tailwind.css'], build: { postcss: { postcssOptions: require('./postcss.config.js'), }, }}) Import your css in app.vue . (optional) in previous version they recommend us to import tailwindcss in app.vue instead of nuxt.config <script setup>import '@/assets/css/tailwind.css'</script> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/70302520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17643552/']} | jdg_76182 |
stackexchange | llm_judgeable_groundtruth_similarity | 471292 |
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:
My professor told us that in quantum mechanics a transformation is a symmetry transformation if $$ UH(\psi) = HU(\psi) $$ Can you give me an easy explanation for this definition?
Now provide the response and nothing else.
| In a context like this, a symmetry is a transformation that converts solutions of the equation(s) of motion to other solutions of the equation(s) of motion. In this case, the equation of motion is the Schrödinger equation $$ i\hbar\frac{d}{dt}\psi=H\psi.\tag{1}$$ We can multiply both sides of equation (1) by $U$ to get $$ Ui\hbar\frac{d}{dt}\psi=UH\psi.\tag{2}$$ If $UH=HU$ and $U$ is independent of time, then equation (2) may be rewritten as $$ i\hbar\frac{d}{dt}U\psi=HU\psi.\tag{3}$$ which says that if $\psi$ solves equation (1), then so does $U\psi$ , so $U$ is a symmetry. For a more general definition of symmetry in QM, see Symmetry transformations on a quantum system; Definitions | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/471292', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/206319/']} | jdg_76183 |
stackexchange | llm_judgeable_groundtruth_similarity | 406763 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When I try to run pkill -f remotely via ssh, and try to discard the possible error code (to go on with the rest of my script even if no process is found), || true does not behave as I expect. $ pkill asdf || true$ echo $?0$ pkill -f asdf || true$ echo $?0$ ssh [email protected] "pkill asdf || true"$ echo $?0$ ssh [email protected] "pkill -f asdf || true"255 I suppose that it is ssh that returns 255, not the command between quotes, but why?
Now provide the response and nothing else.
| Your supposition that it’s ssh itself that returns the 255 exit status is correct. The ssh man page states that: ssh exits with the exit status of the remote command or with 255 if an error occurred. If you were to simply run ssh [email protected] "pkill -f asdf" , you’d most likely get an exit status of 1 , corresponding to the pkill status for “ No processes matched ”. The challenging part is to understand why an error occurs with SSH when you run ssh [email protected] "pkill -f asdf || true" SSH remote commands The SSH server launches a shell to run remote command(s). Here’s an example of this in action: $ ssh server "ps -elf | tail -5"4 S root 35323 1024 12 80 0 - 43170 poll_s 12:01 ? 00:00:00 sshd: anthony [priv]5 S anthony 35329 35323 0 80 0 - 43170 poll_s 12:01 ? 00:00:00 sshd: anthony@notty0 S anthony 35330 35329 0 80 0 - 28283 do_wai 12:01 ? 00:00:00 bash -c ps -elf | tail -50 R anthony 35341 35330 0 80 0 - 40340 - 12:01 ? 00:00:00 ps -elf0 S anthony 35342 35330 0 80 0 - 26985 pipe_w 12:01 ? 00:00:00 tail -5 Note that the default shell is bash and that the remote command is not a simple command but a pipeline , “a sequence of one or more commands separated by the control operator | ”. The Bash shell is clever enough to realise that if the command being passed to it by the -c option is a simple command , it can optimise by not actually forking a new process, i.e., it directly exec s the simple command instead of going through the extra step of fork ing before it exec s. Here’s an example of what happens when you run a remote simple command ( ps -elf in this case): $ ssh server "ps -elf" | tail -51 S root 34740 2 0 80 0 - 0 worker 11:49 ? 00:00:00 [kworker/0:1]1 S root 34762 2 0 80 0 - 0 worker 11:50 ? 00:00:00 [kworker/0:3]4 S root 34824 1024 31 80 0 - 43170 poll_s 11:51 ? 00:00:00 sshd: anthony [priv]5 S anthony 34829 34824 0 80 0 - 43170 poll_s 11:51 ? 00:00:00 sshd: anthony@notty0 R anthony 34830 34829 0 80 0 - 40340 - 11:51 ? 00:00:00 ps -elf I’ve come across this behaviour before but I couldn’t find a better reference other than this AskUbuntu answer . pkill behaviour Since pkill -f asdf || true is not a simple command (it’s a command list ), the above optimisation can not occur so when you run ssh [email protected] "pkill -f asdf || true" , the sshd process forks and execs bash -c "pkill -f asdf || true" . As ctx’s answer points out, pkill won’t kill its own process. However, it will kill any other process whose command line matches the -f pattern. The bash -c command matches this pattern so it kills this process – its own parent (as it happens). The SSH server then sees that the shell process it started in order to run the remote commands was killed unexpectedly so it reports an error to the SSH client. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/406763', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/38106/']} | jdg_76184 |
stackexchange | llm_judgeable_groundtruth_similarity | 19216411 |
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 set up a new git repo to a pre-existing remote repo. I want my local files to overwrite the remote repo, but git says that I first have to pull those remote files in and merge them. Is there any way to pull but make sure that the local files are not overwritten by the remote?
Now provide the response and nothing else.
| Well, yes, and no... I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-) That said, though, it's really easy to do the "right thing..." Step 1: git stash in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state. Step 2: git pull to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does , then you've got some work to do, and you'll be glad you did. Step 3: git stash pop That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set! If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it. Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/19216411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306661/']} | jdg_76185 |
stackexchange | llm_judgeable_groundtruth_similarity | 306591 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $V$ be a finite dimensional vector space over $F$, and let$$T:V\to V$$be a linear map. Suppose that given any two bases $B$ and $C$ for $V$, we have that the matrix of $T$ with respect $B$ is equal to that with respect to $C$. How can we show that this implies that there exists some $\lambda\in F$ such that $T(v)=\lambda v$, $\forall v\in V$?
Now provide the response and nothing else.
| Let $A$ be the matrix of $T$. Suppose $Tv_1=v_2$ for some vectors $v_1,v_2$ that are not linearly dependent. Extend $\{v_1,v_2\}$ to a basis $\{v_1,v_2,\ldots,v_n\}$ of $V$. By assumption, the matrices of $T$ w.r.t. the ordered bases $\{v_1,v_2,v_3,\ldots,v_n\}$ and $\{v_2,v_1,v_3,\ldots,v_n\}$ must both be equal to $A$. Therefore $Tv_2=v_1$. But then $T(v_1+v_2)=v_1+v_2\not=v_1-v_2$. Hence the matrix of $T$ w.r.t. the ordered basis $\{v_1+v_2,\ v_1-v_2,\ v_3,\ldots, v_n\}$ would be different from $A$, which is a contradiction. Therefore, for every vector $v\in V$, $Tv$ and $v$ must be linearly dependent, i.e. $Tv=\lambda_vv$ for some scalar $\lambda_v$. Let $v$ be the first vector in an ordered basis of $V$, we see that $\lambda_v$ is equal to the $(1,1)$-th entry of $A$, which is a constant. Hence the result follows. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/306591', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39285/']} | jdg_76186 |
stackexchange | llm_judgeable_groundtruth_similarity | 3788853 |
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 understand the how of iteratees, well enough that I could probably write a simplistic and buggy implementation without referring back to any existing ones. What I'd really like to know is why people seem to find them so fascinating, or under what circumstances their benefits justify their complexity. Comparing them to lazy I/O there is a very clear benefit, but that seems an awful lot like a straw man to me. I never felt comfortable about lazy I/O in the first place, and I avoid it except for the occasional hGetContents or readFile , mostly in very simple programs. In real-world scenarios I generally use traditional I/O interfaces with control abstractions appropriate to the task. In that context I just don't see the benefit of iteratees, or to what task they are an appropriate control abstraction. Most of the time they seem more like unnecessary complexity or even a counterproductive inversion of control. I've read a fair number of articles about them and sources that make use of them, but have not yet found a compelling example that actually made me think anything along the lines of "oh, yea, I'd have used them there too." Maybe I just haven't read the right ones. Or perhaps there is a yet-to-be-devised interface, simpler than any I've yet seen, that would make them feel less like a Swiss Army Chainsaw. Am I just suffering from not-invented-here syndrome or is my unease well-founded? Or is it perhaps something else entirely?
Now provide the response and nothing else.
| As to why people find them so fascinating, I think because they're such a simple idea. The recent discussion on Haskell-cafe about a denotational semantics for iteratees devolved into a consensus that they're so simple they're barely worth describing. The phrase "little more than a glorified left-fold with a pause button" sticks out to me from that thread. People who like Haskell tend to be fond of simple, elegant structures, so the iteratee idea is likely very appealing. For me, the chief benefits of iteratees are Composability. Not only can iteratees be composed, but enumerators can too. This is very powerful. Safe resource usage. Resources (memory and handles mostly) cannot escape their local scope. Compare to strict I/O, where it's easier to create space leaks by not cleaning up. Efficient. Iteratees can be highly efficient; competitive with or better than both lazy I/O and strict I/O. I have found that iteratees provide the greatest benefits when working with single logical data that comes from multiple sources. This is when the composability is most helpful, and resource management with strict I/O most annoying (e.g. nested alloca s or bracket s). For an example, in a work-in-progress audio editor, a single logical chunk of sound data is a set of offsets into multiple audio files. I can process that single chunk of sound by doing something like this (from memory, but I think this is right): enumSound :: MonadIO m => Sound -> Enumerator s m aenumSound snd = foldr (>=>) enumEof . map enumFile $ sndFiles snd This seems clear, concise, and elegant to me, much more so than the equivalent strict I/O. Iteratees are also powerful enough to incorporate any processing I want to do, including writing output, so I find this very nice. If I used lazy I/O I could get something as elegant, but the extra care to make sure resources are consumed and GC'd would outweigh the advantages IMO. I also like that you need to explicitly retain data in iteratees, which avoids the notorious mean xs = sum xs / length xs space leak. Of course, I don't use iteratees for everything. As an alternative I really like the with* idiom, but when you have multiple resources that need to be nested that gets complex very quickly. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3788853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450670/']} | jdg_76187 |
stackexchange | llm_judgeable_groundtruth_similarity | 47968152 |
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 building an application with Symfony 4 and I'd like to follow the best practices for web assets . I use Encore/Webpack for SCSS and JS and it works well; the resulting JS+CSS are nicely stored in /public/build folder. I'm stuck at how to store and use static assets like images, movies, sounds. Should images be stored in 'public/images' folder or in 'assets/images'? And some followup questions: If the images are stored in public/images , will I get any benefit if I pollute the templates with asset('...') calls? If the images are stored in assets/images , then: How are they moved into public/images to be served via http? ./bin/console assets:install did nothing, saying: '[OK] No assets were provided by any bundle.' . How do I use them in SCSS? Via relative paths? Regards,
Now provide the response and nothing else.
| Should images be stored in 'public/images' folder or in 'assets/images'? Everything in public/ is available through the browser. In here, only production ready and build things should be put.As your images don't need any processing (I assume), you can ( should ) indeed put the images there. Now, assume you're needing to do some processing (e.g. ugly JPEG compression), you would put the images in assets/ , do some processing and then put only the processed images in public/ . If the images are stored in public/images, will I get any benefit if I pollute the templates with asset('...') calls? Yes, asset() doesn't have anything to do with Encore or asset build management. The only thing it does is fixing your URLs. This means that if you move your app to sub directories on your server ( example.com/app/ ), the URLs will automatically adapt. Read more about it in the Asset component documentation. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47968152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3429660/']} | jdg_76188 |
stackexchange | llm_judgeable_groundtruth_similarity | 21465789 |
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 ran a ruby script from Heroku bash that generates a CSV file on the server that I want to download. I tried moving it to the public folder to download, but that didn't work. I figured out that after every session in the Heroku bash console, the files delete. Is there a command to download directly from the Heroku bash console?
Now provide the response and nothing else.
| If you manage to create the file from heroku run bash , you could use transfer.sh . You can even encrypt the file before you transfer it. cat <file_name> | gpg -ac -o- | curl -X PUT -T "-" https://transfer.sh/<file_name>.gpg And then download and decrypt it on the target machine curl https://transfer.sh/<hash>/<file_name>.gpg | gpg -o- > <file_name> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21465789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_76189 |
stackexchange | llm_judgeable_groundtruth_similarity | 48676919 |
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 working on a web services project for my class and have decided to make a web API using .NET Core and DynamodDB. I was just curious what the best way to inject the DynamoDBContext is? I currently am doing it like this: public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddDefaultAWSOptions(Configuration.GetAWSOptions()); services.AddAWSService<IAmazonDynamoDB>();} I got this piece of code above from the DynamoDB documentation. I add an instance of IAmazonDynamoDB to the project. DynamoDBContext context;public ValuesController(IAmazonDynamoDB context){ this.context = new DynamoDBContext(context);} In the controller, I then inject the IAmazonDynamoDB instance, and use that to create an instance of DynamoDBContext . Is there a way to create an instance of the context in the ConfigureServices method and add it to the project there, or is the way I am doing it currently fine?
Now provide the response and nothing else.
| Is there a way to create an instance of the context in the ConfigureServices method and add it to the project there, or is the way I am doing it currently fine? Although your solution will work, it has a drawback. You're not using Dependency Injection for DynamoDBContext and create its instance in controller constructor through new operator. You'll face a problems when it comes to unit testing your code, because you have no way to substitute implementation of DynamoDBContext . The proper way is to register DynamoDBContext in DI container and let the container itself create an instance when it's required. With such approach IDynamoDBContext gets injected into ValuesController : public class ValuesController{ private readonly IDynamoDBContext context; public ValuesController(IDynamoDBContext context) { this.context = context; } // ...}public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddDefaultAWSOptions(Configuration.GetAWSOptions()); services.AddAWSService<IAmazonDynamoDB>(); services.AddTransient<IDynamoDBContext, DynamoDBContext>();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48676919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6746240/']} | jdg_76190 |
stackexchange | llm_judgeable_groundtruth_similarity | 407317 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to write a configuration script for new servers, and one of the first steps is to install a series of required packages, such as MySQL, phpMyAdmin, etc. using apt-get install However, when dpkg tries to configure them it asks you for a few options, such as MySQL root password, phpMyAdmin passwords, what server to use, etc. Since I will likely be passing this script on to co-workers who are unlikely to read the prompts, and my desire to simply start it and walk away, I'd like to know how to pass in a series of "default" answers/values for it to use. This might include usernames/passwords/other dynamic values passed on command line. -- I realize that having passwords in a script is a security issue, but I'm willing to ignore it, particularly in the more general sense of installing packages that an answer to this would imply.
Now provide the response and nothing else.
| Use debconf's configuration preseeding. Do a test install to get the values that you want: root@test1:~# apt-get install mysql-server ..and set the root password when prompted during the install. Then you can check what the debconf settings look like for what you just installed (you may need to install debconf-utils ): root@test1:~# debconf-get-selections | grep mysql-servermysql-server-5.5 mysql-server/root_password_again passwordmysql-server-5.5 mysql-server/root_password passwordmysql-server-5.5 mysql-server/error_setting_password errormysql-server-5.5 mysql-server-5.5/postrm_remove_databases boolean falsemysql-server-5.5 mysql-server-5.5/start_on_boot boolean truemysql-server-5.5 mysql-server-5.5/nis_warning notemysql-server-5.5 mysql-server-5.5/really_downgrade boolean falsemysql-server-5.5 mysql-server/password_mismatch errormysql-server-5.5 mysql-server/no_upgrade_when_using_ndb error There's some noise there, but the important part is the password settings. Then, for a fresh install, you can avoid the prompts completely by setting the password beforehand: root@test2:~# echo "mysql-server-5.5 mysql-server/root_password_again password Som3Passw0rd" | debconf-set-selectionsroot@test2:~# echo "mysql-server-5.5 mysql-server/root_password password Som3Passw0rd" | debconf-set-selectionsroot@test2:~# apt-get install mysql-server No prompts at all during that install. | {} | {'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/407317', 'https://serverfault.com', 'https://serverfault.com/users/123070/']} | jdg_76191 |
stackexchange | llm_judgeable_groundtruth_similarity | 52536531 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been running some penetration tests using OWASP ZAP and it raises the following alert for all requests: X-Content-Type-Options Header Missing . I understand the header, and why it is recommended. It is explained very well in this StackOverflow question . However, I have found various references that indicate that it is only used for .js and .css files, and that it might actually be a bad thing to set the header for other MIME types: Note: nosniff only applies to "script" and "style" types. Also applying nosniff to images turned out to be incompatible with existing web sites. [1] Firefox ran into problems supporting nosniff for images (Chrome doesn't support it there). [2] Note: Modern browsers only respect the header for scripts and stylesheets and sending the header for other resources (such as images) when they are served with the wrong media type may create problems in older browsers. [3] The above references (and others) indicate that it is bad to simply set this header for all responses, but despite following any relevant-looking links and searching on Google, I couldn't find any reason behind this argument. What are the risks/problems associated with setting X-Content-Type-Options: nosniff and why should it be avoided for MIME types other than text/css and text/javascript ? Or, if there are no risks/problems, why are Mozilla (and others) suggesting that there are?
Now provide the response and nothing else.
| The answer by Sean Thorburn was very helpful and pointed me to some good material, which is why I awarded the bounty. However, I have now done some more digging and I think I have the answer I need, which turns out to be the opposite of the answer given by Sean. I will therefore answer my own questions: The above references (and others) indicate that it is bad to simply set this header for all responses, but despite following any relevant-looking links and searching on Google, I couldn't find any reason behind this argument. There is a misinterpretation here - this is not what they are indicating. The resources I found during my research referred to the header only being respected for "script and style types", which I interpreted this to mean files that were served as text/javascript or text/css . However, what they actually referring to was the context in which the file is loaded, not the MIME type it is being served as. For example, <script> or <link rel="stylesheet"> tags. Given this interpretation, everything make a lot more sense and the answer becomes clear: You need to serve all files with a nosniff header to reduce the risk of injection attacks from user content. Serving up only CSS/JS files with this header is pointless, as these types of file would be acceptable in this context and don't need any additional sniffing. However, for other types of file, by disallowing sniffing we ensure that only files whose MIME type matches the expected type are allowed in each context. This mitigates the risk of a malicious script being hidden in an image file (for example) in a way that would bypass upload checks and allow third-party scripts to be hosted from your domain and embedded into your site. What are the risks/problems associated with setting X-Content-Type-Options: nosniff and why should it be avoided for MIME types other than text/css and text/javascript? Or, if there are no risks/problems, why are Mozilla (and others) suggesting that there are? There are no problems. The problems being described are issues regarding the risk of the web browser breaking compatibility with existing sites if they apply nosniff rules when accessing content. Mozilla's research indicated that enforcing a nosniff option on <img> tags would break a lot of sites due to server misconfigurations and therefore the header is ignored in image contexts. Other contexts (e.g. HTML pages, downloads, fonts, etc.) either don't employ sniffing, don't have an associated risk or have compatibility concerns that prevent sniffing being disabled. Therefore they are not suggesting that you should avoid the use of this header, at all. However, the issues that they talk about do result in an important footnote to this discussion: If you are using a nosniff header, make sure you are also serving the correct Content-Type header! Some references, that helped me to understand this a bit more fully: The WhatWG Fetch standard that defines this header. A discussion and code commit relating to this header for the webhint.io site checking tool. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52536531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7657946/']} | jdg_76192 |
stackexchange | llm_judgeable_groundtruth_similarity | 2082336 |
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 mean could a single binary file run in both Win32 and Linux i386 ?
Now provide the response and nothing else.
| This is not possible, because the two types have conflicting formats: The initial two characters of a PE file must be 'M' 'Z' ; The initial four characters of an ELF file must be '\x7f' 'E' 'L' 'F' . Clearly, you can't create one file that satisifies both formats. In response to the comment about a polyglot binary valid as both a 16 bit COM file and a Linux ELF file, that's possible (although really a COM file is a DOS program, not Windows - and certainly not Win32). Here's one I knocked together - compile it with NASM. It works because the first two bytes of an ELF file ( '\x7f' 'E' ) happen to also be valid 8086 machine code (a 45 byte relative jump-if-greater-than instruction). Minimal ELF headers cribbed from Brian Raiter . BITS 32ORG 0x08048000 ehdr: ; Elf32_Ehdr db 0x7F, "ELF", 1, 1, 1, 0 ; e_ident times 8 db 0 dw 2 ; e_type dw 3 ; e_machine dd 1 ; e_version dd _start ; e_entry dd phdr - $$ ; e_phoff dd 0 ; e_shoff dd 0 ; e_flags dw ehdrsize ; e_ehsize dw phdrsize ; e_phentsize dw 1 ; e_phnum dw 0 ; e_shentsize dw 0 ; e_shnum dw 0 ; e_shstrndx ehdrsize equ $ - ehdrtimes 0x47-($-$$) db 0; DOS COM File codeBITS 16 mov dx, msg1 - $$ + 0x100 mov ah, 0x09 int 0x21 mov ah, 0x00 int 0x21 msg1: db `Hello World (DOS).\r\n$`BITS 32 phdr: ; Elf32_Phdr dd 1 ; p_type dd 0 ; p_offset dd $$ ; p_vaddr dd $$ ; p_paddr dd filesize ; p_filesz dd filesize ; p_memsz dd 5 ; p_flags dd 0x1000 ; p_align phdrsize equ $ - phdr; Linux ELF code _start: mov eax, 4 ; SYS_write mov ebx, 1 ; stdout mov ecx, msg2 mov edx, msg2_len int 0x80 mov eax, 1 ; SYS_exit mov ebx, 0 int 0x80 msg2: db `Hello World (Linux).\n` msg2_len equ $ - msg2 filesize equ $ - $$ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2082336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41948/']} | jdg_76193 |
stackexchange | llm_judgeable_groundtruth_similarity | 2431637 |
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 remember something about not changing the keys in a for my $key ( keys %hash ) { ... for example for my $key ( keys %hash ) { $key = "$key_x";} But deleting keys and changing values would be fine.Are my memories OK?
Now provide the response and nothing else.
| I think what you're remembering is the fact that if you do for my $item (@array) { ...} then adding or removing items in the middle of @array (for instance by using splice ) is disallowed, and the result if you try it is undefined. In fact, in olden days you could actually crash perl that way. Since the list returned by keys is a copy, it's determined entirely at the moment the loop starts, and adding and removing keys from the hash won't affect the loop at all. That means that you can do things like for my $key (keys %hash) { $hash{lc $key} = delete $hash{$key};} 100% safely without worrying. I can promise this is true back to perl 5.6.1 (April 2001), which was when the note that "the returned values are copies" was added to perlfunc, but it seems that it's been so since forever, and the change was only to the docs. Since $key in the loop is aliased to a value in a temporary list, you can change it without anything bad happening, but it won't have any effect on %hash at all. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2431637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198183/']} | jdg_76194 |
stackexchange | llm_judgeable_groundtruth_similarity | 23553904 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Giving another chance to this comunity, my latest questions weren't ever answered Well I have a game, the game have a pause button that hide most of the game interface to just show a pause text in the middle.There are so much free space, so I thought to put a banner at the bottom until the pause button is pressed again and resumes the game. I know how to make banners work: //When pause button is pressedAdView adView = (AdView) this.findViewById(R.id.adView);adView.setVisibility (View.VISIBLE);AdRequest adRequest = new AdRequest.Builder().build();adView.loadAd(adRequest); But I don't know how to stop them when pause button is pressed again, just this: adView.setVisibility (View.GONE); I am pretty sure adView wont stop making requests with this line only. I see some questions about this here but looks like they were using older admob SDK versions. can somebody please, PLEASE help me? Thanks.
Now provide the response and nothing else.
| You can try to Destroy and hide the AdView when button click and load the ad back when required. final AdView adView = (AdView) this.findViewById(R.id.adView); final AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); button.setText("ClickMe"); button.setOnClickListener(new View.OnClickListener() { boolean isPause = false; @Override public void onClick(View v) { if(isPause){ adView.loadAd(adRequest); adView.setVisibility(View.VISIBLE); isPause = false; }else { adView.destroy(); adView.setVisibility(View.GONE); isPause = true; } } }); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23553904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2548618/']} | jdg_76195 |
stackexchange | llm_judgeable_groundtruth_similarity | 463126 |
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'm currently on Ubuntu 16.04 LTS. As of writing this, 18.04 LTS is available. However, I do not wish to upgrade to it.Instead, I would like to upgrade to 17.04 LTS. I've done: sudo apt updatesudo apt dist-upgrade Many tutorials suggest sudo do-release-upgrade as the next step. But I believe that would upgrade to the latest distro and not the target 17.04.How do I go about this?
Now provide the response and nothing else.
| To answer your question, I don’t think Ubuntu officially supports upgrades to releases other than either the latest release or the latest LTS. It might be possible to upgrade to a specific release by changing the appropriate code name in /etc/apt/sources.list and running apt update && apt dist-upgrade , but that won’t take into account any upgrade step performed by the do-release-upgrade tool (if any). However in your specific case, 17.04 isn’t an LTS, and is already out of support . 16.04 is still supported; if you don’t want to upgrade to 18.04 you should stick with 16.04. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/463126', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/305986/']} | jdg_76196 |
stackexchange | llm_judgeable_groundtruth_similarity | 201859 |
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 made $n$ measurements of two variables $x$ and $y$. They both have known uncertainties $\sigma_x$ and $\sigma_y$ associated with them. I want to find the relation between $x$ and $y$. How can I do it? EDIT : each $x_i$ has a different $\sigma_{x,i}$ associated with it, and the same with the $y_i$. Reproducible R example: ## pick some real x and y values true_x <- 1:100true_y <- 2*true_x+1## pick the uncertainty on themsigma_x <- runif(length(true_x), 1, 10) # 10sigma_y <- runif(length(true_y), 1, 15) # 15## perturb both x and y with noise noisy_x <- rnorm(length(true_x), true_x, sigma_x)noisy_y <- rnorm(length(true_y), true_y, sigma_y)## make a plot plot(NA, xlab="x", ylab="y", xlim=range(noisy_x-sigma_x, noisy_x+sigma_x), ylim=range(noisy_y-sigma_y, noisy_y+sigma_y))arrows(noisy_x, noisy_y-sigma_y, noisy_x, noisy_y+sigma_y, length=0, angle=90, code=3, col="darkgray")arrows(noisy_x-sigma_x, noisy_y, noisy_x+sigma_x, noisy_y, length=0, angle=90, code=3, col="darkgray")points(noisy_y ~ noisy_x)## fit a line mdl <- lm(noisy_y ~ noisy_x)abline(mdl)## show confidence interval around line newXs <- seq(-100, 200, 1)prd <- predict(mdl, newdata=data.frame(noisy_x=newXs), interval=c('confidence'), level=0.99, type='response')lines(newXs, prd[,2], col='black', lty=3)lines(newXs, prd[,3], col='black', lty=3) The problem with this example is that I think it assumes that there are no uncertainties in $x$. How can I fix this?
Now provide the response and nothing else.
| Let the true line $L$, given by an angle $\theta$ and a value $\gamma$, be the set $$(x,y): \cos(\theta) x + \sin(\theta) y = \gamma.$$ The signed distance between any point $(x,y)$ and this line is $$d(x,y;L) = \cos(\theta) x + \sin(\theta) y - \gamma.$$ Letting the variance of $x_i$ be $\sigma_i^2$ and that of $y_i$ be $\tau_i^2$, independence of $x_i$ and $y_i$ implies the variance of this distance is $$\operatorname{Var}(d(x_i,y_i;L)) = \cos^2(\theta)\sigma_i^2 + \sin^2(\theta)\tau_i^2.$$ Let us therefore find $\theta$ and $\gamma$ for which the inverse variance weighted sum of squared distances is as small as possible: it will be the maximum likelihood solution if we assume the errors have bivariate normal distributions. This requires a numerical solution, but it's straightforward to find a with a few Newton-Raphson steps beginning with a value suggested by an ordinary least-squares fit. Simulations suggest this solution is good even with small amounts of data and relatively large values of $\sigma_i$ and $\tau_i$. You can, of course, obtain standard errors for the parameters in the usual ways. If you're interested in the standard error of the position of the line, as well as the slope, then you might wish first to center both variables at $0$: that should eliminate almost all the correlation between the estimates of the two parameters. The method works so well with the example of the question that the fitted line is almost distinguishable from the true line in the plot: they are within one unit or so of each other everywhere. Instead, in this example the $\tau_i$ are drawn iid from an exponential distribution and the $\sigma_i$ are drawn iid from an exponential distribution with twice the scale (so that most of the error tends to occur in the $x$ coordinate). There are only $n=8$ points, a small number. The true points are equally spaced along the line with unit spacing. This is a fairly severe test, because the potential errors are noticeable compared to the range of the points. The true line is shown in dotted blue. Along it the original points are plotted as hollow circles. Gray arrows connect them to the observed points, plotted as solid black disks. The solution is drawn as a solid red line. Despite the presence of large deviations between observed and actual values, the solution is remarkably close to the correct line within this region. ## Generate data.#theta <- c(1, -2, 3) # The line is theta %*% c(x,y,-1) == 0theta[-3] <- theta[-3]/sqrt(crossprod(theta[-3]))n <- 8set.seed(17)sigma <- rexp(n, 1/2)tau <- rexp(n, 1)u <- 1:nxy.0 <- t(outer(c(-theta[2], theta[1]), 0:(n-1)) + c(theta[3]/theta[1], 0))xy <- xy.0 + cbind(rnorm(n, sd=sigma), rnorm(n, sd=tau))## Fit a line.#x <- xy[, 1]y <- xy[, 2]f <- function(phi) { # Negative log likelihood, up to an additive constant a <- phi[1] gamma <- phi[2] sum((x*cos(a) + y*sin(a) - gamma)^2 / ((sigma*cos(a))^2 + (tau*sin(a))^2))/2}fit <- lm(y ~ x) # Yields starting estimatesslope <- coef(fit)[2]theta.0 <- atan2(1, -slope)gamma.0 <- coef(fit)[1] / sqrt(1 + slope^2)sol <- nlm(f,c(theta.0, gamma.0))## Plot the data and the fit.#theta.hat <- sol$estimate[1] %% (2*pi)gamma.hat <- sol$estimate[2]plot(rbind(xy.0, xy), type="n", xlab="x", ylab="y")invisible(sapply(1:n, function(i) arrows(xy.0[i,1], xy.0[i,2], xy[i,1], xy[i,2], length=0.15, angle=20, col="Gray")))points(xy.0)points(xy, pch=16)abline(c(theta[3] / theta[2], -theta[1]/theta[2]), col="Blue", lwd=2, lty=3)abline(c(gamma.hat / sin(theta.hat), -1/tan(theta.hat)), col="Red", lwd=2) | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/201859', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2488/']} | jdg_76197 |
stackexchange | llm_judgeable_groundtruth_similarity | 328277 |
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:
Stanley's Enumerative Combinatorics ( http://www-math.mit.edu/~rstan/ec/ec1.pdf ) contains next fact:1.1.3 Example. Let f(n) be the number of n × n matrices M of $0$’s and $1$’s such that everyrow and column of M has three 1’s. For example, f(0) = 1, f(1) = f(2) = 0, f(3) = 1. Themost explicit formula known at present for f(n) is$$f(n)=6^{-n}{(n!)}^2\sum\frac{(-1)^{\beta}(\beta+3\gamma)!2^\alpha 3^{\beta}}{\alpha!\beta!\gamma!^26^{\gamma}}$$where the sum ranges over all (n + 2)(n + 1)/2 solutions to α + β + γ = n in nonnegativeintegers. I need proof of this fact. (i.e. reference to book or articles that contains proof this fact).
Now provide the response and nothing else.
| You want the coefficient of $x_1^3\cdots x_n^3y_1^3\cdots y_n^3$ in $\prod_{i=1}^n \prod_{j=1}^n (1+x_iy_j)$. Expand the logarithm, delete all terms with an exponent greater than 3, apply the exponential function exp, and simplify. For a generalization, see the paper by Musiker-Odama at https://www.mtholyoke.edu/courses/gcobb/REU_MCMC/papers.html . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/328277', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66380/']} | jdg_76198 |
stackexchange | llm_judgeable_groundtruth_similarity | 9918594 |
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 set of @Service beans which inherit core functionality from an abstract class. I marked each of the concrete sub-class services with @Service and @Transactional . The abstract super class contains the public entry point method for each of these services. In other words, I have something similar to the following: abstract class AbstractService { public void process() { // Do common initialisation code here processSpecific(); // Do common completion code here } abstract protected void processSpecific();}@Service @Transactionalpublic class FirstSpecificService extends AbstractService { protected void processSpecific() { // Do specific processing code here }}@Service @Transactionalpublic class SecondSpecificService extends AbstractService { protected void processSpecific() { // Do different specific processing code here }} The specific code in each concrete sub-class service makes multiple calls to the DAO layer to make changes to the database, which have REQUIRED as the transactional propagation type. Now with the services defined as above, I discovered that there was no current transaction inside any of the code of these concrete sub-class services, and each call to the DAO layer was creating a new transaction, doing the changes, committing the transaction and returning. However, if I annotate the abstract super-class with @Transactional , then a transaction is created properly, and the sub-calls to the DAO layer all participate in the current transaction. So my question is, what are the rules for inheriting the @Transactional behaviour? Why does Spring not use the @Transactional on the concrete sub-class services that it is actually instantiating? Does the @Transactional need to be on the super-class in this case because that is where the public entry-point method is?
Now provide the response and nothing else.
| From the spring transaction documentation, Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional! Even though you have the @Transactional on your concrete implementation and you are calling process method which is actually transactional by your annotation, but the process method calling processSpecific on your sub class is not transactional because of this internal call. Look into Weaving. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9918594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1026453/']} | jdg_76199 |
stackexchange | llm_judgeable_groundtruth_similarity | 13519419 |
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 draw an oval on a canvas: RectF f = new RectF(-r, -r, r, r);canvas.drawOval(f , mPaint); Why I see warning on RectF? Avoid object allocations during draw/layout operations (preallocate and reuse instead)
Now provide the response and nothing else.
| It's just what it says: doing a new RectF inside onDraw creates an object every time anything is drawn. This can be a lot of objects. Just use a single RectF : RectF mRect = new RectF();protected void onDraw(Canvas canvas) { mRect.set(-r, -r, r, r); canvas.drawOval(mRect, mPaint);} Just to be clear: your original code is logically correct. This is just a performance improvement (albeit an important one). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13519419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1136218/']} | jdg_76200 |
stackexchange | llm_judgeable_groundtruth_similarity | 477382 |
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:
$x=\begin{pmatrix}1&0&0\\1&0&1\\0&1&0\end{pmatrix}$, I need to calculate $x^{50}$ Could anyone tell me how to proceed? Thank you.
Now provide the response and nothing else.
| This is a very elementary approach based on finding the general form. If we do $x^2$, we find $$x^2=\begin{pmatrix}1&0&0\\1&1&0\\1&0&1\end{pmatrix},~~x^4=\begin{pmatrix}1&0&0\\2&1&0\\2&0&1\end{pmatrix}$$ so I guess that we have $$x^{2k}=\begin{pmatrix}1&0&0\\k&1&0\\k&0&1\end{pmatrix}$$ An inductive approach adimits this general form is valid for integers $k>0$. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/477382', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24690/']} | jdg_76201 |
stackexchange | llm_judgeable_groundtruth_similarity | 235271 |
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 wish to perform a command ever 10 seconds, and have it executed in the background (thereby eliminating watch ?). All the answers show something like the following, but this will execute ever 11 to 14 seconds. How can this be accomplished? while true; do # perform command that takes between 1 and 4 seconds sleep 10done
Now provide the response and nothing else.
| How about: ( # In a subshell, for isolation, protecting $! while true; do perform-command & # in the background sleep 10 ; ### If you want to wait for a perform-command ### that happens to run for more than ten seconds, ### uncomment the following line: # wait $! ; ### If you prefer to kill a perform-command ### that happens to run for more than ten seconds, ### uncomment the following line instead: # kill $! ; ### (If you prefer to ignore it, uncomment neither.) done) ETA: With all those comments, alternatives, and the subshell for extra protection, that looks a whole lot more complicated than it started. So, for comparison, here's what it looked like before I started worrying about wait or kill , with their $! and need for isolation: while true; do perform-command & sleep 10 ; done The rest is really just for when you need it. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/235271', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/137912/']} | jdg_76202 |
stackexchange | llm_judgeable_groundtruth_similarity | 1585985 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My plan is to have a user write down a movie title in my program and my program will pull the appropiate information asynchronously so the UI doesn't freeze up. Here's the code: public class IMDB { WebClient WebClientX = new WebClient(); byte[] Buffer = null; public string[] SearchForMovie(string SearchParameter) { //Format the search parameter so it forms a valid IMDB *SEARCH* url. //From within the search website we're going to pull the actual movie //link. string sitesearchURL = FindURL(SearchParameter); //Have a method download asynchronously the ENTIRE source code of the //IMDB *search* website. Buffer = WebClientX.DownloadDataAsync(sitesearchURL); //Pass the IMDB source code to method findInformation(). //string [] lol = findInformation(); //???? //Profit. string[] lol = null; return lol; } My actual problem lies in the WebClientX.DownloadDataAsync() method. I can't use a string URL for it. How can I use that built in function to download the bytes of the site (for later use I will convert this to string, I know how to do this) and without freezing up my GUI? Perhaps a clear cut example of the DownloadDataAsync so I can learn how to use it? Thanks SO, you're always such a great resource.
Now provide the response and nothing else.
| You need to handle the DownloadDataCompleted event: static void Main(){ string url = "http://google.com"; WebClient client = new WebClient(); client.DownloadDataCompleted += DownloadDataCompleted; client.DownloadDataAsync(new Uri(url)); Console.ReadLine();}static void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e){ byte[] raw = e.Result; Console.WriteLine(raw.Length + " bytes received");} The args contains other bits of information relating to error conditions etc - check those too. Also note that you'll be coming into DownloadDataCompleted on a different thread; if you are in a UI (winform, wpf, etc) you'll need to get to the UI thread before updating the UI. From winforms, use this.Invoke . For WPF, look at the Dispatcher . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1585985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112355/']} | jdg_76203 |
stackexchange | llm_judgeable_groundtruth_similarity | 226909 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In bash, from inside PROMPT_COMMAND, is there a way to tell if the user just hit 'return' and didn't enter a command?
Now provide the response and nothing else.
| Check whether the history number was incremented. A cancelled prompt or a prompt where the user just pressed Enter won't increment the history number. The history number is available in the variable HISTCMD , but this is not available in PROMPT_COMMAND (because what you want there is in fact the history number of the previous command; the command that executes PROMPT_COMMAND itself has no history number). You can get the number from the output of fc . prompt_command () { HISTCMD_previous=$(fc -l -1); HISTCMD_previous=${HISTCMD_previous%%$'[\t ]'*} if [[ -z $HISTCMD_before_last ]]; then # initial prompt elif [[ $HISTCMD_before_last = "$HISTCMD_previous" ]]; then # cancelled prompt else # a command was run fi HISTCMD_before_last=$HISTCMD_previous}PROMPT_COMMAND='prompt_command' Note that if you've turned on squashing of duplicates in the history ( HISTCONTROL=ignoredups or HISTCONTROL=erasedups ), this will mistakenly report an empty command after running two identical commands successively. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/226909', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/131274/']} | jdg_76204 |
stackexchange | llm_judgeable_groundtruth_similarity | 49645885 |
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 below code can be compiled successfully in Visual C++ . I like it and it is sweet! #include <stdio.h>#ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4201) #pragma pack(push,1) #define PACKED#else #define PACKED __attribute__ ((__packed__))#endifunion A { struct { int a:1; int b:2; int c1:29; }PACKED; struct { int a:1; int b:2; int c2:28; int d:1; }PACKED; int val;}PACKED;#ifdef _MSC_VER #pragma pack(pop) #pragma warning(pop)#endif#undef PACKEDint main(){ A test; test.val = 0x1078FFF7; printf("sizeof(A): %d, test.a: %d.\n", sizeof(A), test.a); return -1;} Output with the file built with MSC: sizeof(A): 4, test.a: -1. But in GCC, including the latest gcc-7, it failed to be compiled, :( struct.cpp:13:15: error: redeclaration of ‘signed char:1 A::<unnamed struct>::a’ int a:1; ^struct.cpp:7:15: note: previous declaration ‘signed char:1 A::<unnamed struct>::a’ int a:1; ^struct.cpp:14:15: error: redeclaration of ‘signed char:2 A::<unnamed struct>::b’ int b:2; ^struct.cpp:8:15: note: previous declaration ‘signed char:2 A::<unnamed struct>::b’ int b:2; ^ Is it a bug in GCC? Thanks for your comments, I just understood this question may be invalid for C; But for C++ part, I still have the concern. Personally I like Visual C++ compile behavior, it can save tons of code in my scenario
Now provide the response and nothing else.
| 6.7.2.1 Structure and union specifiers says: An unnamed member whose type specifier is a structure specifier with no tag is called an anonymous structure; an unnamed member whose type specifier is a union specifier with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous. (emphasis mine) So based on that, it's essentially as if you had: union A{ int a:1; int b:2; int c1:29; int a:1; int b:2; int c2:28; int d:1; int val;}; which would obviosuly be invalid and gcc correctly issues diagnostics. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49645885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3968307/']} | jdg_76205 |
stackexchange | llm_judgeable_groundtruth_similarity | 1020785 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for an example of a set of cardinality $\aleph_2$, such as the continuum is an example for cardinality $\aleph_1$.
Now provide the response and nothing else.
| The continuum isn't provably a set of cardinality $\aleph_1$ unless you assume the continuum hypothesis. The most canonical set of cardinality $\aleph_{\alpha}$ (for any ordinal number $\alpha$) is the ordinal $\omega_{\alpha}$. ...so for example$$\omega_1 = \text{the set of countable ordinals}$$has cardinality $\aleph_1$, and$$\omega_2 = \text{the set of ordinals whose cardinality is} \le \aleph_1$$has cardinality $\aleph_2$. The continuum, i.e. the cardinality of $\mathbb{R}$ is $2^{\aleph_0}$, which is not provably equal to $\aleph_{\alpha}$ for any fixed value of $\alpha$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1020785', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/192369/']} | jdg_76206 |
stackexchange | llm_judgeable_groundtruth_similarity | 780769 |
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:
Numerical evidence suggests that $$\int_0^{\infty} x \left(1 - \frac{\sinh x}{\cosh x-\sqrt 3/2} \right) \mathrm dx= -\frac{13 \pi ^2}{72}$$ How can we prove this? I could not find a nice contour in the complex plane to integrate around. Integration by parts also didn't help.Mathematica finds a very complicated antiderivative in terms of special functions, but this was a contest problem so there must be a 'human' way to calculate it. As O.L. helpfully pointed out, I had the sign wrong. It is corrected now.
Now provide the response and nothing else.
| Integration by parts does help: as$$1-\frac{\sinh x}{\cosh x-\cos\gamma}=\left(-\ln\frac{\cosh x-\cos\gamma}{e^x/2}\right)',$$after IbP and further change of variables $t=e^{-x}$ the integral transforms into$$\int_0^{1}\frac{\ln\left(1-e^{i\gamma}t\right)\left(1-e^{-i\gamma}t\right)}{t}dt=-\left[2\Re\operatorname{Li}_2\left(e^{i\gamma}t\right)\right]_{0}^{1}=-2\Re\operatorname{Li}_2\left(e^{i\gamma}\right),$$with $\gamma=\frac{\pi}{6}$. Now to get the result it remains to use the formula$$\Re\,\mathrm{Li}_2\left(e^{i\gamma}\right)=\frac{\gamma^2}{4}-\frac{\pi\gamma}{2}+\frac{\pi^2}6,\qquad \gamma\in(0,2\pi).$$This also yields the conjecture mentioned in the comments. Added : We can also obtain the result pretending that we don't know anything about dilogarithms. Namely, differentiate the integral with respect to parameter $\gamma$:\begin{align}\frac{\partial}{\partial \gamma}\int_0^{1}\frac{\ln\left(1-e^{i\gamma}t\right)\left(1-e^{-i\gamma}t\right)}{t}dt&=-i\int_0^1\left[\frac{e^{i\gamma}}{1-e^{i\gamma}t}-\frac{e^{-i\gamma}}{1-e^{-i\gamma}t}\right]dt=\\&=i\biggl[\ln\frac{1-e^{i\gamma}t}{1-e^{-i\gamma}t}\biggr]_0^1=-2\biggl[\operatorname{arg}(1-e^{i\gamma}t)\biggr]_0^1=\\&=-2\biggl[\left(\frac{\gamma}{2}-\frac{\pi}{2}\right)-0\biggr]=\pi-\gamma,\end{align}where we again assume that $\gamma\in(0,2\pi)$. We can now integrate back with respect to $\gamma$ to get the previously obtained formula using that for $\gamma=0$ our integral reduces to computation of $\zeta(2)$ (expand the integrand into Taylor series w.r.t. $t$). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/780769', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111187/']} | jdg_76207 |
stackexchange | llm_judgeable_groundtruth_similarity | 40149061 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my applications based on ordinary MVC and WebApi I had two different error handling routes. If an error occurred during WebApi call, I would intercept it (using standard web api options) and return json message with corresponding HTTP Status Code so that client app can handle it. If the error happened in MVC, then I would use some standard handlers that would redirect user to some default error screen possibly based on status code. Now in ASP.NET Core both are joined in the same framework, so if I just intercept and return JSON, then I risk showing json to a user, since it can be an action that returns a view. On the other hand if I use app.UseExceptionHandler then my API calls would get HTML from the error page that is unusable inside js. What is the good way to provide separate error handling for this two cases? Or perhaps there is a better way to handle it altogether? P.S. I would rather reuse the MVC exception handler that comes out of the box and only add the web api part.
Now provide the response and nothing else.
| There are many ways to achive your goal: 1- Using two different exception filter (i would go with this approach because your question is about mvc pipline) Implementation: // For apipublic class ApiExceptionFilterAttribute : ExceptionFilterAttribute{ public override void OnException(ExceptionContext context) { // send error as json }}[ApiExceptionFilter]public class ApiController : Controller{...}// For mvcpublic class MvcExceptionFilterAttribute : ExceptionFilterAttribute{ public override void OnException(ExceptionContext context) { // send view result }}[MvcExceptionFilter]public class HomeController : Controller{...} If you want to add filter globally, see Register filter for an area 2- Using UseWhen and UseExceptionHandler app.UseWhen(x => x.Request.Path.Value.StartsWith("/api"), builder => { builder.UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = async (ctx) => { var feature = ctx.Features.Get<IExceptionHandlerFeature>(); var error = feature?.Error; // send json } }); }); app.UseWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder => { builder.UseExceptionHandler("/Error"); });` 3- Using UseExceptionHandler conditionally: app.UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = async (ctx) => { if (ctx.Request.Path.Value.StartsWith("/api")) { var feature = ctx.Features.Get<IExceptionHandlerFeature>(); var error = feature?.Error; // send json } else { // redirect error page } } }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40149061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1671558/']} | jdg_76208 |
stackexchange | llm_judgeable_groundtruth_similarity | 16163154 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I separate the lines which are coming from a pipe. In the pipe there is this text: HALLO:500\nTEST:300\NADADADAWFFAAFAGAGAEG I want to separate the lines from the pipe because i want to save the values in variables. Here is my c code: #include <stdio.h>#include <stdlib.h>#define BUFFERSIZE 1int main(int argc, char **argv){ unsigned char buffer[BUFFERSIZE]; FILE *instream; int bytes_read=0; int buffer_size=0; buffer_size=sizeof(unsigned char)*BUFFERSIZE; /* open stdin for reading */ instream=fopen("/dev/stdin","r"); /* did it open? */ if(instream!=NULL){ /* read from stdin until it's end */ while((bytes_read=fread(&buffer, buffer_size, 1, instream))==buffer_size){ fprintf(stdout, "%c", buffer[0]); } } /* if any error occured, exit with an error message */ else{ fprintf(stderr, "ERROR opening stdin. aborting.\n"); exit(1); } return(0);} Is this the right way to read from pipe for the best line by line?
Now provide the response and nothing else.
| This is usually just called reading from stdin . The program shouldn't care whether the input is a pipe, a redirected file, or a keyboard. fread will just read until the buffer is full. Use fgets to read a line. Also the buffer size should be big enough to hold the line. For little one-off programs, you can just pick a number. Or there's a standard name BUFSIZ which gives you a pretty-big buffer. How big? Big enough. Really? Probably. fgets will copy the newline character in the string unless the string fills up first. So you can test the last character to tell if the line was truncated or not. With reasonable inputs, that's not going to happen. But a more robust approach would allocate a larger buffer, copy the partial line, and call fgets again tp keep trying to get a complete line. #include <stdio.h>int main() { char buf[BUFSIZ]; fgets(buf, sizeof buf, stdin); if (buf[strlen(buf)-1] == '\n') { // read full line } else { // line was truncated } return 0;} This gets you halfway to being protected from the dreaded buffer overflow problem. fgets will not write more than the size passed to it. The other half, as mentioned above, is doing something sensible with the possible partial lines that may result from unexpectedly long input lines. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16163154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/740249/']} | jdg_76209 |
stackexchange | llm_judgeable_groundtruth_similarity | 8622587 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We're looking for a way to standardize the entry of phone numbers entered in a form to be, for example, (444) 555-666. Right now you can enter it as any format, such as 4445556666 or 444-555-6666 and there's no standardization. I'd like a way for the number to be converted to the former format when it's entered into the database. Here is the HTML code for the form: <tr> <td align="right"> <label for="phone_number">Telephone:</label> </td> <td> <input type="text" name="phone_number" value="#form.phone_number#" /> </td></tr> This, along with all other data, is entered into the database using a cfquery INSERT INTO command. I can provide that code if needed. Here's an abbridged version: INSERT INTO Schedule_Registrations( phone_number)VALUES( '#FORM.phone_number#') Any thoughts on this would be appreciated.
Now provide the response and nothing else.
| The way I've chosen to deal with this issue is to store raw numbers in the database, and then display them how I want on a web page. To normalize the numbers, use a simple regex: <cfset cleanPhoneNumber = reReplace(form.phoneNumber, "[^0-9]", "", "ALL")> Store cleanPhoneNumber in the database, and then use a simple format function to display it: <cffunction name="formatPhoneNumber"> <cfargument name="phoneNumber" required="true"> <cfif len(phoneNumber) EQ 10> <!--- This only works with 10-digit US/Canada phone numbers ---> <cfreturn "(#left(phoneNumber, 3)#) #mid(phoneNumber, 4, 3)#-#right(phoneNumber, 4)#"> </cfif> <cfreturn phoneNumber></cffunction> The challenge is that outside the US there is not a standardized way to format numbers (that I've found). Also be careful if you allow a user to enter an extension in the phone number field. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8622587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/911075/']} | jdg_76210 |
stackexchange | llm_judgeable_groundtruth_similarity | 23979635 |
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 to grips with EF code first. My domain model design doesn't seem to support the auto 'populating' child of objects when I call them in code. Model: public class Car{ [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required,MaxLength(10)] public string Registration { get; set; } [MaxLength(30)] public string Make { get; set; } [MaxLength(45)] public string Model { get; set; } [Required] public Coordinates Coordinates { get; set; } [Required] public Client Client { get; set; } }public class Coordinates{ [Key, ForeignKey("Car")] public int Id { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } [Required] public Car Car { get; set; }} For example, I simply call: public List<Car> Get(){ var cars = _context.Cars.ToList(); return cars;} And my object contains all the Cars from the database, but doesn't include the Coordinates . The database seed created the data correctly, but I can't get EF to automatically reference Coordinates , or Client for that matter. But I suspect once we solve one, it'll resolve the other. What am I doing wrong, have I misunderstood how to do this?
Now provide the response and nothing else.
| You have a couple of choices here: To eagerly load related entities by telling EF to Include() them. For example you can load Cars including their Coordinates and Clients like this: public List<Car> Get(){ var cars = _context.Cars .Include(car => car.Coordinates) .Include(car => car.Client) .ToList(); return cars;} To lazy load related entities by declaring the navigation properties virtual thus telling EF to load them upon first access. Make sure you don't have disabled lazy loading for your context like this: this.Configuration.LazyLoadingEnabled = false; A short example would look like this: public class Car{ // ... the other properties like in your class definition above public virtual Coordinates Coordinates { get; set;}}public void Get(){ var cars = _context.Cars.ToList(); var coordinates = cars.First().Coordinates; // EF loads the Coordinates of the first car NOW!} Explicitly load related entities to the context. The context will then populate the navigation properties for you. Looks like this: public List<Car> Get(){ // get all cars var cars = _context.Cars.ToList(); // get all coordinates: the context will populate the Coordinates // property on the cars loaded above var coordinates = _context.Coordinates.ToList(); return cars;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23979635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719172/']} | jdg_76211 |
stackexchange | llm_judgeable_groundtruth_similarity | 26316237 |
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 my server to execute a node script every minute. The program executes perfectly if I execute the file manually ( ./main.js ), so I'm pretty sure it's not the problem. But when I hand it over to cron to execute, nothing happens. Here's the line from the cron file. */1 * * * * /home/bryce/scripts/wudu/main.js And here's a sample log: Oct 11 15:21:01 server CROND[2564]: (root) CMD (/home/bryce/scripts/wudu/main.js) The executable: home/bryce/scripts/wudu/main.js #!/usr/bin/env nodevar program = require('commander');var v = require('./cli/validation');var a = require('./cli/actions');program .version('0.0.1') .option('-u, --url', 'Register url') .option('-s, --selector', 'Register selector') .option('-p, --pagination', 'Register pagination') .option('-i, --index', 'Pass an index, to destroy') .parse(process.argv);var args = process.argv.slice(2), mode = v.mode(args[0]), options = v.hasArgs(mode, program);a.init(mode, options); Any idea why I'm getting radio silence? Somewhere else I should be looking to debug? UPDATE: I believe the problem has to do with my relative filepaths, and main.js being executed from outside its own directory. So now, I've placed exe.sh in the wudu directory. It looks like this: #!/bin/bashcd ${0%/*}./main.js mailexit Now, I've set cron to execute this file every minute. I tried executing this file from other folders, and it works as expected. But again, cron isn't picking it up.
Now provide the response and nothing else.
| Wrapping the execution in a shell script, it's likely the execution of the script in cron doesn't have the same environment set as when you run from the command line. Try prefacing the execution of the shell script in cron with setting NODE_PATH & PATH (if you need these values, on a command line type: echo $NODE_PATH and echo $PATH ) So, your cron entry would look like: */1 * * * * NODE_PATH=/usr/local/lib/node_modules PATH=/opt/local/bin:ABC:XYZ /home/bryce/scripts/wudu/exe.sh Just make sure to substitute the actual values for NODE_PATH & PATH with what you get from the echo commands that you first did. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26316237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2472219/']} | jdg_76212 |
stackexchange | llm_judgeable_groundtruth_similarity | 467968 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The family of all the permutations of a set $X$, denoted by $S_X$, is called thesymmetric group on $X$. When $X = \{1, 2, \dots , n\}$, $S_X$ is usually denoted by $S_n$, and it is called the symmetric group on $n$ letters.Notice that composition in $S_3$ is not commutative. Why is composition in $S_3$ not commutative?
Now provide the response and nothing else.
| Suppose\begin{align}f(1) & = 2 \\f(2) & = 1 \\f(3) & = 3\end{align}and\begin{align}g(1) & = 1 \\g(2) & = 3 \\g(3) & = 2\end{align} Then $f(g(1))=2$ and $g(f(1))=3$. So $f\circ g\ne g\circ f$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/467968', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90433/']} | jdg_76213 |
stackexchange | llm_judgeable_groundtruth_similarity | 38256104 |
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 essential difference(s) between pd.DataFrame.merge() and pd.concat() ? So far, this is what I found, please comment on how complete and accurate my understanding is: .merge() can only use columns (plus row-indices) and it is semantically suitable for database-style operations. .concat() can be used with either axis, using only indices, and gives the option for adding a hierarchical index. Incidentally, this allows for the following redundancy: both can combine two dataframes using the rows indices. pd.DataFrame.join() merely offers a shorthand for a subset of the use cases of .merge() (Pandas is great at addressing a very wide spectrum of use cases in data analysis. It can be a bit daunting exploring the documentation to figure out what is the best way to perform a particular task. )
Now provide the response and nothing else.
| A very high level difference is that merge() is used to combine two (or more) dataframes on the basis of values of common columns (indices can also be used, use left_index=True and/or right_index=True ), and concat() is used to append one (or more) dataframes one below the other (or sideways, depending on whether the axis option is set to 0 or 1). join() is used to merge 2 dataframes on the basis of the index; instead of using merge() with the option left_index=True we can use join() . For example: df1 = pd.DataFrame({'Key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})df1: Key data10 b 01 b 12 a 23 c 34 a 45 a 56 b 6df2 = pd.DataFrame({'Key': ['a', 'b', 'd'], 'data2': range(3)})df2: Key data20 a 01 b 12 d 2#Merge# The 2 dataframes are merged on the basis of values in column "Key" as it is # a common column in 2 dataframespd.merge(df1, df2) Key data1 data20 b 0 11 b 1 12 b 6 13 a 2 04 a 4 05 a 5 0#Concat# df2 dataframe is appended at the bottom of df1 pd.concat([df1, df2]) Key data1 data20 b 0 NaN1 b 1 NaN2 a 2 NaN3 c 3 NaN4 a 4 NaN5 a 5 NaN6 b 6 NaN0 a Nan 01 b Nan 12 d Nan 2 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38256104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1972495/']} | jdg_76214 |
stackexchange | llm_judgeable_groundtruth_similarity | 8497885 |
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 an application which aims to run only as a service (no interface, just run in background). I have no activity mentioned in my AndroidManifest.xml but put a receiver to start the application at phone start. <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <service android:enabled="true" android:name=".MyAppService"> <intent-filter> <action android:name = "me.myapp.MyAppService"> </action> </intent-filter> </service> <receiver android:enabled="true" android:name=".BootReceiver"> <intent-filter> <action android:name = "android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver></application> The problem is that as I'm developing (using Eclipse) the application, I need to test my changes often. When I run the application (with my phone connected in debug mode), I've got a message like [2011-12-14 00:18:40 - MyApp] Android Launch![2011-12-14 00:18:40 - MyApp] adb is running normally.[2011-12-14 00:18:40 - MyApp] No Launcher activity found![2011-12-14 00:18:40 - MyApp] The launch will only sync the application package on the device![2011-12-14 00:18:40 - MyApp] Performing sync How can I start the application at run, without having to restart it every time ? Edit this is not possible anymore for Android 3.1 or above. Source
Now provide the response and nothing else.
| Apart from the two options mentioned by EboMike: You can always send the BOOT_COMPLETED broadcast via the command line instead of rebooting your phone. Use adb shell am broadcast -a android.intent.action.BOOT_COMPLETED This will result in a situation like after an actual reboot, and will also trigger any 3rd party apps boot receivers. After typing it once in a terminal you can usually repeat it simply by pressing the up-arrow key followed by return on most operating systems. Or you can include it in a script thats triggered after reinstalling your app. If you want to limit the broadcast to your app only, you can also specify a component: adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -n your.app.packagename/.YourReceiverClassName This sends the reboot broadcast only to your receiver. All other apps are not called. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8497885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147904/']} | jdg_76215 |
stackexchange | llm_judgeable_groundtruth_similarity | 1331895 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A friend of mine was trying to test me on C (my strongest language is C++) and he asked me three questions which I could not answer: Try to explain the following declarations: 1) int (*x)(int, char *, void *);2) int (*x[10])(int, char *, void *);3) int (**x[10])(int, char *, void *); Can anyone explain these function declarations and explain what concepts are being used?
Now provide the response and nothing else.
| Well, the first one is a pointer to a function. In other words, it declares a variable "x" which points to a function of the following type: int function(int, char*, void*); And could be used as follows: int myfunc(int a, char* b, void* c) { return a;}void acallingfunction() { int (*x)(int, char*, void*); x = myfunc; x(1, "hello", 0);} The second appears to be invalid syntax, but I may be wrong. If it had an asterisk before the x (such as int (*x[10])(int, char*, void*) ), it would be an array of function pointers, and would be used like a normal array: x[3](1, "Hi there", 0); The third is an array of pointers to function pointers, which doesn't seem practical, but is perfectly valid. An example usage might be: void anothercaller() { int (*x)(int, char*, void*); int (**y)(int, char*, void*); x = myfunc; y = &x; (*y)(1, "hello", 0);} Note that of these, the first two are relatively common. Pointers to functions are used to accomplish callbacks and various Object-Oriented programming concepts in C. An array of pointers to functions might be used for an event table, to find the appropriate callback. Note that all of those are, in fact, valid C++ as well. ;) Edit: I committed the atrocities of void main() apparently. Edit 2: As Chris Lutz points out below, they really should be wrapped in typedefs. Typedefs make code containing pointers to functions MUCH clearer. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1331895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90871/']} | jdg_76216 |
stackexchange | llm_judgeable_groundtruth_similarity | 17533 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For my C# app, I don't want to always prompt for elevation on application start, but if they choose an output path that is UAC protected then I need to request elevation. So, how do I check if a path is UAC protected and then how do I request elevation mid-execution?
Now provide the response and nothing else.
| The best way to detect if they are unable to perform an action is to attempt it and catch the UnauthorizedAccessException . However as @ DannySmurf correctly points out you can only elevate a COM object or separate process. There is a demonstration application within the Windows SDK Cross Technology Samples called UAC Demo . This demonstration application shows a method of executing actions with an elevated process. It also demonstrates how to find out if a user is currently an administrator. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1147/']} | jdg_76217 |
stackexchange | llm_judgeable_groundtruth_similarity | 83469 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Mathematica can do a Cholesky decomposition $\mathbf A = \mathbf L\mathbf L^\top$, but how do I do a LDL decomposition $\mathbf A = \mathbf L\mathbf D\mathbf L^\top$, with $\mathbf L$ being a unit lower triangular matrix?
Now provide the response and nothing else.
| I needed this decomposition to answer another question, so I broke down and implemented it myself. The code is more or less a straightforward translation of the pseudocode in Golub/Van Loan : LDLT[mat_?SymmetricMatrixQ] := Module[{n = Length[mat], mt = mat, v, w}, Do[ If[j > 1, w = mt[[j, ;; j - 1]]; v = w Take[Diagonal[mt], j - 1]; mt[[j, j]] -= w.v; If[j < n, mt[[j + 1 ;;, j]] -= mt[[j + 1 ;;, ;; j - 1]].v]]; mt[[j + 1 ;;, j]] /= mt[[j, j]], {j, n}]; {LowerTriangularize[mt, -1] + IdentityMatrix[n], Diagonal[mt]}] A few tests: m1 = HilbertMatrix[20];m2 = Array[Min, {20, 20}];{l1, d1} = LDLT[m1];m1 == l1.DiagonalMatrix[d1].Transpose[l1] True{l2, d2} = LDLT[m2];m2 == l2.DiagonalMatrix[d2].Transpose[l2] True | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/83469', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5794/']} | jdg_76218 |
stackexchange | llm_judgeable_groundtruth_similarity | 26570626 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've written a JavaScript program that calculates the depth of a binary tree based on the number of elements. My program has been working fine for months, but recently I've found a difference when the web page is viewed in Chrome vs Firefox. In particular, on Firefox: Math.log2(8) = 3 but now in Chrome: Math.log2(8) = 2.9999999999999996 My JavaScript program was originally written to find the depth of the binary tree based on the number of elements as: var tree_depth = Math.floor(Math.log2(n_elements)) + 1; I made a simple modification to this formula so that it will still work correctly on Chrome: var epsilon = 1.e-5;var tree_depth = Math.floor(Math.log2(n_elements) + epsilon) + 1; I have 2 questions: Has anyone else noticed a change in the precision in Chrome recently for Math.log2 ? Is there a more elegant modification than the one I made above by adding epsilon?
Now provide the response and nothing else.
| Note: Math.log2 hasn't actually changed since it's been implementedin V8. Maybe you remembered incorrectly or you had included a shim thathappened to get the result correct for these special cases before Chromeincluded its own implementation of Math.log2 . Also, it seems that you should be using Math.ceil(x) rather than Math.floor(x) + 1 . How can I solve this? To avoid relying on Math.log or Math.log2 being accurate amongst different implementations of JavaScript (the algorithm used is implementation-defined), you can use bitwise operators if you have less than 2 32 elements in your binary tree. This obviously isn't the fastest way of doing this (this is only O(n)), but it's a relatively simple example: function log2floor(x) { // match the behaviour of Math.floor(Math.log2(x)), change it if you like if (x === 0) return -Infinity; for (var i = 0; i < 32; ++i) { if (x >>> i === 1) return i; }}console.log(log2floor(36) + 1); // 6 How is Math.log2 currently implemented in different browsers? The current implementation in Chrome is inaccurate as they rely on multiplying the value of Math.log(x) by Math.LOG2E , making it susceptible to rounding error ( source ): // ES6 draft 09-27-13, section 20.2.2.22.function MathLog2(x) { return MathLog(x) * 1.442695040888963407; // log2(x) = log(x)/log(2).} If you are running Firefox, it either uses the native log2 function (if present), or if not (e.g. on Windows ), uses a similar implementation to Chrome ( source ). The only difference is that instead of multiplying, they divide by log(2) instead: #if !HAVE_LOG2double log2(double x){ return log(x) / M_LN2;}#endif Multiplying or dividing: how much of a difference does it make? To test the difference between dividing by Math.LN2 and multiplying by Math.LOG2E , we can use the following test: function log2d(x) { return Math.log(x) / Math.LN2; }function log2m(x) { return Math.log(x) * Math.LOG2E; }// 2^1024 rounds to Infinityfor (var i = 0; i < 1024; ++i) { var resultD = log2d(Math.pow(2, i)); var resultM = log2m(Math.pow(2, i)); if (resultD !== i) console.log('log2d: expected ' + i + ', actual ' + resultD); if (resultM !== i) console.log('log2m: expected ' + i + ', actual ' + resultM);} Note that no matter which function you use, they still have floating point errors for certain values 1 . It just so happens that the floating point representation of log(2) is less than the actual value, resulting in a value higher than the actual value (while log2(e) is lower). This means that using log(2) will round down to the correct value for these special cases. 1: log(pow(2, 29)) / log(2) === 29.000000000000004 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26570626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/877314/']} | jdg_76219 |
stackexchange | llm_judgeable_groundtruth_similarity | 1931 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In a small office with 5-10 WAPs, do you create distinct SSIDs for each WAP, or do you name each one the same? Recently I have been deploying multiple WAPs configured with the same SSID and password, and leaving it to the client computer to decide which WAP provides the best coverage, and have had good luck with this. How can I deploy multiple APs in the same office without a centralized WLC?
Now provide the response and nothing else.
| You certainly can do without a controller. A number of vendors either provide management software with the purchase of the AP or have products that are designed to run without one. You can choose from Cisco, Aruba, Aerohive, Meraki (now Cisco), Ubiquiti and quite a few others (supposedly Meru has a solution soon to launch as well) for solutions that work without a controller. As for single SSID or multiple, that is really up to a design choice, but generally speaking you would want to only provide one for roaming if you do mobile computing. Wireless clients have been getting better about making good choices when presented with multiple wireless access points, with some notable exceptions (Apple devices seem to still have some issues periodically). If mobility isn't a concern and you are largely dealing with nomadic (i.e. they may move, but are used almost entirely in one position)or stationary clients, then you can balance your clients in several ways with unique SSIDs. However managing the clients and educating users can be troublesome if you don't put some thought into it. Controllers largely help with the management, reporting and coordination (and sometimes troubleshooting) of the wireless network. While they are nice to have, they are by no means essential for general wireless. If you are looking to do something more complex or that requires a higher class of service (such as wireless-VoIP), then you should look into a controller based solution. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/1931', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/1352/']} | jdg_76220 |
stackexchange | llm_judgeable_groundtruth_similarity | 10234201 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i was looking to find a solution for this problem but seems difficult. I have appengine project working with a servlet that handle registration. When i try to call this servlet i have this log report: 012-04-19 10:31:06.816 /register 500 90ms 0kb Apache-HttpClient/UNAVAILABLE (java 1.4)ip - gecodroidtest [19/Apr/2012:10:31:06 -0700] "POST /register HTTP/1.1" 500 0 - "Apache-HttpClient/UNAVAILABLE (java 1.4)" "cloudnotifyit.appspot.com" ms=90 cpu_ms=58 api_cpu_ms=0 cpm_usd=0.001738 instance=00c61b117c772731eb45290bfcb07750c0505fW 2012-04-19 10:31:06.794com.cloudnotify.server.servlet.RequestInfo processRequest: xxxxxxxxxxxx@xxxx //just for meW 2012-04-19 10:31:06.810Error for /register java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.apache.xerces.parsers.AbstractDOMParser.startDocument(Unknown Source) at org.apache.xerces.impl.dtd.XMLDTDValidator.startDocument(Unknown Source) at org.apache.xerces.impl.XMLDocumentScannerImpl.startEntity(Unknown Source) at org.apache.xerces.impl.XMLVersionDetector.startDocumentParsing(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121) at javax.jdo.JDOHelper.readNamedPMFProperties(JDOHelper.java:1407) at javax.jdo.JDOHelper.getNamedPMFProperties(JDOHelper.java:1286) at javax.jdo.JDOHelper.getPropertiesFromJdoconfig(JDOHelper.java:1232) at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:1079) at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:914) at com.cloudnotify.server.c2dm.C2DMessaging.getPMF(C2DMessaging.java:103) at com.cloudnotify.server.servlet.RequestInfo.initDevices(RequestInfo.java:225) at com.cloudnotify.server.servlet.RequestInfo.processRequest(RequestInfo.java:183) at com.cloudnotify.server.servlet.RegisterServlet.doPost(RegisterServlet.java:100) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455) at com.google.tracing.TraceContext.runInContext(TraceContext.java:695) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453) at java.lang.Thread.run(Thread.java:679)Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ElementTraversal at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java) ... 44 moreC 2012-04-19 10:31:06.812Uncaught exception from servletjava.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.apache.xerces.parsers.AbstractDOMParser.startDocument(Unknown Source) at org.apache.xerces.impl.dtd.XMLDTDValidator.startDocument(Unknown Source) at org.apache.xerces.impl.XMLDocumentScannerImpl.startEntity(Unknown Source) at org.apache.xerces.impl.XMLVersionDetector.startDocumentParsing(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121) at javax.jdo.JDOHelper.readNamedPMFProperties(JDOHelper.java:1407) at javax.jdo.JDOHelper.getNamedPMFProperties(JDOHelper.java:1286) at javax.jdo.JDOHelper.getPropertiesFromJdoconfig(JDOHelper.java:1232) at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:1079) at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:914) at com.cloudnotify.server.c2dm.C2DMessaging.getPMF(C2DMessaging.java:103) at com.cloudnotify.server.servlet.RequestInfo.initDevices(RequestInfo.java:225) at com.cloudnotify.server.servlet.RequestInfo.processRequest(RequestInfo.java:183) at com.cloudnotify.server.servlet.RegisterServlet.doPost(RegisterServlet.java:100) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455) at com.google.tracing.TraceContext.runInContext(TraceContext.java:695) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453) at java.lang.Thread.run(Thread.java:679)Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ElementTraversal at com.google.appengine.runtime.Request.process-240c2ffe1bf8ddba(Request.java) ... 44 moreThanks all
Now provide the response and nothing else.
| MAVEN SOLUTION: At pom.xml , set "xml-apis" dependency to version 1.4.01: <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.4.01</version></dependency> SOLUTION FOR EVERYONE ELSE: If not using maven, you can manually add the xml-apis library, version 1.4.01. You will find the jars inside the xml-commons binary package, named "XML Commons External 1.4.01", and you can download it here: http://xerces.apache.org/mirrors.cgi . Finally, compile and execute your java application/project with this version of the library. Explanation : The 1.4.01 version of the xml-apis library, includes the required ElementTraversal class. Other versions like 2.0.0, 1.0.0, etc. do not include it, and the application fails while compiling. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10234201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1344683/']} | jdg_76221 |
stackexchange | llm_judgeable_groundtruth_similarity | 1427722 |
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 requirement to create jar files with Maven, but they need to be installed to the repository with a "foobar" extension , and it would be nice if they could have their own packaging type so we can identify those artifacts by the packaging. Can I set up a new packaging type to do this?
Now provide the response and nothing else.
| To do as you described, create a Maven project with packaging jar (as stated here , as there won't be mojo definitions). In the src/main/resources/META-INF/plexus sub-folder create a components.xml with the following contents (assuming you want the packaging type to be "my-custom-type", change it to "foobar" if you wish). <component-set> <components> <component> <role>org.apache.maven.lifecycle.mapping.LifecycleMapping</role> <role-hint>my-custom-type</role-hint> <implementation> org.apache.maven.lifecycle.mapping.DefaultLifecycleMapping </implementation> <configuration> <phases> <!--use the basic jar lifecycle bindings, add additional executions in here if you want anything extra to be run--> <process-resources> org.apache.maven.plugins:maven-resources-plugin:resources </process-resources> <package> org.apache.maven.plugins:maven-jar-plugin:jar </package> <install> org.apache.maven.plugins:maven-install-plugin:install </install> <deploy> org.apache.maven.plugins:maven-deploy-plugin:deploy </deploy> </phases> </configuration> </component> <component> <role>org.apache.maven.artifact.handler.ArtifactHandler</role> <role-hint>my-custom-type</role-hint> <implementation> org.apache.maven.artifact.handler.DefaultArtifactHandler </implementation> <configuration> <!--the extension used by Maven in the repository--> <extension>foobar</extension> <!--the type used when specifying dependencies etc.--> <type>my-custom-type</type> <!--the packaging used when declaring an implementation of the packaging--> <packaging>my-custom-type</packaging> </configuration> </component> </components></component-set> Then in a pom that is to have the custom packaging, declare the required type in the packaging element, and ensure you have specified the plugin so the custom packaging can be contributed. Declaring <extensions>true</extensions> tells Maven that the plugin contributes packaging and/or type handlers to Maven. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>name.seller.rich</groupId> <artifactId>test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>my-custom-type</packaging> <build> <plugins> <plugin> <groupId>name.seller.rich.maven.plugins</groupId> <artifactId>maven-foobar-plugin</artifactId> <version>0.0.1</version> <!--declare that this plugin contributes the component extensions--> <extensions>true</extensions> </plugin> </plugins> </build> </project> When the project is packaged, it will be a jar, with a .jar extension, however when it is installed/deployed, Maven will deliver the file to the repository with the ".foobar" extension as specified in components.xml | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1427722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148419/']} | jdg_76222 |
stackexchange | llm_judgeable_groundtruth_similarity | 6990781 |
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 invoke a jar, but I don't see any output when I run the command without args, and when I do run with args, I get the following error: [ant:java] The args attribute is deprecated. Please use nested arg elements.[ant:java] Java Result: 1 How do I invoke ant.java in such a way that I see output and can pass arguments? task compressJs(){ ant.java(jar:"lib/yuicompressor-2.4.6.jar",fork:true,args:['js/file.js', '-o', 'build/js/file.js'])}
Now provide the response and nothing else.
| Your args should be specified like this: ant.java(jar:"lib/yuicompressor-2.4.6.jar",fork:true) { arg(value: "js/file.js") arg(value: "-o") arg(value: "build/js/file.js")} Pretty much it is the same as you would do with ant except using the Groovy style markup builder instead of XML. By default your output will go to the screen. If you want to redirect it, set the 'output' property. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6990781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78182/']} | jdg_76223 |
stackexchange | llm_judgeable_groundtruth_similarity | 41079335 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm building a PHP website where I would like to put a captcha on the login form. I went with Google's new Invisible reCaptcha but I'm having trouble with implementing it (HTML part, the PHP is working). The code I've got now for the "normal" reCaptcha is the following (as according to the Google reCaptcha instructions and this works): <form action=test.php method="POST"> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <!-- <Google reCaptcha> --> <div class="g-recaptcha" data-sitekey="<sitekey>"></div> <!-- </Google reCaptcha> --> <input type="submit" name="login" class="loginmodal-submit" value="Login"></form> There were some instructions sent in the confirmation email when I signed up (took about 24 hours to get the confirmation). That says the following: Invisible reCAPTCHA Integration If you haven’t integrated your site with reCAPTCHA v2, please follow our developer guide for implementation details. Please make sure that your site key that has been whitelisted for Invisible reCAPTCHA. To enable the Invisible reCAPTCHA, rather than put the parameters in a div, you can add them directly to an html button. 3a. data-callback=””. This works just like the checkbox captcha, but is required for invisible. 3b. data-badge: This allows you to reposition the reCAPTCHA badge (i.e. logo and ‘protected by reCAPTCHA’ text) . Valid options as ‘bottomright’ (the default), ‘bottomleft’ or ‘inline’ which will put the badge directly above the button. If you make the badge inline, you can control the CSS of the badge directly. Verifying the user’s response has no changes. The problem I have is with the HTML implementation (therefore I need help with step 3. 1,2 and 4 is working for me). The rest I have working with normal reCaptcha and according to the instructions, it should be the same thing. I do not understand what the data-callback and data-badge is and how it works. A code example of how to implement invisible reCaptcha with how my form is setup would be great!
Now provide the response and nothing else.
| Invisible reCAPTCHA Implementing Google's new Invisible reCAPTCHA is very similar to how we add v2 to our site. You may add it as its own container like normal, or the new method of adding it to the form submit button. I hope this guide will help you along the correct path. Standalone CAPTCHA Container Implementing recaptcha requires a few things: - Sitekey- Class- Callback- Bind This will be your final goal. <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"> </div> When using the standalone method, you must have data-bind set to the ID of your submit button. If you do not have this set, your captcha will not be invisible. A callback must also be used to submit the form. An invisible captcha will cancel all events from the submit button, so you need the callback to actually pass the submission on. <script>function submitForm() { var form = document.getElementById("ContactForm"); if (validate_form(form)) { form.submit(); } else { grecaptcha.reset(); }}</script> Notice in the example callback that there is also custom form validation. It is very important that you reset the reCAPTCHA when the validation fails, otherwise you will not be able to re-submit the form until the CAPTCHA expires. Invisible CAPTCHA Button A lot of this is the same as with the standalone CAPTCHA above, but instead of having a container, everything is placed on the submit button. This will be your goal. <button class="g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit"> Submit</button> There's something new here, data-badge. This is a div that gets inserted into the DOM that contains the inputs required for reCAPTCHA to function. It has three possible values: bottomleft, bottomright, inline. Inline will make it display directly above the submit button, and allow you to control how you would like it to be styled. On to your question <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"></div> <input type="submit" name="login" class="loginmodal-submit" id="recaptcha-submit" value="Login"></form> Or <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button class="loginmodal-submit g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit" value="Login">Submit</button></form> I hope this helps you and future coders. I'll keep this up-to-date as the technology evolves. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41079335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4430319/']} | jdg_76224 |
stackexchange | llm_judgeable_groundtruth_similarity | 3339147 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The following appears as an exercise in Bourbaki, Commutative Algebra , Chapter I, Exercises §3, n°1 (and other books). Consider a family of $R$ -modules $(M_i)_{i\in I}$ ( $R$ and $I$ arbitrary). We wish to show that $\bigoplus_{i\in I}M_i$ is faithfully flat iff all the $M_i$ are flat and at least one of them is faithfully flat. A direct sum of modules is flat iff their summands are flat. Thus the if part follows from the fact that tensor products commute with direct sums. The only if part is where I am stuck. My attempt goes with reductio ad absurdum: suppose none of the $M_i$ are faithfully flat, so there are for every $i\in I$ a non-zero module $N_i$ such that $M_i\otimes_R N_i=0$ . From this, I'd try and build a non-zero module $N$ st $N\otimes_R\bigoplus_{i\in I}M_i = 0$ , but I'm lacking ideas for such a candidate $N$ . Even for $I$ reduced to 2 elements isn't obvious to me. Is such an $N$ easy to find, or is there another way of going about this? Any suggestion is welcome. Thank you.
Now provide the response and nothing else.
| Note: First of all note that if $R$ is any commutative ring. For any prime ideal $P$ of $R$ , the localization $R_P$ is flat $R$ -module. Set $P := \bigoplus_{P\in Spec(R)} R_P$ is also flat. We claim that $P$ is faithfully flat. Indeed, if $M$ is any $R$ -module such that $P \otimes M = 0$ , then $$0 = (\bigoplus_{P\in Spec(R)} R_P)\otimes M = \bigoplus_{P\in Spec(R)} (R_P\otimes M) = \bigoplus_{P\in Spec(R)} M_P.$$ Then each localization $M_P = 0$ . It is well known that this implies that $M = 0$ , so $P$ is faithfully flat $R$ -module. (Note that some of above equalities are actualy isomorphism) Example: Set $R:= \mathbb{Z}$ and $P := (p)$ where p is a prime, then for any prime $l\ne p$ , the nonzero $\mathbb{Z}$ -module $\mathbb{Z}/l \mathbb{Z}$ localizes to zero with respect to $P$ . If $P = (0)$ , any torsion $\mathbb{Z}$ -module localizes to zero with respect to $P$ . This shows that no $\mathbb{Z}_P$ is faithfully flat over $\mathbb{Z}$ . But by above note $$P := \bigoplus_{P\in Spec(\mathbb{Z})} \mathbb{Z}_P$$ is faithfully flat over $\mathbb{Z}$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3339147', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/231098/']} | jdg_76225 |
stackexchange | llm_judgeable_groundtruth_similarity | 4755991 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to know the optimal way of writing/reading DateTime into/from XML. Should I directly write DateTime into XML or DateTime.ToString() into XML? Second question is how to read the date element from XML. Can casting be used for this? Eg: (DateTime)rec.Element("Date").value Or, do I need to parse the string like this? Eg: DateTime.Parse(rec.Element("Date").value)
Now provide the response and nothing else.
| You can use casting of an XElement or XAttribute with LINQ to XML, yes... but not of the string itself. LINQ to XML uses the standard XML format, independent of your culture settings. Sample: using System;using System.Xml.Linq;class Test{ static void Main() { DateTime now = DateTime.Now; XElement element = new XElement("Now", now); Console.WriteLine(element); DateTime parsed = (DateTime) element; Console.WriteLine(parsed); }} Output for me: <Now>2011-01-21T06:24:12.7032222+00:00</Now>21/01/2011 06:24:12 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4755991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570928/']} | jdg_76226 |
stackexchange | llm_judgeable_groundtruth_similarity | 4242035 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I check if the request is a post back in PHP, is the below ok? if (isset($_POST["submit"])) where submit is the name of the <input type="submit" />
Now provide the response and nothing else.
| That will work if you know and expect such a submit button on the same page. If you don't immediately know anything about the request variables, another way is to check the request method: if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') As pointed out in the comments, to specifically check for a postback and not just any POST request, you need to ensure that the referrer is the same page as the processing page. Something like this: if (basename($_SERVER['HTTP_REFERER']) == $_SERVER['SCRIPT_NAME']) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4242035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292291/']} | jdg_76227 |
stackexchange | llm_judgeable_groundtruth_similarity | 28203248 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Below I have a screenshot of a query in MS Access. I am trying to combine the two "Kim Wong" rows into one row that has one time range in the Monday column and the other time range in the Tuesday column. There will when done have time ranges in each of the cells. Here is what the query looks like. And here is the actual code SELECT qryEmployed.EmployeeName, First(IIf([EventDate]=DateAdd("d",0,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Monday, First(IIf([EventDate]=DateAdd("d",1,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Tuesday, First(IIf([EventDate]=DateAdd("d",2,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Wednesday, First(IIf([EventDate]=DateAdd("d",3,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Thursday, First(IIf([EventDate]=DateAdd("d",4,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Friday, First(IIf([EventDate]=DateAdd("d",5,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS Saturday, First(IIf([EventDate]=DateAdd("d",6,[Forms]![tblEvents]![tbxDate]),IIf([Event]="Scheduled",Format([StartTime],"h:nn") & " - " & Format([EndTime],"h:nn"),[Event]),"")) AS SundayFROM tblEvents INNER JOIN qryEmployed ON tblEvents.Employee = qryEmployed.EmployeeNameGROUP BY qryEmployed.EmployeeName, qryEmployed.Position, tblEvents.Event, tblEvents.EventDate, tblEvents.StartTime, tblEvents.EndTime, tblEvents.Lunch, IIf([Event]="Scheduled",((IIf([EndTime]<[StartTime],1,0)+[EndTime])-[StartTime]-IIf([Lunch],1/48,0))*24,0)HAVING (((tblEvents.EventDate)=DateAdd("d",0,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",1,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",2,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",3,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",4,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",5,[Forms]![tblEvents]![tbxDate]))) OR (((tblEvents.EventDate)=DateAdd("d",6,[Forms]![tblEvents]![tbxDate]))); Here is a sample of tblEmployees . Here is the qryEmployed . And here is the tblEvents .
Now provide the response and nothing else.
| The type new Comparator(){} must implement the inherited abstract method Comparator.reversed() then if I apply the fix, I have many functions added Comparator.reversed was introduced in Java 1.8 and it's a default method i.e. a method that you don't have to override. It seems like you have your compliance level set to pre Java 1.8 (since Eclipse asks you to override reversed ), while using Java 1.8 API (since Comparator has a reversed method). Make sure you either change your API to 1.7 or change your compliance level to 1.8 . (The latter option requires Eclipse Luna or better.) More on Eclipse compliance level: What is "compiler compliance level" in Eclipse? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28203248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1406732/']} | jdg_76228 |
stackexchange | llm_judgeable_groundtruth_similarity | 2579253 |
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: Suppose $u,v\in V$ and that $\phi(u)=0$ implies that $\phi(v)=0$ for all $\phi\in V^{*}$, which is the dual of $V$ then show that $v=ku$ for some scalar $k.$ My Attempt: I tried doing this by contrapositive. Suppose $v\not =ku$ then we can say that for every scalar $k$ there exists a non-zero vector $b$ such that $v=ku+b.$ In this case we get that $\phi(v)=\phi(b).$ Now if we set $\phi(b)=t,$ where $t\not =0$ then $\phi(v)\not =0$ Thus we have found a linear functional $\phi$ such that $\phi(u)=0$ but $\phi(v)\not =0.$ PS: The way I negated the first claim was as follows: If $A:=\forall \phi \in V^{*}(\phi(u)=0\implies \phi(v)=0)$ then $\neg A:=\exists\phi\in V^{*}(\phi(u)=0\land\phi(v)\not =0).$ Is this proof correct?
Now provide the response and nothing else.
| Let $F(a)$ be given by the integral $$F(a)=\int_{-\infty}^\infty \frac{e^{-ax^2}}{1+x^2}\,dx$$ for $a>0$. Then the derivative $F'(a)$ of $F(a)$ is $$\begin{align}F'(a)&=-\int_{-\infty}^\infty \frac{x^2e^{-ax^2}}{1+x^2}\,dx\\\\&=F(a)-\int_{-\infty}^\infty e^{-ax^2}\,dx\\\\&=F(a)-\sqrt{\frac{\pi}{a}}\end{align}$$ Hence, $F(a)$ satisfies the ODE $F'(a)-F(a)=-\sqrt{\frac{\pi}{a}}$ subject to $F(0)=\pi$. Solution to that ODE can be written $$\begin{align}F(a)&=e^a \left(\pi -\sqrt \pi \int_0^a \frac{e^{-x}}{\sqrt x}\,dx\right)\\\\&=e^a\left(\pi -\pi \frac{2}{\sqrt \pi}\int_0^{\sqrt a}e^{-x^2}\,dx\right)\\\\&=\pi e^a \left(1-\text{erf}(\sqrt a)\right)\\\\&=\pi e^a \text{erfc}(\sqrt a)\end{align}$$ where $\text{erf(x)}=\frac2{\sqrt \pi}\int_0^x e^{-t^2}\,dt$ is the error function and $\text{erfc}(x)=\frac2{\sqrt \pi}\int_x^\infty e^{-t^2}\,dt=1-\text{erf}(x)$ is the complementary error function. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2579253', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/255452/']} | jdg_76229 |
stackexchange | llm_judgeable_groundtruth_similarity | 33126156 |
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 large Ansible playbook where Docker images are built when running it. I am using an increasing number as the tag to version them. Currently, I have to specify this in every hosts: section. I know there are global variables but from what I found by searching for "ansible" "global variables", they have to defined outside of the playbook. Is it possible to define global variables which are global for the playbook?
Now provide the response and nothing else.
| If the tag/version you are using is applicable to all hosts, then using group_vars/all is a viable option. If the revision numbers are specific to each host entries in a host_vars/host_name file might be better. If you want to read and initial var and then increment it after each play that becomes a bit more difficult to persist that information across plays (or each -hosts as you say) in the playbook. For example if you were looking to deploy N docker instances you might do some dynamic inventory magic like this: - hosts: localhost tasks: - add_host: name=docker_{{item}} groups="dockers,other" tag={{item}} with_sequence: start={{ext_def_start}} count={{ext_def_num}}- hosts: docker_* tasks: - debug: var=tag | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33126156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1474073/']} | jdg_76230 |
stackexchange | llm_judgeable_groundtruth_similarity | 36046155 |
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 almost completely new to Rails, or I am sure I would know how to answer this question myself. I am just trying to modify the basic chat app created in the basic ActionCable demo: https://medium.com/@dhh/rails-5-action-cable-demo-8bba4ccfc55e#.6lmd6tfi7 Instead of having just one chat room, I want to have multiple chat rooms, so I modified my routes.rb by adding this line: get '/rooms/show/:topic', to: 'rooms#show' So now I can visit different chat rooms based on different topics. The rooms controller at /app/controllers/rooms_controller.rb handles these routes with no problem: class RoomsController < ApplicationController def show @topic = params[:topic] @messages = Message.all endend But this parameter is not being passed to app/channels/room_channel.rb , and I'm just not sure what modifications I need to make. My current attempt: class RoomChannel < ApplicationCable::Channel def subscribed stream_from "room_channel_#{params[:topic]}" end only returns "room_channel_"
Now provide the response and nothing else.
| The problem here was that I failed to understand from where the subscribed method was being called, and thus did not know how to pass parameters to it. By reading the actioncable documentation: https://github.com/rails/rails/tree/master/actioncable I found out that the subscribed method is called via client-side javascript, not by the rails controller. In the case of the example chat app, this means I had to change the first line of the file /app/assets/javascripts/channels/room.coffee App.room = App.cable.subscriptions.create "RoomChannel", to App.room = App.cable.subscriptions.create { channel: "RoomChannel", topic: topic}, Passing a javascript object to this method allowed me to access those parameters in the subscribed method of rooms_controller.rb . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36046155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/757550/']} | jdg_76231 |
stackexchange | llm_judgeable_groundtruth_similarity | 13853844 |
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 Angular and I'm stuck with a issue relating IE. Here is the IE Error that I'm getting. Webpage error detailsUser Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)Timestamp: Thu, 13 Dec 2012 04:00:46 UTCMessage: 10 $digest() iterations reached. Aborting!Watchers fired in the last 5 iterations: [["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 7; oldVal: 6"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 8; oldVal: 7"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 9; oldVal: 8"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 10; oldVal: 9"],["fn: function $locationWatch() {\n var oldUrl = $browser.url();\n\n if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t defaultPrevented) {\n\t $location.$$parse(oldUrl);\n\t } else {\n\t $browser.url($location.absUrl(), $location.$$replace);\n\t $location.$$replace = false;\n\t afterLocationChange(oldUrl);\n\t }\n\t});\n }\n\n return changeCounter;\n }; newVal: 11; oldVal: 10"]]Line: 7859Char: 6Code: 0URI: http://localhost:8080/__assets__/lib/angular/angular.js This is not happening in any other browser but IE 8 and IE 9. I have a watch looking at a content filtering object which includes a location filter. My question with this is why doesn't it happen on any other browser but IE and what should I do to get rid of this. Thanks in advance.
Now provide the response and nothing else.
| I had the same issue with error which looked the same. Chrome\FF worked fine, but IE failed. I've clicked on some links in my app and sometimes got this error and sometimes not. 1) In my view I had few links which looked like this: <a href="#" ng-click="addIP(ip)">Add some IP</a> 2) Click handler for those links added new object into IpRanges collection like this: $scope.IpRanges.push(ip); 3) Collection itself was binded on view by ng-repeat, and I thought that somehow IE could not handle this situation well - probably order of binding\adding\applying events wasn't incorrect or else... Also after click on links I had # symbol added to url, and sometimes it blinked, and then I've got an error. So I removed href attribute and everything worked fine: <a href="" ng-click="addCurrentIP()">Add as allowed IP</a> Probably it's better to use spans or divs for similar situations. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13853844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1262123/']} | jdg_76232 |
stackexchange | llm_judgeable_groundtruth_similarity | 4564621 |
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 place an icon left of the two lines of text such that there's about 2-3 pixels of space between the image and the start of text. The control itself is Center aligned horizontally (set through Interface Builder) The button would resemble something like this: | ||[Image] Add To || Favorites | I'm trying to configure this with contentEdgeInset, imageEdgeInsets and titleEdgeInsets to no avail. I understand that a negative value expands the edge while a positive value shrinks it to move it closer to the center. I tried: [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -image.size.width, 0, 0)];[button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width, 0, 0)]; but this doesn't display it correctly. I've been tweaking the values but going from say -5 to -10 on the left inset value doesn't appear to move it in expected manner. -10 will scoot the text all the way to the left so I expected -5 to scoot it half way from the left side but it doesn't. What's the logic behind insets? I'm not familiar with image placements and related terminology. I used this SO question as a reference but something about my values isn't right. UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?
Now provide the response and nothing else.
| I agree the documentation on imageEdgeInsets and titleEdgeInsets should be better, but I figured out how to get the correct positioning without resorting to trial and error. The general idea is here at this question , but that was if you wanted both text and image centered. We don't want the image and text to be centered individually, we want the image and the text to be centered together as a single entity. This is in fact what UIButton already does so we simply need to adjust the spacing. CGFloat spacing = 10; // the amount of spacing to appear between image and titletabBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);tabBtn.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0); I also turned this into a category for UIButton so it will be easy to use: UIButton+Position.h @interface UIButton(ImageTitleCentering)-(void) centerButtonAndImageWithSpacing:(CGFloat)spacing;@end UIButton+Position.m @implementation UIButton(ImageTitleCentering)-(void) centerButtonAndImageWithSpacing:(CGFloat)spacing { self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing); self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);}@end So now all I have to do is: [button centerButtonAndImageWithSpacing:10]; And I get what I need every time. No more messing with the edge insets manually. EDIT: Swapping Image and Text In response to @Javal in comments Using this same mechanism, we can swap the image and the text. To accomplish the swap, simply use a negative spacing but also include the width of the text and the image. This will require frames to be known and layout performed already. [self.view layoutIfNeeded];CGFloat flippedSpacing = -(desiredSpacing + button.currentImage.size.width + button.titleLabel.frame.size.width);[button centerButtonAndImageWithSpacing:flippedSpacing]; Of course you will probably want to make a nice method for this, potentially adding a second category method, this is left as an exercise to the reader. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4564621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/378510/']} | jdg_76233 |
stackexchange | llm_judgeable_groundtruth_similarity | 2747199 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
//always works, returning a valid object into _page _page = _httpContext.Handler as System.Web.UI.Page;//Fails throwing the exception : Unable to cast object of type 'System.Web.DefaultHttpHandler' to type 'System.Web.UI.Page' _page = (System.Web.UI.Page)_httpContext.Handler; I would like to know why this happens? EDIT: //Fixes the problem if(_httpContext.Handler is System.Web.UI.Page) _page = (System.Web.UI.Page)_httpContext.Handler; If i debug the 'as' keyword statement, i never get a null reference (object always assigned properly). However the () cast creates exceptions unless it has the if statment. EDIT: After about 15 runs through the class i was able to get a null. Seems like it took more runs to find a null compared to how fast the () cast would catch an exception. OLD: When there is a debug at the 'as' statement every time the class runs the break point hits - never null. When tthere is a debug in the '()' statement within the if, every time the break point hits the cast works properly. Werid
Now provide the response and nothing else.
| //always works, returning a valid object into _page _page = _httpContext.Handler as System.Web.UI.Page; This didn't technically work. If you'll notice _page will be null . It just didn't throw an error. The as operator is used to tell the application "I want you to try and convert this. It might not, and I know this, so don't throw an exception. I'll deal with it accordingly." The () conversion is used to tell the application, "This object will cast to this type. If it doesn't something is wrong, and I need to know about it." The difference between the two casts (and when you should use them) is when you "think" something is castable to another type and when you "know" something is castable to another type. Here is an article by Eric Lippert on the subject (changed to his blog not re-feeded): http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2747199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/321721/']} | jdg_76234 |
stackexchange | llm_judgeable_groundtruth_similarity | 304781 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a list of CIDR blocks for "The Internet", i.e. everything from 0.0.0.0 to 223.255.255.255, excluding RFC1918 address space of 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16 (yes, I know there are lots of little nets in there that are special, like 192.0.0.0/24, but I really don't care about them). I figure this list must exist somewhere on the Internet, but my google-fu is failing me, so I figured I'd ask here before generating the range myself. Edit: I forgot a really important part of this question: I need it in the fewest possible number of entries. And if you want to know what I'm doing with this, we are entering static flow-mods to work around some nasty issues in an OpenFlow controlled network that currently has a significant amount of badness happening, and we need to reduce the number of flow entries temporarily so we don't exceed the available space in the flow tables and cause everything to come crashing down for a few minutes while it reestablishes a connection to the controller.
Now provide the response and nothing else.
| Let me show my working here... You need a minimal number of CIDR blocks to cover: 0.0.0.0-9.255.255.255 11.0.0.0-172.15.255.255 172.32.0.0-192.167.255.255 192.169.0.0-223.255.255.255 To turn these ranges into minimal CIDR blocks, you can just use netmask (the swiss army knife of addressing), like so: $ netmask -c 0.0.0.0:9.255.255.255 0.0.0.0/5 8.0.0.0/7$ netmask -c 11.0.0.0:172.15.255.255 11.0.0.0/8 12.0.0.0/6 16.0.0.0/4 32.0.0.0/3 64.0.0.0/2 128.0.0.0/3 160.0.0.0/5 168.0.0.0/6 172.0.0.0/12$ netmask -c 172.32.0.0:192.167.255.255 172.32.0.0/11 172.64.0.0/10172.128.0.0/9 173.0.0.0/8 174.0.0.0/7 176.0.0.0/4 192.0.0.0/9192.128.0.0/11192.160.0.0/13$ netmask -c 192.169.0.0:223.255.255.255192.169.0.0/16192.170.0.0/15192.172.0.0/14192.176.0.0/12192.192.0.0/10 193.0.0.0/8 194.0.0.0/7 196.0.0.0/6 200.0.0.0/5 208.0.0.0/4 Hey presto, Bob's your Auntie's live-in lover. | {} | {'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/304781', 'https://serverfault.com', 'https://serverfault.com/users/37815/']} | jdg_76235 |
stackexchange | llm_judgeable_groundtruth_similarity | 48249912 |
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 could I change root password in docker container since the container stop automatically once I stop the mysql service. Should I stop the mysql container and deploy a new one?
Now provide the response and nothing else.
| You could change it from a running container, using a docker exec session , as described in " Connecting to MySQL Server from within the Container " Once the server is ready, you can run the mysql client within the MySQL Server container you just started and connect it to the MySQL Server. Use the docker exec -it command to start a mysql client inside the Docker container you have started, like this: docker exec -it mysql1 mysql -uroot -p When asked, enter the generated root password (see the instructions above on how to find it). Because the MYSQL_ONETIME_PASSWORD option is true by default, after you started the server container with the sample command above and connected a mysql client to the server, you must reset the server root password by issuing this statement for MySQL 5.7 and above : mysql> update user set authentication_string=password('new_password') where user='root'; or alternatively run, mysql> SET PASSWORD FOR 'root' = PASSWORD('new_password'); For MySQL 5.7 and older versions, run, mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpassword'; Substitute newpassword with the password of your choice. Once the password is reset, the server is ready for use. Note that the above command will only change the password for 'root' connecting from 'localhost' host. You can verify this by using the command: select * from mysql.user; To alter the password for 'root' from all hosts, use: ALTER USER 'root'@'%' IDENTIFIED BY 'newpassword'; Then, as described in " hub.docker.com/mysql ", dont forget docker secrets : As an alternative to passing sensitive information via environment variables, _FILE may be appended to the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. In particular, this can be used to load passwords from Docker secrets stored in /run/secrets/<secret_name> files. For example: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD_FILE=/run/secrets/mysql-root -d mysql:tag xeruf points out in the comments to " MYSQL_ROOT_PASSWORD is set but getting " Access denied for user 'root'@'localhost' (using password: YES)" in docker container ", adding: If you mount a volume, make sure to clear it when changing the USER/PASSWORD ! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48249912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7137467/']} | jdg_76236 |
stackexchange | llm_judgeable_groundtruth_similarity | 230696 |
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:
If I have a web-page being sent over the Internet without encryption, anybody in the middle can change it. So if I put a public key of a server inside, the attacker can replace it with his own and decrypt the message sent by the client to the "server" (really an attacker). How can I be sure that the communication is secure? P.S. please don't tell me about SSL/TLS. It is all about trust to a third-party CA.
Now provide the response and nothing else.
| P.S. please don't tell me about SSL/TLS. TLS is the solution. It ensures that you are talking with the holder of the private key corresponding to the certificate. It's made for this purpose. It's tested for this purpose. It's built explicitly to withstand MiTM-attacks. If you distribute certificates ahead of time, you can ensure that there's no man in the middle with TLS. The CA-infrastructure is basically this distribution. It is all about trust to a third-party CA. Then don't use a thirdparty CA - roll your own, and take the pains of distributing certificates manually. Or roll with HPKP , which basically validates that the public key (and thus the private key) has not changed, which means a fraudulent CA can't replace the certificate. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/230696', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/233388/']} | jdg_76237 |
stackexchange | llm_judgeable_groundtruth_similarity | 4406426 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Still getting my head around things here. I'm not even close, but anyways.... I have a TabBar application created from Xcode. It works I have three tab views, that I know how to manipulate, etc. I'd like to put a 'login' nib file in front of this whole thing, requiring a user to answer a (hardcoded for now) username and password. If you get that right, then, render the tab portion, allowing them to click around. I have another application that I've written that does the username and password part, I'm having trouble taking the logic from there, and putting it in front of the TabApplication piece. Anyone have any suggestions?
Now provide the response and nothing else.
| In your AppDelegate, at the end of the application didFinishLaunchingWithOptions method you'll see this: [window addSubview:tabcontroller.view];[window makeKeyAndVisible];return YES; Simply initialize your login view controller and add it after the tabcontroller, like this: initialScreenViewController = [[InitialScreenViewController alloc] init];[window addSubview:tabcontroller.view];[window addSubview:initialScreenViewController.view];[window makeKeyAndVisible];return YES; In you login viewcontroller, after authenticating the user you can hide it like this: [self.parentViewController.view setHidden:YES]; which allows you to show it again if you have a logout feature. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4406426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22451/']} | jdg_76238 |
stackexchange | llm_judgeable_groundtruth_similarity | 46387122 |
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 question is for anyone who is familiar with Node.js Express Passport JWT Authentication with passport (JSON Web Tokens) Facebook OAuth2.0 OR Google OAuth2.0 I have been doing some online courses and understand how to do the two following things: Authentication using Passport Local Strategy + JWT Tokens Authentication using Passport Google/Facebook Strategy + Cookie/sessions. I am trying to combine the content from these two courses basically. I want to use Google Strategy + JWT Authentication. I want to use JWT instead of cookies because my app is going to be a web/mobile/tablet app, and I need to be accessing the api from different domains. There are two issues I am having with this: To kick off the Google/facebook OAuth pipelines, you need to call either '/auth/facebook' or '/auth/google'. Both Oauth flows work basically the same so when I say '/auth/google' from now on, I am referring to either. Now the issue I'm having is: On the client, do I call the '/auth/google' route with a href button link or an axios/ajax call? If I use the href or axios/ajax approach I am still getting problems with both solutions. The href approach problem: When I assign an <a> tag with a href to '/auth/google' the authentication works perfectly fine. The user gets pushed through the Google Auth flow, they log in and the '/auth/google/callback' route gets called. The problem I have now is how do I correctly send the JWT token back to the client from '/auth/google/callback'? After a lot of googling I have seen that people have simply passed the the JWT back to the client from the oauth callback in the redirect query param. For example: res.redirect(301, `/dashboard?token=${tokenForUser(req.user)}`); The issue I have with this is that now the the ability to authenticate is saved in my browser history! I could log out (destroying the token saved in localStorage), and then simply look at my browser url history, go back to the url that contains the token in the query param, and I would automatically log in again without having to go through the Google Strategy! This is a huge security flaw and is obviously the incorrect way to approach it. The axios/ajax approach problem: Now before I explain the problem with this issue, I know for sure that If I get this working, it will solve all issues I was having with the previous href problem. If I manage to call '/google/auth' from an axios.get() call and receive the JWT in the response body, I will not be sending the token as url param, and it will not get saved in the browser history! Perfect right? well there is still some problems with this approach :( When try to call axios.get('/auth/google') I get the following error: How I've tried to solve the problem: I installed cors to my npm server, and added app.use(cors()); to my index.js. I took a stab and added " http://localhost:3000 " to the "Authorised JavaScript origins" in Google developer console. Neither of these solutions solved the issue, so now I really feel stuck. I want to use the axios/ajax approach, but I'm not sure how to get past this cors error. Sorry for such a long message, but I really felt I had to give you all the information in order for you to properly help me. Thanks again, looking forward to hear from you!
Now provide the response and nothing else.
| I solved this in this way: On Front-End (can be mobile app) I made login request to Google (or Facebook) and after the user selected his account and logged in I got back response that contained google auth token and basic user info. Then I sent that google auth token to backend where my API sent one more request to the Google API to confirm that token. ( See step 5 ) After successful request comes you get basic user info and e-mail. At this point, you can assume that user login via Google is good since google check returned that it's okay. Then you just signup or login user with that email and create that JWT token. Return token to your client and just use it for future requests. I hope it helps. I implemented this multiple times and it showed like a good solution. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46387122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4318531/']} | jdg_76239 |
stackexchange | llm_judgeable_groundtruth_similarity | 176099 |
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:
Unlike principal components analysis, the solutions to factor analysis models are not necessarily nested. That is, the loadings (for example) for the first factor won't necessarily be identical when only the first factor is extracted vs. when the first two factors are. With that in mind, consider a case where you have a set of manifest variables that are highly correlated and (by theoretical knowledge of their content) should be driven by a single factor. Imagine that exploratory factor analyses (by whichever metric you prefer: parallel analysis, scree plot, eigen values >1, etc.) strongly suggests that there are $2$ factors: A large primary factor, and a small secondary factor. You are interested in using the manifest variables and the factor solution to estimate (i.e., get factor scores) participants' values for the first factor. In this scenario, would it be better to: Fit a factor model to extract only $1$ factor, and get factor scores (etc.), or fit a factor model to extract both factors, get factor scores for the factors, but throw away / ignore the scores for the second factor? For whichever is the better practice, why? Is there any research on this issue?
Now provide the response and nothing else.
| The issue you're alluding to is the 'approximate unidimensionality' topic when building psychological testing instruments, which has been discussed in the liturature quite a bit in the 80's. The inspiration existed in the past because practitioners wanted to use traditional item response theory (IRT) models for their items, and at the time these IRT models were exclusively limited to measuring unidimensional traits. So, test multidimensionality was hoped to be a nuisance that (hopefully) could be avoided or ignored. This is also what led to the creation of the parallel analysis techniques in factor analysis (Drasgow and Parsons, 1983) and the DETECT methods. These methods were --- and still are --- useful because linear factor analysis (what you are referring to) can be a decent limited-information proxy to full-information factor analysis for categorical data (which is what IRT is at its core), and in some cases (e.g., when polychoric correlations are used with a weighted estimator, such as WLSMV or DWLS) can even be asymptotically equivalent for a small selection of ordinal IRT models. The consequences of ignoring additional traits/factors, other than obviously fitting the wrong model to the data (i.e., ignoring information about potential model misfit; though it may of course be trivial), is that trait estimates on the dominant factor will become biased and therefore less efficient. These conclusions are of course dependent on how the properties of the additional traits (e.g., are they correlated with the primary dimension, do they have strong loadings, how many cross-loadings are there, etc), but the general theme is that secondary estimates for obtaining primary trait scores will be less effective. See the technical report here for a comparison between a miss-fitted unidimensional model and a bi-factor model; the technical report appears to be exactly what you are after. From a practical perspective, using information criteria can be helpful when selecting the most optimal model, as well as model-fit statistics in general (RMSEA, CFI, etc) because the consequences of ignoring multidimensional information will negatively affect the overall fit to the data. But of course, overall model fit is only one indication of using an inappropriate model for the data at hand; it's entirely possible that improper functional forms are used, such as non-linearity or lack of monotonicity, so the respective items/variables should always be inspected as well. See also : Drasgow, F. and Parsons, C. K. (1983). Application of Unidimensional Item Response Theory Models to Multidimensional Data. Applied Psychological Measurement, 7 (2), 189-199. Drasgow, F. & Lissak, R. I. (1983). Modified parallel analysis: A procedure for examining the latent-dimensionality of dichotomously scored item responses. Journal of Applied Psychology, 68, 363-373. Levent Kirisci, Tse-chi Hsu, and Lifa Yu (2001). Robustness of Item Parameter Estimation Programs to Assumptions of Unidimensionality and Normality. Applied Psychological Measurement, 25 (2), 146-162. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/176099', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/7290/']} | jdg_76240 |
Subsets and Splits