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
38400
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 observations are very simple, but I suppose they contain an error, which I haven't been able to find it so far. Maybe somebody can help how to fix it: Let $H$ be a Hilbert space, $U$ be a dense subspace. Assume we can equip $U$ with another Hilbert space norm by itself. We denote this space by $\mathcal U$, to avoid misunderstandings. We then have the linear inclusion $ i : \mathcal U \rightarrow H$ with image dense in $H$. Assume furthermore, $i$ is bounded. Let us now inspect the dual arrow, which acts on the topological dual spaces: $i^\ast : H^\ast \rightarrow \mathcal U^\ast, \;\; w( \cdot) \mapsto w( i \cdot )$ As $i$ is a bounded injection, $i^\ast$ is now a bounded surjection. What is the kernel of $i^\ast$? We have $\ker i^\ast = \{ w \in H^\ast : w(x) = 0, x \in \operatorname{Im} i \}$ But then $\ker i^\ast = (\operatorname{Im} i)^\perp = U^\perp = H^\perp = \{0\}$, so $i^\ast$ is injective. Hence it is an isomorphism. Strange: But if we dualize $i^\ast$ again, we then see $i$ is an isomorphism, too. Furthermore, as $H$ and $\mathcal U$ are Hilbert spaces, we are given (isometric) isomorphisms $H \simeq H^\ast$, $\mathcal U \simeq \mathcal U^\ast$. We can compose these morphisms. Strange: We obtain $\mathcal U \simeq H$, where the injection is in fact an isomorphism. So this eventually means, if we equip any dense subspace of a Hilbert space with a stronger topology, then the injection $i$ as above is an isomorphism. This seems paradoxical, and I suppose there is an error in the above. For example, this implies the injection $H^1(\mathbb R) \rightarrow L^2(\mathbb R)$ is an isomorphism. So, can anybody please either: (a) Point out where I have been wrong (b) Point out how to interpret this paradox? Now provide the response and nothing else.
The error lies in "As $i$ is a bounded injection, $i^{\ast}$ is a bounded surjection". In fact, the range of $i$ is closed in $H$ if and only if the range of $i^{\ast}$ is closed in $U^{\ast}$ by the closed range theorem . However, in the present situation, we need not use this rather difficult result (which is true for all Banach spaces) but it's more an exercise in the yoga of orthogonal complements. Added Later As I failed to mention (and Nate was kind enough to point out in his answer), the image of $i^{\ast}$ is dense of course. This is implicit in my yoga exercise above. To see why $i^{\ast}$ need not be surjective, let me treat the concrete situation of the question by exhibiting an explicit example of a functional on $H^1$ which is not in the image of $i^{\ast}$. Recall the following facts: The Sobolev space $H^1[0,1]$ is dense in $L^2[0,1]$ (since it contains the smooth functions) and consists of continuous functions . In fact, there is an inclusion $H^1[0,1] \to C[0,1]$ which is compact (hence continuous) by one of the standard compactness theorems (whose exact name I tend to forget), when the former is equipped with its Sobolev norm and the latter is equipped with the sup norm. Therefore it makes sense to define the evaluation functional $\phi(f) = f(p)$ for $f \in H^1$ and $p \in [0,1]$ and $\phi$ is continuous with respect to the Sobolev norm. On the other hand, $\phi$ is not continuous with respect to the $L^2$-norm, as can be seen by choosing an appropriate sequence of smooth bump functions such that $\|f_n\|_2 \to 0$ and $\phi(f_n) = f_n (p) \to \infty$. This means that $\phi$ cannot be in the image of $i^{\ast}$ (which is simply the restriction of functionals on $L^2$ to $H^1$ via $i$), and hence $i^{\ast}$ fails to be surjective.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/38400', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3557/']}
jdg_377641
stackexchange
llm_judgeable_groundtruth_similarity
158190
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 : We are given $n\times n$ square matrices $A$ and $B$ with $AB+BA=0$ and $A^2+B^2=I$. Show $tr(A)=tr(B)=0$. Thoughts : We have $tr(BA)=tr(AB)=-tr(BA)=0$. We also have the factorizations $(A+B)^2=I$ and $(A-B)^2=I$ by combining the two relations above. Let $\alpha_i$ denote the eigenvalues of $A$, and $\beta_i$ the eigenvalues of $B$. We have, by basic properties of trace, $\sum \alpha_i^2 +\sum \beta_i^2=n$ from $A^2+B^2=I$. I'm not sure where to go from here. I would prefer a small hint to a complete answer. Now provide the response and nothing else.
It appears from the context in the book that the correct problem is $$ A^2 + B^2 = A B + B A = 0. $$ The middle step is that $(B-A)^2 = 0,$ so we name the nilpotent matrix $N=B-A.$ Wait, I think that is enough. Because it is also true that $(A+B)^2 = 0.$ So $A+B$ and $B-A$ both have trace $0.$ So $tr \; \; 2B = 0.$ That finishes characteristic other than 2. We don't need full Jordan form for nilpotent matrices, just a quick proof that $N^2 = 0$ implies that the trace of $N$ is zero. Hmmm. This certainly does follow from the fact that a nilpotent matrix over any field has a Jordan form, but I cannot say that I have seen a proof of that. Alright, in characteristic 2 this does not work, in any dimension take$$ A = B, $$$$ A = B \; \; \; \mbox{then} \; \; A^2 + B^2 = 2 A^2 = 0, \; AB + BA = 2 A^2 = 0. $$ In comparison, the alternate problem $$ A^2 + B^2 = A B + B A = I $$ has the same thing about nilpotence, however in fields where $2 \neq 0$ and $2$ is a square we get a counterexample with$$ A \; = \; \left( \begin{array}{rr} \frac{1}{\sqrt 2} & \frac{-1}{2} \\ 0 & \frac{1}{\sqrt 2} \end{array} \right) $$and$$ B \; = \; \left( \begin{array}{rr} \frac{1}{\sqrt 2} & \frac{1}{2} \\ 0 & \frac{1}{\sqrt 2} \end{array} \right) $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/158190', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18240/']}
jdg_377642
stackexchange
llm_judgeable_groundtruth_similarity
314613
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $1 \leq k < n$ be natural numbers. Given orthonormal vectors $u_1,\dots,u_k$ in ${\bf R}^n$ , one can always find an additional unit vector $v \in {\bf R}^n$ that is orthogonal to the preceding $k$ . My question is: under what conditions on $k,n$ is it possible to make $v$ depend continuously on $u_1,\dots,u_k$ , as the tuple $(u_1,\dots,u_k)$ ranges over all possible orthonormal systems? (For my application I actually want smooth dependence, but I think that a continuous map can be averaged out to be smooth without difficulty.) When $k=n-1$ then one can just pick the unique unit normal to the span of the $u_1,\dots,u_k$ that is consistent with a chosen orientation on ${\bf R}^n$ (i.e., take wedge product and then Hodge dual, or just cross product in the $(k,n)=(2,3)$ case). But I don't know what is going on in lower dimension. Intuitively it seems to me that if $n$ is much larger than $k$ then the problem is so underdetermined that there should be no topological obstructions (such as that provided by the Borsuk-Ulam theorem), but I don't have the experience in algebraic topology to make this intuition precise. It would suffice to exhibit a global section of the normal bundle of the (oriented) Grassmannian $Gr(k,n)$ , though I don't know how to calculate the space of such sections. Now provide the response and nothing else.
$\def\RR{\mathbb{R}}$ This problem was solved by Whitehead, G. W. , Note on cross-sections in Stiefel manifolds , Comment. Math. Helv. 37, 239-240 (1963). ZBL0118.18702 . Such sections exist only in the cases $(k,n) = (1,2m)$ , $(n-1, n)$ , $(2,7)$ and $(3,8)$ . All sections can be given by antisymmetric multilinear maps (and thus, in particular, can be taken to be smooth). The $(2,7)$ product is the seven dimensional cross product , which is octonion multiplication restricted to the octonions of trace $0$ . The $(3,8)$ product was computed by Zvengrowski, P. , A 3-fold vector product in $R^8$ , Comment. Math. Helv. 40, 149-152 (1966). ZBL0134.38401 to be given by the formula $$X(a,b,c) = -a (\overline{b} c) + a (b \cdot c) - b (c \cdot a) + c (a \cdot b)$$ where $\cdot$ is dot product while multiplication with no symbol and $\overline{b }$ have their standard octonion meanings. Note that, if $(a,b,c)$ are orthogonal, the last $3$ terms are all $0$ , so the expression simplifies to $- a (\overline{b} c)$ ; writing in the formula in the given manner has the advantage that $X(a,b,c)$ is antisymmetric in its arguments and perpendicular to the span of $a$ , $b$ and $c$ for all $(a,b,c)$ .
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/314613', 'https://mathoverflow.net', 'https://mathoverflow.net/users/766/']}
jdg_377643
stackexchange
llm_judgeable_groundtruth_similarity
19035406
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 always thought ngShow and ngHide act as boolean counterpart to each other. That belief, however, is shaken by the unexpected behaviour of ngShow when an empty array is involved. Here is a demo plunker . Why isn't ng-show="!emptyArray" behaving like ng-hide="emptyArray" ? Now provide the response and nothing else.
Because [] !== false . You can coerce the length value to boolean instead with !! . <div ng-hide="!!emptyArray.length">emptyArray is falsy, so do not hide this.</div><div ng-show="!!!emptyArray.length">!emptyArray is truthy, so show this.</div> Edited: AngularJS's directive hide or show depends on the function toBoolean() for evaluating the value passed in. Here is the source code of toBoolean() : function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value;} And you can verify the following code in JS console: >var emptyArray = [];>toBoolean(emptyArray)false>toBoolean(!emptyArray)false That explains why. Since when emptyArray is passed to the toBoolean() directly, it evaluates the correct result false . However when !emptyArray is passed to toBoolean() , it doesn't evaluate to true since !emptyArray is false itself. Hope it helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19035406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338961/']}
jdg_377644
stackexchange
llm_judgeable_groundtruth_similarity
1103994
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 noticed that pinging whatever.localhost resolves to 127.0.0.1 . I'm on macos. Is that a standard behavior (resolving *.localhost to 127.0.0.1 ) I can rely on? Does it work on Linux or Windows the same way? Now provide the response and nothing else.
It should on most systems. The RFC itself says name resolution SHOULD return the loopback address for anything inside .localhost. The domain "localhost." and any names falling within ".localhost." are special in the following ways: (skip a bit) Name resolution APIs and libraries SHOULD recognize localhostnames as special and SHOULD always return the IP loopback addressfor address queries SHOULD is not quite the same as MUST, but I'd expect almost all systems to follow that behaviour. I can't think of any linux or windows systems I've used that don't.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1103994', 'https://serverfault.com', 'https://serverfault.com/users/66154/']}
jdg_377645
stackexchange
llm_judgeable_groundtruth_similarity
30543993
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to add NavigationView in my layout as below: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <android.support.design.widget.NavigationView xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/drawer" /> </android.support.v4.widget.DrawerLayout></RelativeLayout> But the problem is I am getting an error during compile as below: C:\Users\IBM_ADMIN\Documents\Androidprojects\supporttest\app\src\main\res\layout\activity_main.xmlError:(22) No resource identifier found for attribute 'menu' in package 'ranjithnair02.com.supporttest'Error:Execution failed for task ':app:processDebugResources'.> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\IBM_ADMIN\Documents\android-studio\sdk\build-tools\22.0.1\aapt.exe'' finished with non-zero exit value 1Information:BUILD FAILED I have added the menu item in menu/drawer.xml. <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <group android:checkableBehavior="single"> <item android:id="@+id/navigation_item_1" android:checked="true" android:icon="@drawable/abc_tab_indicator_mtrl_alpha" android:title="First" /> <item android:id="@+id/navigation_item_2" android:icon="@drawable/abc_btn_check_material" android:title="Second" /> </group></menu> Now provide the response and nothing else.
Make sure you have the correct dependency to the Android Design Support Library.It's easy to choose the wrong one - because it seems that Google posted two different dependency strings: At the time of this answer, the Android developer blog (and the comment by user hungryghost) had the correct dependency string, while the dependency string on the Support library homepage did not work. Use this one: compile 'com.android.support:design:26.1.0' Note that the version is 22. 2 .0 (wrong: 22.0.0 ) and that the package is called design (wrong: support-design ) After these changes use the Android Studio menu "Rebuild project", or the "Sync" button that appears sometimes after changing the gradle file.That finally made it work for me.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30543993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1908328/']}
jdg_377646
stackexchange
llm_judgeable_groundtruth_similarity
920991
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got this parameter: $objDbCmd.Parameters.Add("@telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;$objDbCmd.Parameters["@telephone"].Value = $objUser.Telephone; Where the string $objUser.Telephone can be empty. If it's empty, how can I convert it to [DBNull]::Value ? I tried: if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value }; But that gives me the error: Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String." And if I convert it to a string, it inserts an empty string "" , and not DBNull . How can this be accomplished? Thanks. Now provide the response and nothing else.
In PowerShell, you can treat null/empty strings as a boolean. $x = $nullif ($x) { 'this wont print' }$x = ""if ($x) { 'this wont print' }$x = "blah"if ($x) { 'this will' } So.... having said that you can do: $Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value }) But I'd much rather wrap this up in a function like: function CatchNull([String]$x) { if ($x) { $x } else { [DBNull]::Value }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/920991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109896/']}
jdg_377647
stackexchange
llm_judgeable_groundtruth_similarity
89770
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: An apology might be in due for asking another question about prerequisites, but I was confused about the starting points. I have come across various terms such as "Modal Logic", "Temporal logic", "First -order Logic", "Second order Logic" and "Higher order logic". What exactly does "Logic" mean in this context? How do we rigorously define the word "Logic"? After going through the beginning pages of few books I can roughly conclude that a "Logic is a way to decide what follows from what and is significant in designing programming languages as it dictates and facilitates designing of programs to automatically reason and understand programs.I want to understand about the second point in a bit elaborated manner. Now coming to these logics. Are all these logics, "temporal Logic", "Modal Logic", "First order Logic", "Higher order Logic" independent of each other or we need to understand few of these logic to understand a few others in this group? In a nutshell, what will be the prerequisites for them? (It will be great if I can get suggestions on some materials also.) P.S : Thanks a ton for your kindness Now provide the response and nothing else.
Fundamentally, a logic consists of two things. Syntax is a set of rules that determine what is and is not a formula. Semantics is a set of rules that determine what formulae are "true" and what are "false". To a model theorist , this is expressed by relating formulas to the mathematical structures that they're true in; to a proof theorist , truth corresponds to provability from a chosen set of axioms with a chosen set of proof rules (techniques). The difference between different logics is, most simply, in the choice of syntax and semantics. Most logics are extensions of propositional logic or first-order logic . In a sense, you can see these extensions as "adding more features" to the logic. For example, temporal logics deal with truths that can vary over time. In general, these features could be expressed in a simpler logic, at the cost of having to write longer formulas. For example, the temporal concept "$\varphi$ is true from this point for eternity" can be expressed in a first-order way by adding a time parameter to all your propositions and saying "For all times $t$, if $t$ is greater than or equal to the current time, then $\varphi$ is true at time $t$." In a sense, you can think of these logics as adding libraries to a basic programming language so you can say things more easily. Since pretty much all logics are based on propositional and first-order logic, I'd recommend learning about those first.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/89770', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/85819/']}
jdg_377648
stackexchange
llm_judgeable_groundtruth_similarity
2097935
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 a first year student, studying linear algebra. In the lecture we briefly discussed double dual spaces and I am not sure if I understood it correctly: we take a function f that is an element of the dual space and we evaluate the function on a vector from V and its value is an element of the double dual space? Thank you very much in advance. Now provide the response and nothing else.
Nope, you're missing a bit here. Long story short: the elements of the double dual space are functions that take a function $f$ from the dual space, and evaluate the function on a vector from $V$ . That is, an element of the double dual space is a function of the form $f \mapsto f(v)$ . It's nice to think of this weird function as just being that vector $v$ from $V$ . Long story long: for simplicity, I'll talk about vector spaces over $\Bbb R$ , but the same applies over arbitrary fields. The first thing to understand is that the set $\mathcal L(U,V)$ of linear transformations between two vector spaces $U$ and $V$ forms a vector space. For example, if $U = \Bbb R^n$ and $V = \Bbb R^m$ , then $\mathcal L(U,V)$ is canonically identified with the space $\Bbb R^{m \times n}$ of $m \times n$ matrices. In general, $\dim (\mathcal L(U,V)) = \dim(U) \cdot \dim(V)$ . Dimension is important because any vector spaces of the same (finite) dimension are isomorphic. Now, for any vector space $V$ , $V^* = \mathcal L(V,\Bbb R)$ is the dual space of $V$ . The elements of $V^*$ are called linear functionals; they are linear transformations that take vectors and produce numbers. Notably, $\dim(V^*) = \dim(V) \cdot \dim(\Bbb R) = \dim(V) \cdot 1 = \dim (V)$ . So, any (finite dimensional) space is isomorphic to its dual space. The double dual space is the dual of the dual. That is, $V^{**} = \mathcal L(V^*, \Bbb R) = \mathcal L(\mathcal L(V,\Bbb R),\Bbb R)$ . The elements of this space are linear transformations that take linear functionals and produce numbers. If that seems weird and unintuitive, that's fine: it should. Just like $V^*$ , $V^{**}$ is isomorphic to $V$ , since $\dim(V^{**}) = \dim(V^*)\cdot 1 = \dim(V)$ . However, it turns out that $V^{**}$ is canonically isomorphic to $V$ . That is (for our purposes), it is isomorphic in a "really nice way". In particular, there is a really nice invertible linear map that takes us from $V$ to $V^{**}$ , and it's so slick that we can think of $V$ and $V^{**}$ as being "essentially the same space". Let's describe that map $\alpha:V \to V^{**}$ . For any vector $v \in V$ , we want an element $\alpha(v) = \alpha_v \in V^{**}$ , which is to say that $\alpha_v$ takes in functionals $f \in V^*$ , and produces a number. So, we define $$\alpha_v(f) = f(v)$$ In other words, the question of "is $V$ canonically isomorphic to $V^{**}$ ?" can be roughly translated as "is there a natural way to use $v$ to make an element $f \in V^*$ into a number?" Our answer is, "yes: plug $v$ into $f$ ". For any vector $v \in V$ , $\alpha_v$ is the element of $V^{**}$ that tells you to plug in $v$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2097935', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/406823/']}
jdg_377649
stackexchange
llm_judgeable_groundtruth_similarity
29399217
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im trying to iterate over an array that I construct from multiple http calls inside a angular.forEach() the function $scope.ticket_stats = function(){ //cleaning variables $scope.data_set = []; $scope.closed_tickets = []; //fetching time stamps (epoch) $scope.time_frame = time_period.days(7); //calling data using time stamps angular.forEach($scope.time_frame, function(item) { //debug console.log(item); var promise = tickets.status("closed", item); promise.success(function(data){ console.log(data); $scope.closed_tickets.push(data[0].datapoints[0][0]); // returns a numerical value }); }); //SEE MESSAGE BELOW $scope.data_set.push($scope.closed_tickets);} the last line $scope.data_set.push() is working but increment itself over time once calls return data. I would like this line to be executed once everything within the for Each loop is all done. I need to iterate over the $scope.closed_tickets array afteward to play (addition) data inside it and build up a second array. here are the services used in this function: // CALL TICKETS STATSapp.service('tickets', function($http){ this.status = function(status, date){ var one_snap = date - 100; var url = "/url/render?format=json&target=sum(stats.tickets."+status+")&from="+one_snap+"&until="+date+""; return $http.get(url); }; });// TIME STAMPS MATHSapp.service('time_period', function(){ var currentDate = parseInt((new Date).getTime()/1000); this.days = function(number){ var pending = []; for (var i = number; i > 0; i--) { pending.push(currentDate - (87677*i)); } return pending; }; }); I search for information and found out about the $q.all() service but didn't manage to make this work the way I want. Any advices would be welcomed!Thanks! Now provide the response and nothing else.
You can use $q.all to wait for multiple ansynchronous events (promises) to finish. $scope.ticket_stats = function() { // list of all promises var promises = []; //cleaning variables $scope.data_set = []; $scope.closed_tickets = []; //fetching time stamps (epoch) $scope.time_frame = time_period.days(7); //calling data using time stamps angular.forEach($scope.time_frame, function(item) { // create a $q deferred promise var deferred = $q.defer(); //debug console.log(item); tickets.status("closed", item).success(function(data) { console.log(data); $scope.closed_tickets.push(data[0].datapoints[0][0]); // promise successfully resolved deferred.resolve(data); }); // add to the list of promises promises.push(deferred.promise); }); // execute all the promises and do something with the results $q.all(promises).then( // success // results: an array of data objects from each deferred.resolve(data) call function(results) { $scope.data_set.push($scope.closed_tickets); }, // error function(response) { } );} First, deferred represents a piece of code that will take an unknown amount of time to execute (asynchronous). deferred.resolve(data) simply states that the code is finished. Data could be anything, an object, string, whatever, but it is usually the results of your asynchronous code. Likewise you can reject a promise with deferred.reject(data) (maybe an error was thrown by the sever). Again, data can be anything but here it should probably be the error response. deferred.promise just returns a promise object. The promise object allows you to set callbacks like .then(successFunction, errorFunction) so you know a piece of code has finished executing before moving on to successFunction (or errorFunction in the case of a failure). In our case $q has the .all method which waits for an array of promises to finish then gives you the results of all the promises as an array. Don't forget to inject the $q service.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29399217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2611897/']}
jdg_377650
stackexchange
llm_judgeable_groundtruth_similarity
42178636
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 request sounds trivial but I could not find a way to do it. I have as input an array of JSON objects: [ { "foo": 1, "bar": 2 }, { "foo": 3, "bar": 4 }, (...)] and I want as output the JSONL version of the same, aka one object per line, not an array: { "foo": 1, "bar": 2 } { "foo": 3, "bar": 4 } (...) This is not the same as using --compact-output , as that would preserve the array and give me: [ { "foo": 1, "bar": 2 }, { "foo": 3, "bar": 4 }, (...) ] Thank you in advance. Now provide the response and nothing else.
The answer to the original question is to use the filter .[] together with the -c command-line option: $ jq -c '.[]' If the input file is very large (notably, if it is too large to fit into memory), it may be better to use jq's --stream command-line option, or a companion tool. If the preservation of numerical precision is important, then you may wish to consider jm , which is particularly easy to use: invoking jm without any parameters suffices. See the jq Cookbook: https://github.com/stedolan/jq/wiki/Cookbook
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42178636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1218376/']}
jdg_377651
stackexchange
llm_judgeable_groundtruth_similarity
45964731
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 accounting tree that's stored with indents/spaces in the source: Income Revenue IAP Ads Other-IncomeExpenses Developers In-house Contractors Advertising Other Expenses There are a fixed number of levels, so I'd like to flatten the hierarchy by using 3 fields (actual data has 6 levels, simplified for example): L1 L2 L3IncomeIncome RevenueIncome Revenue IAPIncome Revenue AdsIncome Other-IncomeExpenses Developers In-house ... etc I can do this by checking the number of spaces prior to the account name: for rownum in range(6,ws.max_row+1): accountName = str(ws.cell(row=rownum,column=1).value) indent = len(accountName) - len(accountName.lstrip(' ')) if indent == 0: l1 = accountName l2 = '' l3 = '' elif indent == 3: l2 = accountName l3 = '' else: l3 = accountName w.writerow([l1,l2,l3]) Is there a more flexible way to achieve this based on the indentation of the current row compared to the previous row rather than assuming it's always 3 spaces per level? L1 will always have no indent, and we can trust that lower levels will be indented further than their parent, but maybe not always 3 spaces per level. Update, ended up with this as the meat of the logic, since I ultimately wanted the account list with the content, it seemed easiest to just use the indent to decide whether to reset, append, or pop the list: if indent == 0: accountList = [] accountList.append((indent,accountName)) elif indent > prev_indent: accountList.append((indent,accountName)) elif indent <= prev_indent: max_indent = int(max(accountList,key=itemgetter(0))[0]) while max_indent >= indent: accountList.pop() max_indent = int(max(accountList,key=itemgetter(0))[0]) accountList.append((indent,accountName)) So at each row of output the accountList is complete. Now provide the response and nothing else.
You can mimick the way Python actually parses the indentation.First, create a stack that will contain the indentation levels.At each line: If the indentation is bigger than the top of the stack, push it and increase the depth level. If it is the same, continue at the same level. If it is lower, pop the top of the stack while it is higher than the new indentation.If you find a lower indentation level before finding exactly the same, then there is an indentation error. indentation = []indentation.append(0)depth = 0f = open("test.txt", 'r')for line in f: line = line[:-1] content = line.strip() indent = len(line) - len(content) if indent > indentation[-1]: depth += 1 indentation.append(indent) elif indent < indentation[-1]: while indent < indentation[-1]: depth -= 1 indentation.pop() if indent != indentation[-1]: raise RuntimeError("Bad formatting") print(f"{content} (depth: {depth})") With a "test.txt" file whose content is as you provided: Income Revenue IAP Ads Other-IncomeExpenses Developers In-house Contractors Advertising Other Expenses Here is the output: Income (depth: 0)Revenue (depth: 1)IAP (depth: 2)Ads (depth: 2)Other-Income (depth: 1)Expenses (depth: 0)Developers (depth: 1)In-house (depth: 2)Contractors (depth: 2)Advertising (depth: 1)Other Expense (depth: 1) So, what can you do with this?Suppose you want to build nested lists.First, create a data stack. When you find an indentation, append a new list at the end of the data stack. When you find an unindentation, pop the top list, and append it to the new top. And regardless, for each line, append the content to the list at the top of the data stack. Here is the corresponding implementation: for line in f: line = line[:-1] content = line.strip() indent = len(line) - len(content) if indent > indentation[-1]: depth += 1 indentation.append(indent) data.append([]) elif indent < indentation[-1]: while indent < indentation[-1]: depth -= 1 indentation.pop() top = data.pop() data[-1].append(top) if indent != indentation[-1]: raise RuntimeError("Bad formatting") data[-1].append(content)while len(data) > 1: top = data.pop() data[-1].append(top) Your nested list is at the top of your data stack.The output for the same file is: ['Income', ['Revenue', ['IAP', 'Ads' ], 'Other-Income' ], 'Expenses', ['Developers', ['In-house', 'Contractors' ], 'Advertising', 'Other Expense' ] ] This is rather easy to manipulate, although quite deeply nested.You can access the data by chaining the item accesses: >>> l = data[0]>>> l['Income', ['Revenue', ['IAP', 'Ads'], 'Other-Income'], 'Expenses', ['Developers', ['In-house', 'Contractors'], 'Advertising', 'Other Expense']]>>> l[1]['Revenue', ['IAP', 'Ads'], 'Other-Income']>>> l[1][1]['IAP', 'Ads']>>> l[1][1][0]'IAP'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45964731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1130801/']}
jdg_377652
stackexchange
llm_judgeable_groundtruth_similarity
2763885
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 looking for a way to automate the deployment of a custom CAS policy in SharePoint. What i would like to achieve is the following: All assemblies that have been built and signed by our build server (with a secret key) should run in SharePoint under the 'higher than normal' trust level. Now I can manually edit the cas policy files to include something like this: <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="MyPermissionSet" Name="[My Company public key]" Description="Grants all "> <IMembershipCondition class="StrongNameMembershipCondition" version="1" PublicKeyBlob="[public key goes here]" /> </CodeGroup> And that works great. However, we have several huge sharepoint farms, with many applications running on it. I'd like to avoid having to manually edit all policy files to include this xml snippet. Is there a way to automate this? For example, from a feature? With kind regards,Erwin van der Valk Now provide the response and nothing else.
Note: I'm assuming Windows batch files as most people seem to be unaware that there are significant differences and just blindly call everything with grey text on black background DOS. Nevertheless, the first variant should work in DOS as well. Executable configuration The easiest way to do this is to just put the variables in a batch file themselves, each with its own set statement: set var1=value1set var2=value2... and in your main batch: call config.cmd Of course, that also enables variables to be created conditionally or depending on aspects of the system, so it's pretty versatile. However, arbitrary code can run there and if there is a syntax error, then your main batch will exit too. In the UNIX world this seems to be fairly common, especially for shells. And if you think about it, autoexec.bat is nothing else. Key/value pairs Another way would be some kind of var=value pairs in the configuration file: var1=value1var2=value2... You can then use the following snippet to load them: for /f "delims=" %%x in (config.txt) do (set "%%x") This utilizes a similar trick as before, namely just using set on each line. The quotes are there to escape things like < , > , & , | . However, they will themselves break when quotes are used in the input. Also you always need to be careful when further processing data in variables stored with such characters. Generally, automatically escaping arbitrary input to cause no headaches or problems in batch files seems pretty impossible to me. At least I didn't find a way to do so yet. Of course, with the first solution you're pushing that responsibility to the one writing the config file.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2763885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332133/']}
jdg_377653
stackexchange
llm_judgeable_groundtruth_similarity
17616286
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: System.out.println("\1"); I thought it did not compile because of the non-recognized escape sequence. What does "\1" exactly represent? Now provide the response and nothing else.
It's an octal escape sequence, as listed in section 3.10.6 of the JLS. So for example: String x = "\16"; is equivalent to: String x = "\u000E"; (As Octal 16 = Hex E.) So \1 us U+0001, the "start of heading" character. Octal escape sequences are very rarely used in Java in my experience, and I'd personally avoid them where possible. When I want to specify a character using a numeric escape sequence, I always use \uxxxx .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17616286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2017866/']}
jdg_377654
stackexchange
llm_judgeable_groundtruth_similarity
10560
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: I am setting up a highly redundant network and want to run my two ASA's in failover mode - each with a link to a router connected to two different ISP's. The topology: My two 2911's are running BGP to the ISPs, and the ASAs are configured in active/passive failover mode. But how do I configure the links from the ASAs to the routers? They are on 2 different subnets at the moment. Now provide the response and nothing else.
Assuming a single context active/passive failover configuration with the ASAs connecting to the 2911s on unique subnets, you could trunk the links using two subinterfaces and vlan tagging. But the hack is to not have both subinterfaces active at the same time on a single ASA. On the ASA on the left assuming it's active, the first subint would be alive and the second down. After a failover event, the ASA on the right becomes active, and the first subint goes down and the second subint comes up. Ideally, the ASAs share a common subnet with the LAN side of the 2911s precluding this hack; a L2 switch can sit between the ASAs and provide connectivity from any ASA to any 2911. Only the relevant subinterfaces' config shown. ASA interface GigabitEthernet0/0 no nameif no security-level no ip address!interface GigabitEthernet0/0.10 vlan 10 nameif Outside-ISP1 security-level 0 ip address 1.1.1.254 255.255.255.0!interface GigabitEthernet0/0.11 vlan 11 nameif Outside-ISP2 security-level 0 ip address 2.1.1.254 255.255.255.0route Outside-ISP1 0.0.0.0 0.0.0.0 1.1.1.1 1route Outside-ISP2 0.0.0.0 0.0.0.0 2.1.1.2 1 2911-ISP1 interface GigabitEthernet0/1 description LAN no ip address duplex auto speed auto!interface GigabitEthernet0/1.10 description LAN-ISP1 encapsulation dot1Q 10 ip vrf forwarding vpn ip address 1.1.1.1 255.255.255.0!interface GigabitEthernet0/1.11 description LAN-ISP2 encapsulation dot1Q 11 ip address 2.1.1.1 255.255.255.0 shutdown 2911-ISP2 interface GigabitEthernet0/1 description LAN no ip address duplex auto speed auto!interface GigabitEthernet0/1.10 description LAN-ISP1 encapsulation dot1Q 10 ip address 1.1.1.2 255.255.255.0 shutdown!interface GigabitEthernet0/1.11 description LAN-ISP2 encapsulation dot1Q 11 ip address 2.1.1.2 255.255.255.0
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/10560', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/8084/']}
jdg_377655
stackexchange
llm_judgeable_groundtruth_similarity
3792663
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between atol() & strtol()? According to their man pages, they seem to have the same effect as well as matching arguments: long atol(const char *nptr);long int strtol(const char *nptr, char **endptr, int base); In a generalized case, when I don't want to use the base argument (I just have decimal numbers), which function should I use? Now provide the response and nothing else.
strtol provides you with more flexibility, as it can actually tell you if the whole string was converted to an integer or not. atol , when unable to convert the string to a number (like in atol("help") ), returns 0, which is indistinguishable from atol("0") : int main(){ int res_help = atol("help"); int res_zero = atol("0"); printf("Got from help: %d, from zero: %d\n", res_help, res_zero); return 0;} Outputs: Got from help: 0, from zero: 0 strtol will specify, using its endptr argument, where the conversion failed. int main(){ char* end; int res_help = strtol("help", &end, 10); if (!*end) printf("Converted successfully\n"); else printf("Conversion error, non-convertible part: %s", end); return 0;} Outputs: Conversion error, non-convertible part: help Therefore, for any serious programming, I definitely recommend using strtol . It's a bit more tricky to use but this has a good reason, as I explained above. atol may be suitable only for very simple and controlled cases.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3792663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377656
stackexchange
llm_judgeable_groundtruth_similarity
22092762
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 blocked all aTOz character input for my text field using regular expression in my JavaScript but as I have blocked entire alphabets I am not able to perform CTRL + C and CTRL + V , here is my regular expression goes: var reValidChars = /[\x08\x0D\d]/;iKeyCode = objEvent.charCode;strKey = String.fromCharCode(iKeyCode); if (!reValidChars.test(strKey)) { return false;} Could you please help me in this issue.Thanks in advance Now provide the response and nothing else.
You can't detect key pressing with RegExp, though you can like following: document.body.addEventListener("keydown",function(e){ e = e || window.event; var key = e.which || e.keyCode; // keyCode detection var ctrl = e.ctrlKey ? e.ctrlKey : ((key === 17) ? true : false); // ctrl detection if ( key == 86 && ctrl ) { console.log("Ctrl + V Pressed !"); } else if ( key == 67 && ctrl ) { console.log("Ctrl + C Pressed !"); }},false); JSFiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22092762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3040482/']}
jdg_377657
stackexchange
llm_judgeable_groundtruth_similarity
12562152
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 iOS 6, the purpose property of CLLocationManager, to describe the reason for using location services ( @property(copy, nonatomic) NSString *purpose ) has been deprecated. What replacement, if any, is proposed by Apple? Now provide the response and nothing else.
The replacement for the purpose property in iOS 6 is a new Info.plist key named NSLocationUsageDescription (aka "Privacy - Location Usage Description"). The key is documented in the Information Property List Key Reference but unfortunately it's not mentioned with the deprecation note of the purpose property. However, the CLLocationManager.h does have this comment: * Deprecated. Set the purpose string in Info.plist using key NSLocationUsageDescription. In your code, you could set both the key and the purpose property (but you may want to check if the location manager responds to that selector first if/when that method is actually removed in the future). If running under iOS 6, the location manager will use the key. When running under less than iOS 6, the key will be ignored and the purpose property will be used.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12562152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272342/']}
jdg_377658
stackexchange
llm_judgeable_groundtruth_similarity
236624
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 instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)? <div id='header-inner'> <div class='titlewrapper'> <h1 class='title'> Some text I want to change </h1> </div> </div> Thanks! Now provide the response and nothing else.
function findFirstDescendant(parent, tagname){ parent = document.getElementById(parent); var descendants = parent.getElementsByTagName(tagname); if ( descendants.length ) return descendants[0]; return null;}var header = findFirstDescendant("header-inner", "h1"); Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/236624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1311500/']}
jdg_377659
stackexchange
llm_judgeable_groundtruth_similarity
2370486
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to show $$I := \int_{-\infty}^\infty \exp \left(-\left(x-\frac p x \right)^2\right) \, dx = \sqrt{\pi}$$ for any non-negative $p\geq 0$. I tried to prove $I^2=\pi$ using Fubini's theorem, but had no success. Now provide the response and nothing else.
The key is to essentially make the substitution $u = x - p/x$. The problem is that this isn't an invertible function--it has a positive and a negative root for $x$. To fix, this we divide the integral into a positive and negative side and make the substitutions\begin{eqnarray}x(u) &=& \frac{1}{2}\left(u \pm \sqrt{4p+u^2}\right) \\dx &=& \frac{1}{2}\left(1 \pm \frac{u}{\sqrt{4p+u^2}}\right)\end{eqnarray}This gives\begin{multline}\int_{-\infty}^\infty \exp\left[-\left(x-\frac{p}{x}\right)^2\right]\,dx =\int_{-\infty}^0 \exp\left[-\left(x-\frac{p}{x}\right)^2\right] \, dx+\int_0^\infty \exp\left[-\left(x-\frac{p}{x}\right)^2\right]dx\\= \int_{-\infty}^\infty \frac{e^{-u^2}}{2}\left(1 - \frac{u}{\sqrt{4p+u^2}}\right) \, du + \int_{-\infty}^\infty \frac{e^{-u^2}}{2}\left(1 + \frac{u}{\sqrt{4p+u^2}}\right) \, du\\= \int_{-\infty}^\infty e^{-u^2}du = \sqrt{\pi}\end{multline}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2370486', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/394418/']}
jdg_377660
stackexchange
llm_judgeable_groundtruth_similarity
55644479
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 pretty new to C++17 and am attempting to understand the decltype keyword and how it pairs with auto . Below is a snippet of code that produces an unexpected result. #include <typeinfo>#include <iostream>#include <algorithm>using namespace std;int main() { int16_t mid = 4; auto low = mid - static_cast<int16_t>(2); auto hi = mid + static_cast<int16_t>(2); int16_t val; cin >> val; val = std::clamp(val,low,hi); return 0;} Surprisingly, the compiler tells me there is a mismatch in clamp and that low and high are int . If I change auto to int16_t all is good in the world and all the types are int16_t as expected. The question I'm posing is, why does auto cast low and hi to int when all of the types are int16_t ? Is this a good use case for decltype ? Even after reading cppreference.com, I don't fully understand how decltype works, so excuse my ignorance. Now provide the response and nothing else.
The problem isn't with auto here. When you subtract two int16_t values, the result is an int . We can demonstrate it with this code here : #include <iostream>#include <cstdint>using namespace std;template<class T>void print_type(T) { std::cout << __PRETTY_FUNCTION__ << std::endl; }int main() { int16_t a = 10; int16_t b = 20; print_type(a); print_type(b); print_type(a - b); return 0;} a and b are both short int s, but when you add or subtract them it produces a regular int . This is to help prevent overflow / and is also for backwards compatibility.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55644479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5141619/']}
jdg_377661
stackexchange
llm_judgeable_groundtruth_similarity
2958388
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: As the title says, the problem I'm trying to solve gives that $Q \succcurlyeq 0$ , but it doesn't seem to indicate that $Q$ is necessarily symmetric. So far I've tried proving from the definition of convexity, which got me a monstrous expression which I did not manage to simplify attempting to show $f$ is a norm (that went nowhere) finding the Hessian (I did not get very far on this, as I wasn't sure how to properly derive and the just finding the gradient was difficult) The fact that the function is of a vector, not a scalar is only complicating things. Any insight, strategies, or solutions to solve this problem? I'm totally puzzled! Now provide the response and nothing else.
Here is shorter proof. Since $f(x) = ||Ax + b||$ with $$A = \begin{pmatrix}Q^{1/2} \\ \bf{0}^T \end{pmatrix} \text{ and } b = \begin{pmatrix} \bf{0} \\ 1 \end{pmatrix},$$ which is just a convex function evaluated in an affine transformation of $x$ , $f$ is convex. Here, $Q^{1/2}$ is the cholesky factor of $Q$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2958388', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477221/']}
jdg_377662
stackexchange
llm_judgeable_groundtruth_similarity
21350132
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using jssor to make a slideshow with an <ul> of <img> tags loaded dynamically when the user upload images to the server with an AJAX request. The thing is when the user want to remove some image. I can do that, but in the slideshow it's appear an empty box where the deleted images was. How can I update or another option to keep this things of remove images dynamically? Here is my code of creating the slideshow and to remove some item: var i = 0;for(; i < data.Paths.length; i++) { $('#slides').append($("<div id='div_" + i + "''><img u='images' style='width: 225px; height: 150px;' src='"+data.Paths[i]+"' id='img_" + i + "''></div>"));}var options = { $ArrowNavigatorOptions: { $Class: $JssorArrowNavigator$, $ChanceToShow: 2 }};jssor_slider1 = new $JssorSlider$('slider1_container', options);$(document).on('click', '#delete_photo', function(){ //Check the data of this button, because we gonna make the button next or previous load the id of the picture inside //console.log(jssor_slider1.$CurrentIndex()); //Return current index of the element inside the slider. var selected_index = jssor_slider1.$CurrentIndex(); var element = "#div_" + selected_index; console.log(element); $(element).remove(); var options = { $ArrowNavigatorOptions: { $Class: $JssorArrowNavigator$, $ChanceToShow: 2 } }; jssor_slider1 = null; jssor_slider1 = new $JssorSlider$('slider1_container', options);}); Now provide the response and nothing else.
A couple of thoughts: You have to make sure you do the necessary coding outlined in the Handling iOS Background Activity section of the URL Loading System Programming Guide says: If you are using NSURLSession in iOS, your app is automatically relaunched when a download completes. Your app’s application:handleEventsForBackgroundURLSession:completionHandler: app delegate method is responsible for recreating the appropriate session, storing a completion handler, and calling that handler when the session calls your session delegate’s URLSessionDidFinishEventsForBackgroundURLSession: method. That guide shows some examples of what you can do. Frankly, I think the code samples discussed in the latter part of the WWDC 2013 video What’s New in Foundation Networking are even more clear. The basic implementation of AFURLSessionManager will work in conjunction with background sessions if the app is merely suspended (you'll see your blocks called when the network tasks are done, assuming you've done the above). But as you guessed, any task-specific block parameters that are passed to the AFURLSessionManager method where you create the NSURLSessionTask for uploads and downloads are lost "if the app terminated or crashes." For background uploads, this is an annoyance (as your task-level informational progress and completion blocks you specified when creating the task will not get called). But if you employ the session-level renditions (e.g. setTaskDidCompleteBlock and setTaskDidSendBodyDataBlock ), that will get called properly (assuming you always set these blocks when you re-instantiate the session manager). As it turns out, this issue of losing the blocks is actually more problematic for background downloads, but the solution there is very similar (do not use task-based block parameters, but rather use session-based blocks, such as setDownloadTaskDidFinishDownloadingBlock ). An alternative, you could stick with default (non-background) NSURLSession , but make sure your app requests a little time to finish the upload if the user leaves the app while the task is in progress. For example, before you create your NSURLSessionTask , you can create a UIBackgroundTaskIdentifier : UIBackgroundTaskIdentifier __block taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) { // handle timeout gracefully if you can [[UIApplication sharedApplication] endBackgroundTask:taskId]; taskId = UIBackgroundTaskInvalid;}]; But make sure that the completion block of the network task correctly informs iOS that it is complete: if (taskId != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:taskId]; taskId = UIBackgroundTaskInvalid;} This is not as powerful as a background NSURLSession (e.g., you have a limited amount of time available), but in some cases this can be useful. Update: I thought I'd add a practical example of how to do background downloads using AFNetworking. First define your background manager. //// BackgroundSessionManager.h//// Created by Robert Ryan on 10/11/14.// Copyright (c) 2014 Robert Ryan. All rights reserved.//#import "AFHTTPSessionManager.h"@interface BackgroundSessionManager : AFHTTPSessionManager+ (instancetype)sharedManager;@property (nonatomic, copy) void (^savedCompletionHandler)(void);@end and //// BackgroundSessionManager.m//// Created by Robert Ryan on 10/11/14.// Copyright (c) 2014 Robert Ryan. All rights reserved.//#import "BackgroundSessionManager.h"static NSString * const kBackgroundSessionIdentifier = @"com.domain.backgroundsession";@implementation BackgroundSessionManager+ (instancetype)sharedManager { static id sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager;}- (instancetype)init { NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundSessionIdentifier]; self = [super initWithSessionConfiguration:configuration]; if (self) { [self configureDownloadFinished]; // when download done, save file [self configureBackgroundSessionFinished]; // when entire background session done, call completion handler [self configureAuthentication]; // my server uses authentication, so let's handle that; if you don't use authentication challenges, you can remove this } return self;}- (void)configureDownloadFinished { // just save the downloaded file to documents folder using filename from URL [self setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) { if ([downloadTask.response isKindOfClass:[NSHTTPURLResponse class]]) { NSInteger statusCode = [(NSHTTPURLResponse *)downloadTask.response statusCode]; if (statusCode != 200) { // handle error here, e.g. NSLog(@"%@ failed (statusCode = %ld)", [downloadTask.originalRequest.URL lastPathComponent], statusCode); return nil; } } NSString *filename = [downloadTask.originalRequest.URL lastPathComponent]; NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *path = [documentsPath stringByAppendingPathComponent:filename]; return [NSURL fileURLWithPath:path]; }]; [self setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) { if (error) { // handle error here, e.g., NSLog(@"%@: %@", [task.originalRequest.URL lastPathComponent], error); } }];}- (void)configureBackgroundSessionFinished { typeof(self) __weak weakSelf = self; [self setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) { if (weakSelf.savedCompletionHandler) { weakSelf.savedCompletionHandler(); weakSelf.savedCompletionHandler = nil; } }];}- (void)configureAuthentication { NSURLCredential *myCredential = [NSURLCredential credentialWithUser:@"userid" password:@"password" persistence:NSURLCredentialPersistenceForSession]; [self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) { if (challenge.previousFailureCount == 0) { *credential = myCredential; return NSURLSessionAuthChallengeUseCredential; } else { return NSURLSessionAuthChallengePerformDefaultHandling; } }];}@end Make sure app delegate saves completion handler (instantiating the background session as necessary): - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler { NSAssert([[BackgroundSessionManager sharedManager].session.configuration.identifier isEqualToString:identifier], @"Identifiers didn't match"); [BackgroundSessionManager sharedManager].savedCompletionHandler = completionHandler;} Then start your downloads: for (NSString *filename in filenames) { NSURL *url = [baseURL URLByAppendingPathComponent:filename]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[[BackgroundSessionManager sharedManager] downloadTaskWithRequest:request progress:nil destination:nil completionHandler:nil] resume];} Note, I don't supply any of those task related blocks, because those aren't reliable with background sessions. (Background downloads proceed even after the app is terminated and these blocks have long disappeared.) One must rely upon the session-level, easily recreated setDownloadTaskDidFinishDownloadingBlock only. Clearly this is a simple example (only one background session object; just saving files to the docs folder using last component of URL as the filename; etc.), but hopefully it illustrates the pattern.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21350132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3234974/']}
jdg_377663
stackexchange
llm_judgeable_groundtruth_similarity
530
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Earth's inner core is solid because despite the enormous temperature in this region, there is also enormous pressure there, which in turn raises the melting point of iron and nickel to a value above the Earth's core temperature. Now as we move out from the solid inner core, temperature drops, and pressure also decreases. Obviously because the inner core is solid but the outer core is liquid, we must conclude that the drop in temperature vs the drop in pressure must be lower than the gradient of 16 degrees/GPa shown in the diagram below ( link to source ), given that at the outer-core temperature has exceeded the melting point of iron/nickel, which is a function of pressure. In other words, the drop in pressure must be quite significant compared to the drop in temperature as radius increases from the core. So how is it that pressure drops off fast enough relative to temperature to give rise to the liquid outer-core. A good answer will explain how temperature drops off with radius and how pressure drops off with radius and how these compare to give rise to the liquid outer-core. Now provide the response and nothing else.
First, you need a phase diagram that goes to higher pressure. The pressure at the inner/outer core boundary is over 300 GPa. The one in the question would only get us into the mantle: ( link to source ) A typical temperature and pressure at the outermost part of the core would be 3750K and 135GPa, which is in the liquid region of the phase diagram. For more data on pressure and temperature as a function of depth see this University of Arizona source . All appropriate credit to Marcus Origlieri.
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/530', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/51/']}
jdg_377664
stackexchange
llm_judgeable_groundtruth_similarity
24148403
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As this question observes, immediate CSS transitions on newly-appended elements are somehow ignored - the end state of the transition is rendered immediately. For example, given this CSS (prefixes omitted here): .box { opacity: 0; transition: all 2s; background-color: red; height: 100px; width: 100px;}.box.in { opacity: 1; } The opacity of this element will be set immediately to 1: // Does not animatevar $a = $('<div>') .addClass('box a') .appendTo('#wrapper');$a.addClass('in'); I have seen several ways of triggering the transition to get the expected behaviour: // Does animatevar $b = $('<div>') .addClass('box b') .appendTo('#wrapper');setTimeout(function() { $('.b').addClass('in');},0);// Does animatevar $c = $('<div>') .addClass('box c') .appendTo('#wrapper');$c[0]. offsetWidth = $c[0].offsetWidth$c.addClass('in');// Does animatevar $d = $('<div>') .addClass('box d') .appendTo('#wrapper');$d.focus().addClass('in'); The same methods apply to vanilla JS DOM manipulation - this is not jQuery-specific behaviour. Edit - I am using Chrome 35. JSFiddle (includes vanilla JS example). Why are immediate CSS animations on appended elements ignored? How and why do these methods work? Are there other ways of doing it Which, if any, is the preferred solution? Now provide the response and nothing else.
The cause of not animating the newly added element is batching reflows by browsers. When element is added, reflow is needed. The same applies to adding the class. However when you do both in single javascript round , browser takes its chance to optimize out the first one. In that case, there is only single (initial and final at the same time) style value, so no transition is going to happen. The setTimeout trick works, because it delays the class addition to another javascript round, so there are two values present to the rendering engine, that needs to be calculated, as there is point in time, when the first one is presented to the user. There is another exception of the batching rule. Browser need to calculate the immediate value, if you are trying to access it. One of these values is offsetWidth . When you are accessing it, the reflow is triggered. Another one is done separately during the actual display. Again, we have two different style values, so we can interpolate them in time. This is really one of very few occasion, when this behaviour is desirable. Most of the time accessing the reflow-causing properties in between DOM modifications can cause serious slowdown. The preferred solution may vary from person to person, but for me, the access of offsetWidth (or getComputedStyle() ) is the best. There are cases, when setTimeout is fired without styles recalculation in between. This is rare case, mostly on loaded sites, but it happens. Then you won't get your animation. By accessing any calculated style, you are forcing the browser to actually calculate it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24148403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2806996/']}
jdg_377665
stackexchange
llm_judgeable_groundtruth_similarity
6386098
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 added several directories, libraries such as matlab, opencv, etc to compile my current C file in Visual Studio project. All my upcoming projects will require the same setup/properties. Do I need to setup my each project's properties individually or I can do something to apply it to all ? Now provide the response and nothing else.
Try using Property Sheets. These can create a single properties file that can be inherited by multiple projects. Use "View > Other Windows > Property Manager" to bring up the Property Manager. It will show your projects and configurations. Right click a configuration, and select "Add New Project Property Sheet...". You can name it, and select a location that works for all your projects. Once created, you can edit its properties just as you would a build configuration. To use that property sheet as the basis for other projects, just right click the configuration or project, and select "Add Existing Property Sheet...". Browse to where you saved the original sheet, and it will be inherited. Any changes to the original sheet will be applied to any project that inherits it, unless they are overridden. If you go into properties higher up the chain, properties that override will have bold type for their values. To get them to always use the value in the base sheet, there will be a "inherit from parent or project defaults" option where applicable.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6386098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801387/']}
jdg_377666
stackexchange
llm_judgeable_groundtruth_similarity
6430716
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 standardized sequence of code which I used to display topic information on the home page and other pages on my site. I want to throw it in an include file so that I don't have to keep fixing multiple pages. The problem is sometimes this include occurs in a while statement which means there was a previous query supplying information for sorting purposes. When the code is raw in the while statement, it works as it should and if there are multiple ids being served to the code from the previous query, it shows multiple results. However, if this code is in an include, I will only see one result. I assume because the include file only executes once. How would I serve an include file as the equivalent as my raw code? Include //outside querywhile($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $topic_id=htmlspecialchars( $row['topic_id'], ENT_NOQUOTES, 'UTF-8' ); //code to display topics include('display_topics.php'); } Raw Code //outside querywhile($row = $stmt->fetch(PDO::FETCH_ASSOC)){ //code to display topics $sql = "SELECT * FROM topic WHERE id=?"; $stmt = $conn->prepare($sql); $stmt->bindValue(1,topic_id, PDO::PARAM_INT); $result=$stmt->execute();}while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ //yada yada ...} Now provide the response and nothing else.
Don't do it this way. It's much better to do one include, and to declare a function in it that does what you need: function display_topics($topic_id) { .... } Call that function inside the loop, and pass all necessary data to it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6430716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301121/']}
jdg_377667
stackexchange
llm_judgeable_groundtruth_similarity
53734007
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 built a simple counter app: class Counter extends React.Component { constructor(props) { super(props); this.handleAddOne = this.handleAddOne.bind(this); this.handleMinusOne = this.handleMinusOne.bind(this); this.handleReset = this.handleReset.bind(this); this.state = { count: 0 }; } componentDidMount() { const stringCount = localStorage.getItem('count'); const count = parseInt(stringCount); if (isNaN(count) === false) { this.setState(() => ({ count })); } } componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { localStorage.setItem('count', this.state.count); console.log('componentDidUpdate'); } } handleAddOne() { this.setState((prevState) => { return { count: prevState.count + 1 } }); } handleMinusOne() { console.log('handleMinusOne'); this.setState((prevState) => { return { count: prevState.count - 1 } }); } handleReset() { this.setState(() => { return { count: 0 } }); } render() { return ( <div> <h1>Count: {this.state.count}</h1> <button onClick={this.handleAddOne}>+</button> <button onClick={this.handleMinusOne}>-1</button> <button onClick={this.handleReset}>reset</button> </div> ); }}ReactDOM.render(<Counter />, document.getElementById('app')); The question I have is with componentDidUpdate() . In it, I am checking to see if the prevState.count is not the same as the this.state.count . If it is not the same, then I set localStorage to the new count. If it is same, I do nothing. In the current componentDidUpdate(), I need prevProps as an argument for this function to work correctly. For example, if I just have this: componentDidUpdate(prevState) { if (prevState.count !== this.state.count) { localStorage.setItem('count', this.state.count); console.log('componentDidUpdate'); } } Then the component sets localStorage every time the reset button is pressed repeatedly, even though the count remains at 0. What is going on? Why do I need prevProps for componentDidUpdate() to work correctly, if I am never using props in that function? Now provide the response and nothing else.
The first parameter in componentDidUpdate is prevProps . The second parameter is prevState . The documentation clearly states that: componentDidUpdate(prevProps, prevState, snapshot) This componentDidUpdate(prevState) {...} is not a correct signature for the hook. Even though the first parameter was called prevState , it contains previous props. It's possible to alternate function parameters based on its arity but this isn't implemented in React and considered a bad practice in general because this leads to more complex signatures. To not cause linter warnings, unused parameters can be underscored by convention: componentDidUpdate(_prevProps, prevState) {...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53734007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8785094/']}
jdg_377668
stackexchange
llm_judgeable_groundtruth_similarity
9259
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using WindRiver JTAG Debugger to debug my code. Whenever I run the code with Debugger connected, Code works correctly but If I disconnect it, It fails to even Start! Has anyone faced such kind of Problems? Now provide the response and nothing else.
My debugger for a Coldfire does some initialization of the SDRAM controller and other low-level registers that is normally done by the bootloader. Check to see how your debugger initializes the chip.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/9259', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2574/']}
jdg_377669
stackexchange
llm_judgeable_groundtruth_similarity
14523480
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this very simple assembly code: start:add ax, 100 ; if ax overflow add to bx 1jmp start but i don't know how to detect ax register overflow, can anyone help me? Now provide the response and nothing else.
ADD instruction sets appropriate FLAGS reflecting the overflow condition. There are two kinds of overflow: signed and unsigned. You have to decide what's appropriate and use jc/jnc for unsigned and jo/jno for signed. add ax, 100jnc noUnsignedOverflow...noUnsignedOverflow:add ax, 100jno noSignedOverflow...noSignedOverflow:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14523480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/720893/']}
jdg_377670
stackexchange
llm_judgeable_groundtruth_similarity
37220896
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: 7 Server with 4 Discs and I have this configuration: "/" In a LVM (Physical disk 1) "/data" In LVM (Physical disk 1 + fake raid 0 of disks 2 and 3) "/data1" Ext4 (Physical disk 4) The server is a supermicro (motherboard model X8DTL) with 8gb of ram. I need to upgrade to centos 7 because the dependencies in the newer software are only in this distro but I have afraid of fuck UP With the data in "/data" How I can upgrade safely without screw with "/data"? PS:I can't make a backup, the information is more than 5TB. "/data" and "/data1" there are only standalone files (Text, spreadsheet files, multimedia files). The programs and associations are only in "/" Edit:Here it is how the disks are arranged: # lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABELNAME FSTYPE SIZE MOUNTPOINT LABELsda linux_raid_member 931,5G GLaDOS:0└─md0 LVM2_member 1,8T └─vg_glados_media-lv_data (dm-3) ext4 3,6T /datasdc linux_raid_member 931,5G GLaDOS:0└─md0 LVM2_member 1,8T └─vg_glados_media-lv_data (dm-3) ext4 3,6T /datasdb 1,8T├─sdb1 ext4 500M /boot├─sdb2 LVM2_member 97,7G│ ├─vg_glados-lv_root (dm-0) ext4 50G /│ ├─vg_glados-lv_swap (dm-1) swap 7,8G [SWAP]│ └─vg_glados-lv_home (dm-2) ext4 39,9G /home└─sdb3 LVM2_member 1,7T └─vg_glados_media-lv_data (dm-3) ext4 3,6T /datasdd 931,5G└─sdd1 ext4 931,5G /data1 /data1sr0 1024M# df -HFilesystem Size Used Avail Use% Mounted on/dev/mapper/vg_glados-lv_root 53G 44G 6,6G 87% /tmpfs 4,2G 78k 4,2G 1% /dev/shm/dev/sdb1 500M 132M 342M 28% /boot/dev/mapper/vg_glados_media-lv_data 3,9T 3,7T 28G 100% /data/dev/mapper/vg_glados-lv_home 42G 862M 39G 3% /home/dev/sdd1 985G 359G 576G 39% /data1 Now provide the response and nothing else.
I think I have figured it and decided to share what I figured so far. make() vs. new() I think I now understand the difference between make() and new() . At first, it was little confusing, but here what I got: new is simply like new in C# or Java, but since there is no constructor in Go, all the fields (like in Java and C# terminology) will be zeroed. Zeroing means more like defaulting the fields. So if the field type is int , then it will be 0 , or if it is a struct , then it will be defaulted to nil , and "" for string types. It is actually similar to C# and Java when there is only parameterless constructor available and you are not setting the members to something else manually. However, types like map , slice , and channel s are different. They are different because they are actually wrapper types that wrap an array type to hold the values behind the scenes. So something like List<T> or ArrayList in C# and Java. But using new is not enough in this situation, because the underlying array should be initialized to an empty array to be usable. Because you cannot add or remove from a field of type array which is nil (or null ). Therefore, they provided a make() method to help you to initialize slices and such. So what happens when you use new() over slices, for instance? Simple: Since the underlying array will be nil , the slice will be pointing at a nil array. So new() would look like the following C#/Java code: public class Person{ public string Name; public int Age; public Address HomeAddress;}var person = new Person();Console.WriteLine(person.Name); // ""Console.WriteLine(person.Age); // 0Console.WriteLine(person.HomeAddress); // null make() , on the other hand, would look like this for slice , map , and channel s: public class PersonList{ // We are initializing the array so that we can use it. // Its capacity can increase. private Person[] _personList = new Person[100]; public void Add(Person p){} public void Remove(Person p){} public Person Get(int index){}} Initialization vs. Zeroing Simply speaking, zeroing is a form of initialization. At first, I thought they were different but they are not. Initialization is a more general term, whereas if you are set the fields (properties, etc.) of a struct or a variable to its type default such as 0 , nil , "" , false , etc., then this is called zeroing. However, you can, for instance, use Composite Literals like hello := Hello{name="world"} , which is similar to var hello = new Hello() {Name = "World"} in C#, then you initialize your Hello object with a name field set to world . In C#, at the time you say new List<string>() , [the underlying array field is initialized to a new array], and make) is performing a similar operation behind the scenes but as a language construct (built in the language itself): ( http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646 ): So new does zeroing and returns a pointer back. Whereas make() initializes to underlying array to an array with default values for each element and returns the value itself rather than a pointer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37220896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6308057/']}
jdg_377671
stackexchange
llm_judgeable_groundtruth_similarity
49681
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Is it safe to change the domain membership of a Windows Server 2008 that runs MS SQL 08? Have you already done this and did you experience any problems?I fear that there could be some kind of domain dependencies (accounts,permissions) that would break certain services once the server has been moved into the new domain. Any feedback is welcome. Now provide the response and nothing else.
You are going to have to go through the Security section and examine the logins to see if your users are connecting with Windows credentials. Look for DOMAIN1\userid logins and determine if they need to be replicated. Be aware that deep within SQL Server it knows what the name of the server was when it was initially installed. So "SELECT @@SERVERNAME" may return the wrong thing if you change the machine name as part of a domain move. It is rare that things depend on it but occasionally you find some code that cares. Note that for 2008 especially there are special local groups created on the server that may need new members added to them in order to make things work right. IF you are running the server as a domain user rather than NT Authority/Network Service or NT Authority/Local System then you will need to change that within the control panel for Services. I'd recommend that you set the sql services to Manual in the Services control panel for the move. Makes the reboots fast and you can check all the file owner ships and stuff without having the server come up half way and then fail to find some of the DBs. If it saves you a checkpoint scan and restore it is worth it. Have backups done right before the move!!!
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/49681', 'https://serverfault.com', 'https://serverfault.com/users/9786/']}
jdg_377672
stackexchange
llm_judgeable_groundtruth_similarity
12479742
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If one tries to run any of the git-bisect commands from anywhere other than the root directory of the repository, one is told: You need to run this command from the toplevel of the working tree. Why is that? I know of no other git command that has this requirement, and I see no obvious reason that bisect should be special. The man page makes no mention of this restriction, either. It's really not a big deal. I'm mostly just curious. Now provide the response and nothing else.
Looking at some commits in the project, I see one by Marcel M. Cary (marcel@oak.homeunix.org) He says in a commit (it happens to be about git-pull but I think it is relevant) "git pull" fails because POSIX shells have a notion of current working directory that is different from getcwd(). The shell stores this path in PWD. As a result, "cd ../" can be interpreted differently in a shell script than chdir("../") in a C program. The shell interprets "../" by essentially stripping the last textual path component from PWD, whereas C chdir() follows the ".." link in the current directory on the filesystem. When PWD is a symlink, these are different destinations. As a result, Git's C commands find the correct top-level working tree, and shell scripts do not. https://github.com/git/git/commit/08fc0608657ee91bc85276667804c36a93138c7d SO I'd say part of the reason is because git-bisect is a shell script which can't be trusted to find the toplevel on its own (when symlinks are involved).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12479742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4757/']}
jdg_377673
stackexchange
llm_judgeable_groundtruth_similarity
3815412
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to figure out which module in my CGI::Application is loading Moose. I attempted to overload "require" but I don't seem to have the syntax quite right. If someone could clean up the following code I would appreciate it: use strict;use warnings;use Carp qw//;BEGIN { *CORE::GLOBAL::require = sub (*) { warn "Requiring $_[0] at: " . Carp::longmess(); CORE::require (@_); };} Basically, the problem with this script is that it isn't actually loading anything. When CORE::require(@ ) is called is doesn't "do" anything. I tried just passing it the script name directly using $ [0], but that just resulted in the script deadlocking until it timed out. NOTE: The above script is at the beginning of my start up script Now provide the response and nothing else.
Hows about: BEGIN { unshift @INC, sub { printf "Moose first called by pkg %s at line %d in %s\n", (caller)[0,2,1] if $_[1] eq 'Moose.pm'; };} This "works" because subroutine references in @INC are called and passed the coderef and filename as arguments. See require perldoc: As mentioned by phaylon , you can also use Devel::TraceLoad to get a summary of all modules loaded while your application ran (and what line of what file loaded them) with perl -MDevel::TraceLoad=summary my_progam.pl
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3815412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1655251/']}
jdg_377674
stackexchange
llm_judgeable_groundtruth_similarity
31275
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $R$ be a nonzero commutative ring with $1$, such that all finite matrices over $R$ have a Smith normal form . Does it follow that $R$ is a principal ideal domain? If this fails, suppose we additionally suppose that $R$ is an integral domain? What can we say if we impose the additional condition that the diagonal entries be unique up to associates? Now provide the response and nothing else.
The implication is false without the assumption that R is Noetherian, because finite matrices don't detect enough information about infinitely generated ideals. For example, let R be the ring$$\bigcup_{n \geq 0} k[[t^{1/n}]]$$where $k$ is a field (an indiscrete valuation ring). Any finite matrix with coefficients in R comes from a subring $k[[t^{1/N}]]$ for some large $N$, and hence can be reduced to Smith normal form within this smaller PID. However, the ideal $\cup (t^{1/N})$ is not principal.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/31275', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_377675
stackexchange
llm_judgeable_groundtruth_similarity
10249302
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently slugging it out with TeamCity trying to get two build configuration working for an ASP.NET MVC 3 solution. My setup is pretty much identical to the guidance at http://www.troyhunt.com/2010/11/you-deploying-it-wrong-teamcity_26.html . When it builds the .sln in the first "Build & Test" build configuration, everything works great. But in the "Package & Deploy" configuration, when I'm having MSBuild build the MyWebProject.csproj file directly, it seems to be resolving core .NET references to .NET 3.5 assemblies, and not .NET 4.0 assemblies. Accordingly, I'm getting all kinds of .NET 3.5 compilation errors, such as "{ get; set; }" properies needing bodies since they're not marked as abstract. Additionally, what makes me think that it's picking up v3.5 assemblies, is that during the TeamCity CoreCompile - Csc build activity, it says "[Csc] c:\Program Files\TeamCity\buildAgent\work\651adc4c97432014\packages\DataAnnotationsExtensions.1.0.2.0\lib\NETFramework40\DataAnnotationsExtensions.dll error CS1705: Assembly 'DataAnnotationsExtensions, Version=1.0.2.0, Culture=neutral, PublicKeyToken=358a5681c50fd84c' uses 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'" Now if I explicitly set the version to "Version=4.0.0.0" in the web project's .csproj file, then it starts giving me similar exceptions on other core .NET assemblies, such as System.Core.dll; i.e., it keeps trying to resolve references to v3.5 assemblies instead of v4.0. Interestingly, I know it's using the MSBuild for v4.0, because the build log states "Using user-defined MSBuild from: C:\Windows\Microsoft.NET\Framework\v4.0.30319." My command line parameters, begin passed to the MSBuild configuration, is as follows: /P:Configuration=%env.Configuration%/P:DeployOnBuild=True/P:DeployTarget=MSDeployPublish/P:MsDeployServiceUrl=https://%env.TargetServer%/MsDeploy.axd/P:AllowUntrustedCertificate=True/P:MSDeployPublishMethod=WMSvc/P:CreatePackageOnPublish=True/P:UserName=MyUsername/P:Password=MyPassword I've done the following on the build server:* Installed "Microsoft Windows SDK for Windows 7 and .NET Framework 4"* Installed VS 2010 (was hoping to avoid this)* Installed ASP.NET MVC 3* Added the evn.MSBuild set to %system.DotNetFramework4.0_x86_Path%.* Added the registry key HKLM/SOFTWARE/Microsoft/.NETFramework/SDKInstallRootv2.0 to be "C:\Program Files\Microsoft SDKs\Windows\v7.1." Thanks for any help you can provide! Billy McCafferty Now provide the response and nothing else.
What you gotta do is make sure a few things are set when you are building the project... I typically break it into two steps 1) build the solution In this step make sure the visual studio version is set to 2010. 2) Prebuild Web In this step I invoke commands to build the web project and generate the deployable, set the framework version for the msbuild step and appropriate and platform. Set the targets to "ResolveReferences;_CopyWebApplication" The build file path should be pointed to the csproj file for the mvc application The last required step is to set a few build parameters. system.Configuration => Release system.OutputPath => C:\inetpub\wwwroot\foo\bin system.WebProjectOutputDir => C:\inetpub\wwwroot\foo
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10249302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002157/']}
jdg_377676
stackexchange
llm_judgeable_groundtruth_similarity
619050
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 saw partial information, old information, but nothing as good as the actual sample files with brief comments that I have locally. I need to understand the exact relationship between odbc.ini and odbcinst.ini .Superficially it is pretty obvious - at the top of the odbc.ini file there is a section like: [ODBC Data Sources]MYDSN = MyDriverName... However, I am not sure if I can, for example, have settings in either the driver or the DSN section. 1) I have a line Driver = /path/to/file/.so in both files and the values sometimes differ. Does this even make sense? If so, which prevails? 2) Is odbcinst.ini a JavaScript-like "prototype" for odbc.ini ? In other words, if I am creating a number of DSNs with common settings, can I promote common settings from odbc.ini into odbcinst.ini ? 3) What is the difference between Driver and Setup in odbcinst.ini ? They seem to have the same values. Are these settings database-specific or are they universal? Now provide the response and nothing else.
I use FreeTDS on Debian to connect a php -driven website to a MS-SQL Server 2005 Database. The explanation I can give to the config files: /etc/odbc.ini Holds the instance that is referred to within the handler (e.g. php ) that connects to the database (see example below). The configuration defines the server it needs to connect to. [freetds_odbc_connection]Driver = FreeTDSDescription = testDatabase = MyCompanyDbServer = frodoReadonly = YesPort = 1433Trace = No - /etc/odbcinst.ini Holds the configuration for the Driver section in odbc.ini . [FreeTDS]Description = TDS connectionDriver = /usr/lib/odbc/libtdsodbc.soSetup = /usr/lib/odbc/libtdsS.soUsageCount = 1FileUsage = 1Trace = YesTraceFile = /tmp/odbcinst_tr - show-companies.php Example php code to demonstrate how I set up and use the connection. $host="freetds_odbc_connection"; $user="freetds"; $password="secretpassword"; $conn_id = odbc_connect($host, $user ,$password) or die (odbc_errormsg()); $sql_companies = "SELECT * from AMGR_Client_Tbl WHERE Record_Type='1'"; $query_companies = odbc_exec($conn_id, $sql_companies); while (odbc_fetch_row($query_companies)) { $client_id = odbc_result($query_companies, 6); $company_name = odbc_result($query_companies, 9); } etc.. etc.. I'm sure there's many other variables that can be set and used but this is the simplest explanation I can give of the files you asked about.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/619050', 'https://serverfault.com', 'https://serverfault.com/users/236770/']}
jdg_377677
stackexchange
llm_judgeable_groundtruth_similarity
51173976
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include <stdio.h>#include <string.h>int main(void){ char ch='a'; printf("sizeof(ch) = %d\n", sizeof(ch)); printf("sizeof('a') = %d\n", sizeof('a')); printf("sizeof('a'+'b'+'C') = %d\n", sizeof('a'+'b'+'C')); printf("sizeof(\"a\") = %d\n", sizeof("a"));} This program uses sizeof to calculate sizes. Why is the size of 'a' different from the size of ch (where ch='a' )? sizeof(ch) = 1sizeof('a') = 4sizeof('a'+'b'+'C') = 4sizeof("a") = 2 Now provide the response and nothing else.
TL;DR - sizeof works on the type of the operand. sizeof(ch) == sizeof (char) -------------------(1) sizeof('a') == sizeof(int) --------------------(2) sizeof ('a'+ 'b' + 'c') == sizeof(int) ---(3) sizeof ("a") == sizeof (char [2]) ----------(4) Let's see each case now. ch is defined to be of char type, so , pretty straightforward. In C, sizeof('a') is the same as sizeof (int) , as a character constant has type integer. Quoting C11 , An integer character constant has type int . [...] In C++, a character literal has type char . sizeof is a compile-time operator (except when the operand is a VLA), so the type of the expression is used. As earlier , all the integer character constants are of type int , so int + int + int produces int . So the type of the operand is taken as int . "a" is an array of two char s, 'a' and 0 (null-terminator) ( no, it does not decay to pointer to the first element of the array type ), hence the size is the same as of an array with two char elements. That said, finally, sizeof produces a result of type size_t , so you must use %zu format specifier to print the result.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51173976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9999814/']}
jdg_377678
stackexchange
llm_judgeable_groundtruth_similarity
23354359
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 simply trying to get milliseconds to display the first two digits of the variable. What I expect to work (I see two digits initially, then as it is incremented I see three digits): @Overridepublic String toString() { Long milliSeconds = TimeUnit.MILLISECONDS.toMillis(elapsedTime) % 1000; Long seconds = (TimeUnit.MILLISECONDS.toSeconds(elapsedTime)); return String.format("%2d.%02d seconds", seconds, milliSeconds);} What actually works: @Overridepublic String toString() { String milliSeconds = String.format("%02d", TimeUnit.MILLISECONDS.toMillis(elapsedTime) % 1000).substring(0, 2); Long seconds = (TimeUnit.MILLISECONDS.toSeconds(elapsedTime)); return String.format("%2d.%s seconds", seconds, milliSeconds);} Or: @Overridepublic String toString() { double milliSeconds = (double)(TimeUnit.MILLISECONDS.toMillis(elapsedTime) % 1000) / 1000; Long seconds = (TimeUnit.MILLISECONDS.toSeconds(elapsedTime)); return String.format("%.2f seconds", seconds + milliSeconds);} I guess my first question would be are either of my solutions that work more resource intensive than the one that doesn't? And secondly, what am I doing wrong in the first solution? I would expect %02d to take the long and truncate it to 2 digits buffered with a 0. Instead I see the two digits plus a trailing 0. Now provide the response and nothing else.
I tried this solution of mine and it worked. Run the script on dom ready using jquery. basically instead of using your function initialize like this : function initialize(){/*You code */} do this: $(function(){/*You code */}) And no need for google.maps.event.addDomListener(window, 'load', initialize); Anymore. Edit #1 : I am currently facing some familiar problem to yours, and I think I have a better solution to you now. in your JS file, after your initialize function , put this function: var ready: // Where to store the function ready = function() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'libraries=places&'+'callback=initialize'; document.body.appendChild(script); }; What it basically does is that it calls for the map loader first, and then calls for the map after the loader is ready. And afterwards make use of you what just wrote with this In your html page : <script> $.getScript("You js file path",function(){ $(document).ready(ready); });</script> And this gets the script so you can use its variables, and then call the variable you need ready after the DOM is ready and finished loading. I recommend putting this at the bottom of your html page,after the body closes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23354359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/679716/']}
jdg_377679
stackexchange
llm_judgeable_groundtruth_similarity
32044846
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 a regular expression to validate durations in the ISO 8601 duration format (with the exception of fractional parts which I don't need). PnYnMnDTnHnMnS PnW Here is what I have: ^P(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(\d+H)?(\d+M)?(\d+S)?)?$ The only problem is that the strings P and PT are allowed with this regex as all of the parts are "zero or one" ? . There needs to be at least one component (date or time) If there is a T then there needs to be a time component (H, M, or S) If there is a T then there may or may not be any date components (Y, M, or D) Overflow is allowed (e.g. P72H is mostly equivalent to P3D ) Acceptable inputs: P1Y // date component onlyP2MT30M // date and time componentsPT6H // time component onlyP5W // another date component Unacceptable inputs: P // no componentsPT // no componentsP3MT // T specified but not time components Right now the invalid strings are passing client-side validation but failing on the server-side because it's passed into DateInteval but I'd like to fail on the client side if possible. If everyone was using Chrome 40+ I could specify minlength='3' on the input element to help but that isn't the case unfortunately. Now provide the response and nothing else.
If you have almost all parts optional, but you want to make sure there is something else after P or T , you can make use of look-aheads: ^P(?=\d+[YMWD])(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d+[HMS])(\d+H)?(\d+M)?(\d+S)?)?$ ^^^^^^^^^^^^ ^^^^^^^^^^^^ They require a sequence of digits followed by a letter from the specified set to appear right after the preceding pattern. See demo UPDATE If P can be "empty", use ^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d+[HMS])(\d+H)?(\d+M)?(\d+S)?)?$ See another demo . Here, (?!$) makes sure the string is not equal to P , and there must be some other symbols on the right. Or, as @UlugbekUmirov suggests, it is enough to just use T(?=\d) (since all the optional parts start with a digit): ^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$ UPDATE 2 If the numbers can be both float or integers, add (?:\.\d+)? after each \d+ . Here is an updated pattern from Update 1: ^P(?!$)(\d+(?:\.\d+)?Y)?(\d+(?:\.\d+)?M)?(\d+(?:\.\d+)?W)?(\d+(?:\.\d+)?D)?(T(?=\d)(\d+(?:\.\d+)?H)?(\d+(?:\.\d+)?M)?(\d+(?:\.\d+)?S)?)?$
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32044846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404623/']}
jdg_377680
stackexchange
llm_judgeable_groundtruth_similarity
7897339
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Whenever there is a call to an undefined function, no errors are logged. Instead the script just stops executing. To make things worse, if I run php -l filename.php, It shows that there are no syntax errors. I am using a custom error handler function, but even the first line is never reached. How can I get it to run my error handler when there is a call to an undefined function? I am using PHP 5.3.2-1. Here is the code that is setting the error handler: error_reporting(-1);$old_error_handler = set_error_handler( "userErrorHandler" );set_exception_handler('exception_handler'); Neither the error handler nor the exception handler are being reached, although they do work for other errors. The reason I want this is I end up having to place debug statements in my code to see how far it gets before it stops executing which is a slow process compared to an error message that would tell me the file and line number where the error is. Now provide the response and nothing else.
Fatal errors can not be caught by a user error handler. See http://php.net/manual/en/function.set-error-handler.php Specifically the part: The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called. And as per the comments on the PHP manual page, one work around is to test for errors in the shutdown function: <?php error_reporting(E_ALL); ini_set('display_errors', 0); function shutdown(){ $isError = false; if ($error = error_get_last()){ switch($error['type']){ case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: $isError = true; break; } } if ($isError){ echo "Script execution halted ({$error['message']})"; } else { echo "Script completed"; } } register_shutdown_function('shutdown');?>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7897339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172274/']}
jdg_377681
stackexchange
llm_judgeable_groundtruth_similarity
47042261
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 brand new to Angular 2/4 and have been enjoying the Material Design components ( https://material.angular.io ). I have a simple SPA which uses a tab group for switching between dynamic views. I have a plus button for adding more tabs and each tab can deleted itself. My question is whether the mat-tab-group can be altered to contain the "plus" button in the upper bar (where the tabs appear). Right now it sits in a div beside the mat-tab-group div, and thus takes up 20px along the whole right side of my web-page, which does not look terribly nice. Now provide the response and nothing else.
One approach would be to add another disabled tab with no content and attach the click event to a button in the tab label. <mat-tab-group> <mat-tab label="Tab 1">Tab 1 Content</mat-tab> <mat-tab label="Tab 2">Tab 2 Content</mat-tab> <mat-tab disabled> <ng-template mat-tab-label> <button mat-icon-button (click)="someFn()"> <mat-icon>add_circle</mat-icon> </button> </ng-template> </mat-tab></mat-tab-group> The only odd thing is the width of the tab label. I haven't been able to figure out how to reduce that specific one.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47042261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/991985/']}
jdg_377682
stackexchange
llm_judgeable_groundtruth_similarity
6220756
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Sorry for this curiosity that I have. sha1 use [a-f0-9] chars for its hashing function. May I know why it doens't use all the chars possible [a-z0-9] by using all chars availabe it could grealty increase the number of possibile different hash, thus lowering the probabilty of possibile collision. If you don't think this is a real question, just leave a comment I will instantly delete this question. === As stated in the answer, sha1 does NOT uses only 16 chars . The correct fact is: sha1 is 160 bits of binary data (cit.). I have added this to prevent confusion. Now provide the response and nothing else.
You're confusing representation with content . sha1 is 160 bits of binary data. You can just as easily represent it with: hex: 0xf1d2d2f924e986ac86fdf7b36c94bcdf32beec15decimal: 1380568310619656533693587816107765069100751973397binary: 1111000111010010110100101111100100100100111010011000011010101100100001101111110111110111101100110110110010010100101111001101111100110010101111101110110000010101base 62: xufK3qj2bZgDrLA0XN0cLv1jZXc There's nothing magical about hexidecimal. It's just very common mechanism for showing content that breaks easily along 4-bit boundaries. The base 62 output is generated with this little bit of ruby: #!/usr/bin/rubydef chars_from_hex(s) c = s % 62 s = s / 62 if ( s > 0 ) chars_from_hex(s) end if (c < 10) print c elsif (c < 36) print "abcdefghijklmnopqrstuvwxyz"[c-11].chr() elsif (c < 62) print "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[c-37].chr() else puts "error c", c endendchars_from_hex(0xf1d2d2f924e986ac86fdf7b36c94bcdf32beec15) It uses the standard idiom for converting from one base to another and treats 0-9 as 0-9, a-z as 10-35, A-Z as 36-61. It could be trivially extended to support more digits by including e.g. !@#$%^&*()-_=+\|[]{},.<>/?;:'"~` if one so desired. (Or any of the vast array of Unicode codepoints .) @yes123 asked about the ascii representation of the hash specifically, so here is the result of interpreting the 160-bit hash directly as ascii: ñÒÒù$é¬ý÷³l¼ß2¾ì It doesn't look like much because: ascii doesn't have a good printable representation for byte values less than 32 ascii itself can't represent byte values greater than 127, between 127 and 255 gets interpreted according to iso-8859-01 or other character encoding schemes This base conversion can be practically useful, too; the Base64 encoding method uses 64 (instead of my 62) characters to represent 6 bits at a time; it needs two more characters for 'digits' and a character for padding. UUEncoding chose a different set of 'digits'. And a fellow stacker had a problem that was easily solved by changing the base of input numbers to output numbers .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6220756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496223/']}
jdg_377683
stackexchange
llm_judgeable_groundtruth_similarity
263043
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm monitoring my home network with Wireshark, since I believe my computer is being actively hacked. I looked up a LOT of IP addresses, but didn't find any suspicious ones. Can a connection be hidden from Wireshark? What evasion techniques do hackers usually employ? Now provide the response and nothing else.
By requiring a VPN you prevent the others from connecting to your RDP port directly. They have to go through your VPN first, and only then they can start connecting to your RDP. Effectively, you're putting a shield in front of your RDP. You do not want the entire internet to connect to complex services such as RDP or SMB directly. Since they're complex services, they tend to have a much larger attack surface than the VPN service. In addition, with VPN, your only biggest priority is to keep your VPN service patched and secure. Of course, you need to patch all your systems and everything, but it's only your VPN service that's facing the internet and getting pounded with attacks, where it's really time critical that you patch it asap. Your RDP and SMB should still be patched, but your attackers are no longer the entire internet, but rather users you have already authenticated (and who may or not may have viruses). Basically, instead of having multiple ports with services that you all need to keep secure, and that might not even be designed to be facing an untrusted network in the first place, you have a single port with a service that has definitely been designed to be facing said untrusted network. A user connecting to your VPN also doesn't necessarily have access to your full network - you can set up firewall rules to prevent them from doing anything but connect to the specific hosts and ports you allow. These firewall rules can also be user-dependent, so some users could, for example, access only RDP, while others can access greater portions of your network. As you authenticated your users, you can do that - the port-forwarding from your router doesn't know who's connecting, and so it just forwards regardless of who it is. Another reason, if you want to talk at a non-technical level, is that it's recommended to do so, simply because Microsoft themselves recommends against RDP or SMB being directly exposed to the internet, and as such you do something, so that it isn't. If you consider all that, using a well-configured VPN as an entry point makes it much more difficult to attack your services directly, which is why it's generally recommended to do so.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/263043', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/279695/']}
jdg_377684
stackexchange
llm_judgeable_groundtruth_similarity
2047793
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between override and overload? Now provide the response and nothing else.
Overloading: picking a method signature at compile time based on the number and type of the arguments specified Overriding: picking a method implementation at execution time based on the actual type of the target object (as opposed to the compile-time type of the expression) For example: class Base{ void foo(int x) { System.out.println("Base.foo(int)"); } void foo(double d) { System.out.println("Base.foo(double)"); }}class Child extends Base{ @Override void foo (int x) { System.out.println("Child.foo(int)"); }}...Base b = new Child();b.foo(10); // Prints Child.foo(int)b.foo(5.0); // Prints Base.foo(double) Both calls are examples of overloading . There are two methods called foo , and the compiler determines which signature to call. The first call is an example of overriding . The compiler picks the signature "foo(int)" but then at execution time, the type of the target object determines that the implementation to use should be the one in Child .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2047793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190623/']}
jdg_377685
stackexchange
llm_judgeable_groundtruth_similarity
271054
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $X\rightarrow \mathbb P^n_{\mathbb C}$ be a double cover ramified over a smooth hypersurface $B$ of degre $2d$. In the case of hypersurfaces of $\mathbb P^n$ one can determine the integral cohomology using Lefschetz hyperlane section theorem and universal coefficients theorem. Q. Are there some simple techniques allowing to compute $H^k(X,\mathbb Z)$ for any $k$? Now provide the response and nothing else.
If $\pi \colon X \longrightarrow Y$ is a cyclic cover of complex projective manifolds of dimension $n$ branched along an ample divisor $B \subset Y$, then by a variation of Lefschetz Hyperplane Theorem one can show that the pullback map $$\pi^* \colon H^i(Y, \, \mathbb{Z}) \longrightarrow H^i(X, \, \mathbb{Z})$$ is an isomorphism for $i \leq n-1$ and is injective for $i=n$, see Proposition 1.1 in [1] . The corresponding dual result for the push-forward map in integral homology is also true, see Proposition 1.11 in [2] . Using Poincaré duality, from this it follows that all Betti numbers of $X$ and $Y$ are equal, except possibly the middle Betti number, for which we have $b_n(X) \geq b_n(Y)$. On the other hand, in your case we can easily find the topological Euler number $\chi_{\mathrm{top}}(X)$ by additivity. In fact the ramification locus $R \subset X$ is isomorphic to the (smooth) branch locus $S \subset \mathbb{P}^n$ and the restriction $\pi \colon X - R \longrightarrow \mathbb{P}^n - S$ is an unramified double cover, so we obtain$$\chi_{\mathrm{top}}(X) = 2(\chi_{\mathrm{top}}(\mathbb{P}^n) - \chi_{\mathrm{top}}(S))+ \chi_{\mathrm{top}}(R) = 2\chi_{\mathrm{top}}(\mathbb{P}^n) - \chi_{\mathrm{top}}(S)$$and this allows us to recover $b_n(X)$ as well. ${}$ References [1] J. A. Wisniewski: On topological properties of some coverings. An addendum to a paper of Lanteri and Struppa , Can. J. Math. 44 , No.1, 206-214 (1992). ZBL0766.14012 . [2] A. Lanteri, D. C. Struppa: Topological properties of cyclic coverings branched along an ample divisor , Can. J. Math. 41 , No.3, 462-479 (1989). ZBL0699.14019 .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/271054', 'https://mathoverflow.net', 'https://mathoverflow.net/users/85595/']}
jdg_377686
stackexchange
llm_judgeable_groundtruth_similarity
34041
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to calculate the velocity of an asteroid orbiting around a star (Sun) at the perihelion of its orbit. I know the excentricity of the ellipse and its semimajor axis. I have found that the vis-viva equation is used to calculate the velocity of an object on an elliptical orbit and that the perihelion is at distance r = a(1-e). However I (simply enough) cannot see how to mathematically combine these two pieces of information in order to get the velocity at the perihelion. (I am not so much looking for just a formula but rather a proof/intuition regarding how to get from the vis-visa equation for velocity to a perihelion velocity equation) Now provide the response and nothing else.
The vis-viva equation is commonly written like this: $$v^2 = GM\left(\frac{2}{r} - \frac{1}{a}\right)$$ . For $r=a(1-e)$ : $$v = \sqrt{GM\left(\frac{2}{a(1-e)} - \frac{1}{a}\right)} = \sqrt{GM\frac{1}{a}\left(\frac{2}{1-e}-1\right)} = \sqrt{GM\frac{1}{a}\left(\frac{1+e}{1-e}\right)}$$ . The derivation of the vis-viva equation is not at all trivial and can be found here . The product $GM$ is also called the standard gravitational parameter and for solar system bodies is often known more accurately than $G$ and $M$ separately. For the Sun $GM_☉$ is about 1.327E+20 m³ s⁻² which in different units is 1.327E+11 km³ s⁻² or about 1.0 AU³ year⁻².
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/34041', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/31021/']}
jdg_377687
stackexchange
llm_judgeable_groundtruth_similarity
56349
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: This is probably an extremely simple question. I have a manipulate that sets variables used to define an offset, amplitude, frequency and phase of a trigonometric function. Manipulate[ Module[{Vac,Vdc, ω, ϕ, f}, Vac = ctrlVac; (* AC Voltage *) Vdc = ctrlVdc; (* DC Offset *) f = ctrlf; (* Frequency *) ω = 2 π f; ϕ = ctrlPhi; (* Phase Offset *) gFunc = ctrlgFunc; (* Function *) Plot[ Vdc + Vac gFunc[ ω t + ϕ],{t,0, 0.4}]], {{ctrlgFunc,Sin,""},{Sin,Cos, Tan, Cot }},Delimiter, {{ctrlVac,1.5,Subscript["V","ac"]}, -10,10}, {{ctrlVdc, 0.5, Subscript["V","dc"]}, -1,1},Delimiter, {{ctrlf, 10, "Frequency"}, 0.001,100}, {{ctrlPhi, 0, "ϕ"}, 0, 2 π}, ControlPlacement->Left, Paneled->True] I would like to use the Manipulate as an editor that sets the values of the variables in the code snippet above and then passes them on as parameters to a function along with other sets of variables. Is there a way to add a button to save the current values to a dataset? Now provide the response and nothing else.
I think I have it this time: Here's the Manipulate , I removed the Module and cleaned up the Symbols a bit Manipulate[(*Function*) Plot[ctrlVdc + ctrlVac ctrlgFunc[2 Pi ctrlf t + ctrlPhi], {t, 0, 0.4}], {{ctrlgFunc, Sin, ""}, {Sin, Cos, Tan, Cot}}, Delimiter, {{ctrlVac, 1.5, Subscript["V", "ac"]}, -10, 10}, {{ctrlVdc, 0.5, Subscript["V", "dc"]}, -1, 1}, Delimiter, {{ctrlf, 10, "Frequency"}, 0.001, 100}, {{ctrlPhi, 0, "ϕ"}, 0, 2 π}, Delimiter, Button[ "Store", d = Dataset[Association @ {gFunc -> ctrlgFunc, Vac -> ctrlVac, Vdc -> ctrlVdc, ϕ -> ctrlPhi, ω -> 2 Pi ctrlf}]], ControlPlacement -> Left, Paneled -> True] A Button has been added that, when pressed, creates a Dataset , d, that can be referenced outside of the Manipulate . d
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/56349', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/3059/']}
jdg_377688
stackexchange
llm_judgeable_groundtruth_similarity
28542251
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following in my .gitconfig file: [user] name = myname email = myname@gmail.com[core] autocrlf = true excludesfile = C:\\Users\\myname\\Documents\\gitignore_global.txt[diff] tool = meld[difftool "meld"] cmd = "C:/Program Files (x86)/Meld/meld/meld.exe" prompt = false[merge] tool = meld[mergetool "meld"] cmd = "C:/Program Files (x86)/Meld/meld/meld.exe"[difftool "sourcetree"] cmd = "C:/Program Files (x86)/Meld/meld/meld.exe $PWD/$LOCAL $PWD/$BASE $PWD/$REMOTE"[mergetool "sourcetree"] cmd = 'C:/Program Files (x86)/Meld/meld/meld.exe' \"$LOCAL\" \"$REMOTE\" \"$MERGED\" trustExitCode = true And in Sourcetree, I have the following settings: However, when I right-clicked a file on Sourcetree to do an external diff, I was able to open Meld, but the contents of the file were not displayed at all. What have I done wrong in the settings? Now provide the response and nothing else.
The actual setting to use here in order to have a real 3-way merge, with read only THEIRS and MINE tabs is this: $LOCAL $BASE $REMOTE --auto-merge --output=$MERGED Note the = after --output . I've finally got this command right by digging in comments on the second answer to this question Git merging using Meld .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28542251', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1841131/']}
jdg_377689
stackexchange
llm_judgeable_groundtruth_similarity
71117
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have this assertion: if $p$ is a prime such that $p\equiv 11 \pmod{56}$, then $p$ splits in $\mathbb{Z}[\sqrt{14}]$ (the discriminant of $\mathbb{Z}[\sqrt{14}]$ is $56$.) Why? Does $p\equiv 11\pmod{56}$ imply $14$ is a quadratic residue mod $p$? Now provide the response and nothing else.
If we have a quadratic field $K = \mathbb{Q}(\sqrt{d})$ with $d$ squarefree, then an odd prime $p$ splits if and only if $\left(\frac{d}{p}\right) = 1$. Claim : If $q$ is an odd prime with $q \equiv 3 \pmod 4$, then $q$ is a quadratic residue mod $p$ if and only if $p \equiv \pm b^2 \pmod {4q}$, where $b$ is an odd integer prime to $q$. The proof is straightforward from the law of quadratic reciprocity. So, $\left(\frac{14}{p}\right) = \left(\frac{2}{p}\right) \left(\frac{7}{p}\right)$. $2$ is a quadratic residue mod $p$ if and only if $p \equiv \pm 1 \pmod 8$. Since $p \equiv 11 \pmod {56}$ we see that $p \equiv 3 \pmod 8$. So $\left( \frac{2}{p}\right) = -1$. On the other hand, we can use the claim above to calculate $\left(\frac{7}{p}\right)$. So we need only check that $p \equiv \pm b^2 \pmod {28}$. Since $p \equiv 11 \pmod {56}$, $p \equiv 11 \pmod {28}$. And simple computation shows that $\pm 11$ are non-quadratic residues mod $28$. Hence $\left(\frac{7}{p}\right) = -1$. So $\left(\frac{14}{p}\right) = 1$, and so $p$ splits in $\mathcal{O}_K = \mathbb{Z}[\sqrt{14}]$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/71117', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17346/']}
jdg_377690
stackexchange
llm_judgeable_groundtruth_similarity
25168062
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 is i++ not atomic in Java? To get a bit deeper in Java I tried to count how often the loop in threads are executed. So I used a private static int total = 0; in the main class. I have two threads. Thread 1: Prints System.out.println("Hello from Thread 1!"); Thread 2: Prints System.out.println("Hello from Thread 2!"); And I count the lines printed by thread 1 and thread 2. But the lines of thread 1 + lines of thread 2 don't match the total number of lines printed out. Here is my code: import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.logging.Level;import java.util.logging.Logger;public class Test { private static int total = 0; private static int countT1 = 0; private static int countT2 = 0; private boolean run = true; public Test() { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); newCachedThreadPool.execute(t1); newCachedThreadPool.execute(t2); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } run = false; try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } System.out.println((countT1 + countT2 + " == " + total)); } private Runnable t1 = new Runnable() { @Override public void run() { while (run) { total++; countT1++; System.out.println("Hello #" + countT1 + " from Thread 2! Total hello: " + total); } } }; private Runnable t2 = new Runnable() { @Override public void run() { while (run) { total++; countT2++; System.out.println("Hello #" + countT2 + " from Thread 2! Total hello: " + total); } } }; public static void main(String[] args) { new Test(); }} Now provide the response and nothing else.
i++ is probably not atomic in Java because atomicity is a special requirement which is not present in the majority of the uses of i++ . That requirement has a significant overhead: there is a large cost in making an increment operation atomic; it involves synchronization at both the software and hardware levels that need not be present in an ordinary increment. You could make the argument that i++ should have been designed and documented as specifically performing an atomic increment, so that a non-atomic increment is performed using i = i + 1 . However, this would break the "cultural compatibility" between Java, and C and C++. As well, it would take away a convenient notation which programmers familiar with C-like languages take for granted, giving it a special meaning that applies only in limited circumstances. Basic C or C++ code like for (i = 0; i < LIMIT; i++) would translate into Java as for (i = 0; i < LIMIT; i = i + 1) ; because it would be inappropriate to use the atomic i++ . What's worse, programmers coming from C or other C-like languages to Java would use i++ anyway, resulting in unnecessary use of atomic instructions. Even at the machine instruction set level, an increment type operation is usually not atomic for performance reasons. In x86, a special instruction "lock prefix" must be used to make the inc instruction atomic: for the same reasons as above. If inc were always atomic, it would never be used when a non-atomic inc is required; programmers and compilers would generate code that loads, adds 1 and stores, because it would be way faster. In some instruction set architectures, there is no atomic inc or perhaps no inc at all; to do an atomic inc on MIPS, you have to write a software loop which uses the ll and sc : load-linked, and store-conditional. Load-linked reads the word, and store-conditional stores the new value if the word has not changed, or else it fails (which is detected and causes a re-try).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25168062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3790360/']}
jdg_377691
stackexchange
llm_judgeable_groundtruth_similarity
24895
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From the news today, it mentions that Jeremy Corbyn and the Labour Party is preparing to deal with a run on the pound. What is a run on the pound? Why is it making news headlines? Why does Jeremy Corbyn plan for this eventuality happening? The article says that it's where investors sell sterling en masse, but what can the Labour Government do in that situation? Now provide the response and nothing else.
A "run on the pound" occurs when financial traders believe that it is not in their interest to own "pounds", but an alternative like dollars or euros, or even gold, is a better currency to own. They will then try to sell pounds, and buy the other currencies. In order to sell quickly they reduce the price at which they are selling pounds. As this happens we say that he value of the pound has dropped. Other investors seeing this drop in price may then try to sell off their pounds very quickly, cutting the price a lot. If everyone is trying to sell, then the value of the pound can drop rapidly against other currencies. This has several consequences. It means that it costs more for a British company to buy things from abroad. The price of imported goods and raw materials goes up. This makes things more expensive. It makes it more costly to travel abroad. On the other hand, if you are making something in Britain and selling it abroad, it makes that thing cheaper, so it makes exporting more profitable, it also makes it cheaper for tourists to visit the UK. It would add to the costs of the government and lead to higher taxes, inflation and slower growth. There was a run on the pound after the vote to leave the EU, there was also a run on the pound when it was forced to leave the ERM in 1992 Generally a run on the pound is a bad thing it destabilises international markets that depend on predictable prices. There is a concern that the level of government borrowing implied by the Labour party's policies would cause financial traders to sell pounds in large enough amounts to cause a run, and this would be damaging to the UK economy. As such the shadow chancellor mentioned in a meeting that he was engaged in planning for this event, even though he said it was unlikely. The fact he mentioned this possibility surprised many journalists, as predicting a run on the pound can be a self-fulfilling prophesy. So a run on the pound is not something that the Labour party planning to have. Instead the Labour party is planning its defensive strategy if a damaging run on the pound occurs.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/24895', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/6297/']}
jdg_377692
stackexchange
llm_judgeable_groundtruth_similarity
44775534
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this under parameter section , Parameters: PlatformSelect: Description: Cockpit platform Select. Type: String Default: qa-1 AllowedValues: [qa-1, qa-2, staging, production] I need to reference this value in my UserData. I’m using Mappings in between. Mappings: bootstrap: ubuntu: print: echo ${PlatformSelect} >>test.txtResources: EC2Instance: Type: AWS::EC2::Instance Properties: InstanceType: !Ref ‘InstanceType’ KeyName: !Ref ‘KeyName’ Tags: - Key: Name Value: Test UserData: Fn::Base64: Fn::Join: - ‘’ - - | #!/bin/bash - Fn::FindInMap: - bootstrap - ubuntu - print - |2+ This is not working. Not sure the way I refer it is wrong in first place!! Should I use something before it like, ‘${AWS::Parameters:PlatformSelect}’ ? Now provide the response and nothing else.
Is there a reason why you are using Mapping in between? You could easily use !Sub instead Resources: EC2Instance: Type: AWS::EC2::Instance Properties: InstanceType: !Ref InstanceType KeyName: !Ref KeyName Tags: - Key: Name Value: Test UserData: Fn::Base64: !Sub | #!/bin/bash ${PlatformSelect}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44775534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2251418/']}
jdg_377693
stackexchange
llm_judgeable_groundtruth_similarity
19474862
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 often read in many places that one should avoid returning an iterable and return a collection instead. For example - public Iterable<Maze> Portals() { // a list of some maze configurations List<Maze> mazes = createMazes(); ... return Collections.unmodifiableList(mazes);} Since returning an iterable is only useful for using it in foreach loop, while collection already provides an iterator and provides much more control. Could you please tell me when it is beneficial to specifically return an iterable in a method? Or we should always return a collection instead? Note : This question is not about Guava library Now provide the response and nothing else.
Returning an Iterable would be beneficial when we need to lazily load a collection that contains a lot of elements. The following quote from Google Collections FAQ seems to support the idea of lazy loading: Why so much emphasis on Iterators and Iterables? In general, our methods do not require a Collection to be passed in when an Iterable or Iterator would suffice. This distinction is important to us, as sometimes at Google we work with very large quantities of data, which may be too large to fit in memory, but which can be traversed from beginning to end in the course of some computation. Such data structures can be implemented as collections, but most of their methods would have to either throw an exception, return a wrong answer, or perform abysmally. For these situations, Collection is a very poor fit; a square peg in a round hole. An Iterator represents a one-way scrollable "stream" of elements, and an Iterable is anything which can spawn independent iterators. A Collection is much, much more than this, so we only require it when we need to.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19474862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1328106/']}
jdg_377694
stackexchange
llm_judgeable_groundtruth_similarity
369185
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 want to see the pagetable that kernel manages for one of my processes. In my case PID 4680 is mapped to dhclient . So in order to view the page table I tried the following: sudo cat /proc/4680/pagemap However this command just hangs on my Ubuntu 14.04 without any output. I have tried waiting 2 minutes and then have to kill it. Is there a better way of doing this? Now provide the response and nothing else.
According to the documentation , /proc/PID/pagemap contains one 64-bit value for each virtual page. With 4096-byte pages and a 64-bit virtual address space, there are 2**52 pages. So the full pagemap file will be 2**52 entries of 8 bytes each. That's a really big file. Catting the whole thing is going to take a long time. Not 2 minutes. A really long time. A speed test on my own computer suggests about 21 years. And it's mostly going to be filled with zeros (for all the virtual addresses that aren't mapped in the process). A bunch of \0 's output to a terminal cause no visible effect. It's not hung, it's doing what you asked. It's not a text file, so the entries that aren't zero aren't likely to look good on your terminal either. The right way to use the pagemap file is to know what virtual address you're looking for, seek to it, and read 8 bytes. Or if you want information for a range, read some multiple of 8 bytes. If you want all the nonzero entries, first read /proc/PID/maps to find what ranges are mapped.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/369185', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/200436/']}
jdg_377695
stackexchange
llm_judgeable_groundtruth_similarity
18621
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: In the discussion following a recent question about whether the standard deviation can exceed the mean, one question was raised briefly but never fully answered. So I am asking it here. Consider a set of $n$ nonnegative numbers $x_i$ where $0 \leq x_i \leq c$ for $1 \leq i \leq n$. It is not required that the $x_i$ be distinct, that is, the set could be a multiset.The mean and varianceof the set are defined as$$\bar{x} = \frac{1}{n}\sum_{i=1}^n x_i, ~~ \sigma_x^2 = \frac{1}{n}\sum_{i=1}^n (x_i - \bar{x})^2 = \left(\frac{1}{n}\sum_{i=1}^n x_i^2\right) - \bar{x}^2$$and the standard deviation is $\sigma_x$. Note that the setof numbers is not a sample from a population and we are not estimating a population mean or a population variance.The question then is: What is the maximum value of $\dfrac{\sigma_x}{\bar{x}}$, the coefficient of variation, over all choices of the $x_i$'s in the interval $[0,c]$? The maximum value that I can find for $\frac{\sigma_x}{\bar{x}}$ is $\sqrt{n-1}$which is achieved when $n-1$ of the $x_i$ have value $0$ and the remaining(outlier) $x_i$has value $c$, giving $$\bar{x} = \frac{c}{n},~~ \frac{1}{n}\sum x_i^2 = \frac{c^2}{n} \Rightarrow \sigma_x = \sqrt{\frac{c^2}{n} - \frac{c^2}{n^2}} = \frac{c}{n}\sqrt{n-1}.$$But this does not depend on $c$ at all, and I am wondering if largervalues, possibly dependent on both $n$ and $c$, can be achieved. Any ideas? I am sure that this question has been studied in the statistical literature before, and so references, if not the actual results, would be muchappreciated. Now provide the response and nothing else.
Geometry provides insight and classical inequalities afford easy access to rigor. Geometric solution We know, from the geometry of least squares , that $\mathbf{\bar{x}} = (\bar{x}, \bar{x}, \ldots, \bar{x})$ is the orthogonal projection of the vector of data $\mathbf{x}=(x_1, x_2, \ldots, x_n)$ onto the linear subspace generated by the constant vector $(1,1,\ldots,1)$ and that $\sigma_x$ is directly proportional to the (Euclidean) distance between $\mathbf{x}$ and $\mathbf{\bar{x}}.$ The non-negativity constraints are linear and distance is a convex function, whence the extremes of distance must be attained at the edges of the cone determined by the constraints. This cone is the positive orthant in $\mathbb{R}^n$ and its edges are the coordinate axes, whence it immediately follows that all but one of the $x_i$ must be zero at the maximum distances. For such a set of data, a direct (simple) calculation shows $\sigma_x/\bar{x}=\sqrt{n}.$ Solution exploiting classical inequalities $\sigma_x/\bar{x}$ is optimized simultaneously with any monotonic transformation thereof. In light of this, let's maximize $$\frac{x_1^2+x_2^2+\ldots+x_n^2}{(x_1+x_2+\ldots+x_n)^2} = \frac{1}{n}\left(\frac{n-1}{n}\left(\frac{\sigma_x}{\bar{x}}\right)^2+1\right) = f\left(\frac{\sigma_x}{\bar{x}}\right).$$ (The formula for $f$ may look mysterious until you realize it just records the steps one would take in algebraically manipulating $\sigma_x/\bar{x}$ to get it into a simple looking form, which is the left hand side.) An easy way begins with Holder's Inequality , $$x_1^2+x_2^2+\ldots+x_n^2 \le \left(x_1+x_2+\ldots+x_n\right)\max(\{x_i\}).$$ (This needs no special proof in this simple context: merely replace one factor of each term $x_i^2 = x_i \times x_i$ by the maximum component $\max(\{x_i\})$: obviously the sum of squares will not decrease. Factoring out the common term $\max(\{x_i\})$ yields the right hand side of the inequality.) Because the $x_i$ are not all $0$ (that would leave $\sigma_x/\bar{x}$ undefined), division by the square of their sum is valid and gives the equivalent inequality $$\frac{x_1^2+x_2^2+\ldots+x_n^2}{(x_1+x_2+\ldots+x_n)^2} \le \frac{\max(\{x_i\})}{x_1+x_2+\ldots+x_n}.$$ Because the denominator cannot be less than the numerator (which itself is just one of the terms in the denominator), the right hand side is dominated by the value $1$, which is achieved only when all but one of the $x_i$ equal $0$. Whence $$\frac{\sigma_x}{\bar{x}} \le f^{-1}\left(1\right) = \sqrt{\left(1 \times (n - 1)\right)\frac{n}{n-1}}=\sqrt{n}.$$ Alternative approach Because the $x_i$ are nonnegative and cannot sum to $0$, the values $p(i) = x_i/(x_1+x_2+\ldots+x_n)$ determine a probability distribution $F$ on $\{1,2,\ldots,n\}$. Writing $s$ for the sum of the $x_i$, we recognize $$\eqalign{\frac{x_1^2+x_2^2+\ldots+x_n^2}{(x_1+x_2+\ldots+x_n)^2} &= \frac{x_1^2+x_2^2+\ldots+x_n^2}{s^2} \\&= \left(\frac{x_1}{s}\right)\left(\frac{x_1}{s}\right)+\left(\frac{x_2}{s}\right)\left(\frac{x_2}{s}\right) + \ldots + \left(\frac{x_n}{s}\right)\left(\frac{x_n}{s}\right)\\&= p_1 p_1 + p_2 p_2 + \ldots + p_n p_n\\&= \mathbb{E}_F[p].}$$ The axiomatic fact that no probability can exceed $1$ implies this expectation cannot exceed $1$, either, but it's easy to make it equal to $1$ by setting all but one of the $p_i$ equal to $0$ and therefore exactly one of the $x_i$ is nonzero. Compute the coefficient of variation as in the last line of the geometric solution above.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/18621', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/6633/']}
jdg_377696
stackexchange
llm_judgeable_groundtruth_similarity
118792
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: Could someone explain the following? $$ \nabla_X \operatorname{tr}(AXB) = BA $$ I understand that $$ {\rm d} \operatorname{tr}(AXB) = \operatorname{tr}(BA \; {\rm d} X) $$ but I don't quite understand how to move ${\rm d} X$ out of the trace. Now provide the response and nothing else.
The notation is quite misleading (at least for me). Hint: Does it make sense that$$\frac{\partial}{\partial X_{mn}} \mathop{\rm tr} (A X B) = (B A)_{nm}?$$ More information: $$\frac{\partial}{\partial X_{mn}} \mathop{\rm tr} (A X B) = \frac{\partial}{\partial X_{mn}} \sum_{jkl} A_{jk} X_{kl} B_{lj}= \sum_{jkl} A_{jk} \delta_{km} \delta_{nl} B_{lj}= \sum_{j} A_{jm} B_{nj} =(B A)_{nm}. $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/118792', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19141/']}
jdg_377697
stackexchange
llm_judgeable_groundtruth_similarity
12327
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: May a former U.S. president be part of a successor's administration? More specifically, may Hillary Clinton make Barack Obama a member of her cabinet? Are there even any historic precedents for such a move? Now provide the response and nothing else.
The relevant legislation appears to be the United States constitution (which defines some of the processes and procedures around the office of the President) and the United States Code (which includes some description of the scope of the Executive branch). The only specific proscription on the activities of former presidents seems to be the 22nd Amendment which states that No person shall be elected to the office of the President more than twice, and no person who has held the office of President, or acted as President, for more than two years of a term to which some other person was elected President shall be elected to the office of the President more than once. But this article shall not apply to any person holding the office of President when this article was proposed by the Congress, and shall not prevent any person who may be holding the office of President, or acting as President, during the term within which this article becomes operative from holding the office of President or acting as President during the remainder of such term. It's fairly clear that this doesn't apply to other executive offices. In practice this is fairly unlikely to happen, if only because of the distracting sideshow of having one's predecessor in the job hanging around. The only remotely similar case I can think of is that of William Taft who eight years after serving as America's 27th President was appointed Chief Justice, and thus head of the judicial branch.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/12327', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/4857/']}
jdg_377698
stackexchange
llm_judgeable_groundtruth_similarity
16454
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: When running traceroutes some hops return * which as far as I know means that the host is not responding to ICMP echo request, and some other hops (mainly the last) return !H which according to the man pages it means that the host is unreachable . What does unreachable means? That there's no known route to that address? Now provide the response and nothing else.
The answer by YLearn is correct but it is important to know more details. * means that your machine received no response. !H means that your machine received ICMP message "destination host unreachable" from the host indicated in the traceroute output. Rarely traceroute can indicate also other unreachable messages like !N or !P (network or protocol) etc. A machine normally sends "destination host unreachable" when it cannot send the IP packet to the network. This could happen when: There is no route to the destination. The next hop IP address or the final IP address cannot be resolved to an L2 address (there is no ARP reply for the IP address). As YLearn wrote, routers can be configured to not to send the ICMP message but you can also get * instead of !H when your request was silently dropped by an ACL or firewall policy. In security policies silent drop is a normal practice. The drop caused by a security policy depends on the type of the message sent by traceroute . Traditional Unix traceroute by default sends UDP packets to "unusual" ports like 33434 but it can use other methods too. Windows tracert sends ICMP echo request.
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/16454', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/6431/']}
jdg_377699
stackexchange
llm_judgeable_groundtruth_similarity
51493995
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 dict like below: {'activity_count': [10, 11, 12], 'type': ['all', 'paper', 'fpy']} I want to transform this dict into this form: {'all': {'activity_count': 10}, 'paper': {'activity_count': 11}, 'fpy': {'activity_count': 12}} How can I solve this? So far I tried this solution, dic={"activity_count":[10,11,12],"type":["all","paper","fpy"]}in={}i=0for val in dic['type']: for v in dic['activity_count']: if i== dic['activity_count'].index(v): temp={} temp['activity_count']=v fin[val]=temp i+=1 It works as I expected, but it looks very ineffective way to achieve this task. Is there a way to solve this problem? Now provide the response and nothing else.
Here a try, here zip is used to get values from both lists and to assign each: d = {'activity_count': [10, 11, 12], 'type': ['all', 'paper', 'fpy']}nd = {j:{'activity_count':i} for i, j in zip(d['activity_count'], d['type'])}print(nd)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51493995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4684861/']}
jdg_377700
stackexchange
llm_judgeable_groundtruth_similarity
47297089
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 react I can arbitrarily pass props down like so: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>;} How can I do the same thing in Angular? -- More specifically, I want to write a custom dropdown component and pass props down to a select box. Now provide the response and nothing else.
As opposed to React components, Angular components aren't recompiled on input changes and use @Input property decorators to enable change detection. All properties that are expected to be passed should be explicitly defined as component inputs. There are no better options than this one for custom select component. It's possible to read static attributes from current component element and set them on nested component element, but this won't set up bindings. As for React recipe for deep props in wrapped components: const Baz = props => <p>{props.baz}</p>;const Bar = props => <Baz {...props} />;const Foo = props => <Bar {...props} />; This is usually handled by Angular DI and a hierarchy of injectors. A provider can be defined on respective injector in order to make data and behaviour available to nested components.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47297089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5776910/']}
jdg_377701
stackexchange
llm_judgeable_groundtruth_similarity
11628789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Need a little help with knockoutjs and binding a keypress event. I'm trying to hook up knockout so that I pick up on the enter keypress from within a text box. So I can perform the same action as clicking a button. Its a little tricky to explain but hopefully this JsFiddle will demonstrate what I'm trying to achieve. http://jsfiddle.net/nbnML/8/ The problem I have is that observable value is not getting updated and I think its something to do with an observable not being updated until focus moves away from the textbox? Any solutions to this problem. Thanks! Now provide the response and nothing else.
One option is to use the valueUpdate additional binding to force an update on each keypress. For example, you would do: <input type="text" data-bind="value: InputValue, valueUpdate: 'afterkeydown', event: { keypress: RunSomethingKey }" /> If that is not what you are after, then really you would want to fire the element's change event in your handler. For example with jQuery, you would do something like: $(event.target).change(); . It would be better though to move this into a custom binding. Maybe something like (probably should check if the result of valueAccessor() is a function): ko.bindingHandlers.enterKey = { init: function(element, valueAccessor, allBindings, vm) { ko.utils.registerEventHandler(element, "keyup", function(event) { if (event.keyCode === 13) { ko.utils.triggerEvent(element, "change"); valueAccessor().call(vm, vm); //set "this" to the data and also pass it as first arg, in case function has "this" bound } return true; }); } }; Here is your sample updated: http://jsfiddle.net/rniemeyer/nbnML/9/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11628789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192313/']}
jdg_377702
stackexchange
llm_judgeable_groundtruth_similarity
139977
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: How can we efficiently compute the partial trace of a matrix with Mathematica? There is some Mathematica code around to compute this, but most of it seems outdates and not very well written.See for example this code on the Wolfram Library Archive.Only one question seems to have been asked here about this problem, but it was about a very special case. Here is my solution to the problem: makeIterators[iterators_, lengths_, indices_] := Join @@ Table[ Table[ {iter[k], lengths[[k]]}, {k, indices} ], {iter, iterators} ];indicesToIndex[indices_List, lengths_List] := 1 + Total@MapIndexed[ #1 Times @@ lengths[[First@#2 + 1 ;;]] &, indices - 1 ];ClearAll[partialTrace];partialTrace[matrix_, lengths_, indicesToKeep_] := Module[{i, j}, With[{indicesToTrace = Complement[Range@Length@lengths, indicesToKeep]}, With[{ iteratorsInFinalMatrix = Sequence @@ makeIterators[{i, j}, lengths, indicesToKeep], iteratorsToTrace = Sequence @@ makeIterators[{i}, lengths, indicesToTrace] }, Do[ Plus @@ Flatten @ Table[ matrix[[ indicesToIndex[i /@ Range@Length@lengths, lengths], indicesToIndex[ j /@ Range@Length@lengths /. j[n_] :> i[n], lengths] ]], iteratorsToTrace ] // Sow, iteratorsInFinalMatrix ] // Reap // Last // First // Partition[#, Times @@ lengths[[indicesToKeep]]] & ] ] ] This solution basically replicates the steps one would naturally do when computing the partial trace by hand, but I don't like it very much (in particular having to programmatically create the iterators for the Table and Do ). To name a few problems, it cannot be compiled nor parallelized. Here is an example of its operation: testMatrix = KroneckerProduct[Array[a, {2, 2}], Array[b, {2, 2}], Array[c, {2, 2}]];partialTrace[testMatrix, {2, 2, 2}, {1, 3}] // TraditionalForm which gives While an algorithm working for symbolic inputs is nice, I'm mostly interested in a function working efficiently for (potentially big) numerical matrices. To be clear: the problem is that of finding an algorithm to compute the partial trace of a matrix .That is, the inputs will be one matrix, the set of dimensions of the bases, and the dimensions to keep (or those to trace away, equivalently).A solution working on the nested structure given by TensorProduct is a valid answer only as long as one also provides a mean to convert back and forth between the regular matrix representation and the TensorProduct representation. Now provide the response and nothing else.
Looks like you can just use TensorContract / TensorProduct : TensorContract[ TensorProduct[Array[a,{2,2}],Array[b,{2,2}],Array[c,{2,2}]], {3,4}] //ArrayFlatten //TeXForm $\tiny \begin{pmatrix} a(1,1) b(1,1) c(1,1)+a(1,1) b(2,2) c(1,1) & a(1,1) b(1,1) c(1,2)+a(1,1) b(2,2) c(1,2) & a(1,2) b(1,1) c(1,1)+a(1,2) b(2,2) c(1,1) & a(1,2) b(1,1) c(1,2)+a(1,2) b(2,2) c(1,2) \\ a(1,1) b(1,1) c(2,1)+a(1,1) b(2,2) c(2,1) & a(1,1) b(1,1) c(2,2)+a(1,1) b(2,2) c(2,2) & a(1,2) b(1,1) c(2,1)+a(1,2) b(2,2) c(2,1) & a(1,2) b(1,1) c(2,2)+a(1,2) b(2,2) c(2,2) \\ a(2,1) b(1,1) c(1,1)+a(2,1) b(2,2) c(1,1) & a(2,1) b(1,1) c(1,2)+a(2,1) b(2,2) c(1,2) & a(2,2) b(1,1) c(1,1)+a(2,2) b(2,2) c(1,1) & a(2,2) b(1,1) c(1,2)+a(2,2) b(2,2) c(1,2) \\ a(2,1) b(1,1) c(2,1)+a(2,1) b(2,2) c(2,1) & a(2,1) b(1,1) c(2,2)+a(2,1) b(2,2) c(2,2) & a(2,2) b(1,1) c(2,1)+a(2,2) b(2,2) c(2,1) & a(2,2) b(1,1) c(2,2)+a(2,2) b(2,2) c(2,2) \\\end{pmatrix}$ You can look at Ways to compute inner products of tensors and in particular this answer for an efficient version of this approach. The OP wanted a method to convert a KroneckerProduct representation to a TensorProduct representation so that TensorContract could be used. For this particular example, you could use Nest and Partition to do this. Here I use this method on a random 1000 x 1000 matrix: TensorContract[ Nest[Partition[#, {10, 10}]&, RandomReal[1, {1000, 1000}], 2], {3,4}] Another possibility is to use ArrayReshape , although a little massaging is necessary for this approach: r1 = Transpose[ ArrayReshape[data, {10,10,10,10,10,10}], {1,3,5,2,4,6}]; //AbsoluteTimingr2 = Nest[Partition[#, {10,10}]&, data, 2]; //AbsoluteTimingr1===r2 {0.005594, Null} {0.0286, Null} True To convert back you would use ArrayFlatten or Flatten . To wrap it all up into a function: partialTrace[matrix_, lengths_, indicesToKeep_] := With[{ indicesToTrace = Complement[Range@Length@lengths, indicesToKeep] }, With[{ matrixInTPForm = Transpose[ ArrayReshape[matrix, Join[lengths, lengths]], Join @@ Transpose@Partition[Range[2 Length@lengths], 2] ] }, Flatten[ TensorContract[matrixInTPForm, {2 # - 1, 2 #} & /@ indicesToTrace ], Transpose@ Partition[Range[2 Length@lengths - 2 Length@indicesToTrace], 2] ] ] ]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/139977', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/27539/']}
jdg_377703
stackexchange
llm_judgeable_groundtruth_similarity
1783554
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's the best way of concatenating binary files using Powershell?I'd prefer a one-liner that simple to remember and fast to execute. The best I've come up with is: gc -Encoding Byte -Path ".\File1.bin",".\File2.bin" | sc -Encoding Byte new.bin This seems to work ok, but is terribly slow with large files. Now provide the response and nothing else.
The approach you're taking is the way I would do it in PowerShell. However you should use the -ReadCount parameter to improve perf. You can also take advantage of positional parameters to shorten this even further: gc File1.bin,File2.bin -Encoding Byte -Read 512 | sc new.bin -Encoding Byte Editor's note : In the cross-platform PowerShell (Core) edition (version 6 and up), -AsByteStream must now be used instead of -Encoding Byte ; also, the sc alias for the Set-Content cmdlet has been removed. Regarding the use of the -ReadCount parameter, I did a blog post on this a while ago that folks might find useful - Optimizing Performance of Get Content for Large Files .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1783554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70836/']}
jdg_377704
stackexchange
llm_judgeable_groundtruth_similarity
1366105
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 entity object Country with country name and country code. It is a subclass of NSManagedObject and I am using it with core data model to store its value to a persistent store. I have a place where the same Country object will used as a normal object i.e. I will use it to store some temporary country name. For that I have initialized the Country as following [NSManagedObject alloc] init] Initialization successfully done, but I am not able to set any property to that object.Hence I did an exploration. In that I found that, init for the NSManagedObject is not supported as per the documentation. I don't know how to use the NSManagedObject Country with CoreData as well as a normal Object. Now provide the response and nothing else.
2nd paragraph of the NSManagedObject class documentation's overview: A managed object is associated with an entity description (an instance of NSEntityDescription) that provides metadata about the object (including the name of the entity that the object represents and the names of its attributes and relationships) and with a managed object context that tracks changes to the object graph. It is important that a managed object is properly configured for use with Core Data. If you instantiate a managed object directly, you must call the designated initializer (initWithEntity:insertIntoManagedObjectContext:). From the documentation of the method: Important : This method is the designated initializer for NSManagedObject. You should not initialize a managed object simply by sending it init. The documentation is actually very good. You do not want to try to use an NSManagedObject outside of a viable CoreData stack. NSManagedObjects are quite explicitly designed to work within a correctly configured Core Data environment. If you need a temporary instance, you can either create an in-memory store or create one in your regular store and just don't save the changes without deleting it first.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1366105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150371/']}
jdg_377705
stackexchange
llm_judgeable_groundtruth_similarity
16146219
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 assignment I have to create a Gas Meter System for a Gas company to allow employees to create new customer accounts and amend data such as name and unit costs along with taking (depositing) money from their account. I have created my constructor and even added in a method of overloading although I'm currently running into a problem when initiating one of my methods I named deposit() , this is supposed to take money from the users account while other methods such as recordUnits() allows the employee to import a gas meter reading of how many units the customer has used and updates the balance of that customers account which is essentially what the customer owes the company. When testing the program with just preset information when trying to initiate the deposit method I get this Account.deposit(Double.MAX_VALUE); I am not too sure what this means and cannot seem to find anyway of getting past it! test data and code seen below: public class TestGasAccount { public static void main (String [] args) { GasAccount Account = new GasAccount (223,"Havana","TQ",1000); Account.getAccNo(); Account.getName(); Account.getAddress(); Account.getUnits(); Account.getBalance(); Account.recordUnits(1000); Account.getUnits(); Account.getBalance(); Account.deposit(Double.MAX_VALUE); }}public class GasAccount { private int intAccNo; private String strName; private String strAddress; private double dblBalance; private double dblUnits; protected double dblUnitCost = 0.02; public GasAccount(int intNewAccNo,String strNewName,String strNewAddress,double dblNewUnits) { intAccNo = intNewAccNo; strName = strNewName; strAddress = strNewAddress; dblUnits = dblNewUnits; dblBalance = dblNewUnits * dblUnitCost; } public GasAccount (int intNewAccNo, String strNewName, String strNewAddress) { intAccNo = intNewAccNo; strName = strNewName; strAddress = strNewAddress; } public double deposit (Double dblDepositAmount) { dblBalance = dblBalance - dblDepositAmount; return dblBalance; } public String recordUnits (double dblUnitsUsed) { double dblTempBalance; dblTempBalance = dblUnitsUsed * dblUnitCost; dblBalance = dblBalance + dblTempBalance; dblUnits = dblUnits + dblUnitsUsed; return "Transaction Successful"; } public int getAccNo () { System.out.println(intAccNo); return intAccNo; } public String getName() { System.out.println(strName); return strName; } public String getAddress() { System.out.println(strAddress); return strName; } public double getBalance() { System.out.println("£"+dblBalance); return dblBalance; } public double getUnitCost() { return dblUnitCost; } public double getUnits () { System.out.println(dblUnits); return dblUnits; } public void updateUnitCost (double dblNewUnitCost) { dblUnitCost = dblNewUnitCost; }} Now provide the response and nothing else.
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308). This should end in some calculation problems, if you try to subtract the maximum possible value of a data type. Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16146219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2307118/']}
jdg_377706
stackexchange
llm_judgeable_groundtruth_similarity
1396036
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 understand the following statement There are only finitely many quadratic unramified extension of a number field $K$ I know by Kummer theory that such extensions are of the form $K(\sqrt{a})$ for some $a \in K$ such that $a$ generates $K^*/(K^*)^2$. But I can't figure out how to use this to show the claim. Now provide the response and nothing else.
One can prove this directly: Firstly, as noted by the OP, Kummer theory says that a quad. ext. is of the form $K(\sqrt{a})$ for $a \in K^{\times}/(K^{\times})^2.$ However, the condition for this extension to be unram. is mis-stated. If $\mathfrak p$ is a prime of odd residue characteristic, then $K(\sqrt{a})$ is unramified at $\mathfrak p$ if and only if $v_{\mathfrak p}(a)$ is even. If $\mathfrak p$ has even residue characteristic, then the condition that $v_{\mathfrak p}(a)$ be even is necessary, but not sufficient, for $K(\sqrt{a})$ to be unramified at $a$. One way to exploit this information is as follows: There is a natural map $$K^{\times}/(K^{\times})^2 \to \oplus_{\mathfrak p} \mathbb Z/2\mathbb Z$$ (the sum begin taken over all primes)given by $a \mapsto (v_{\mathfrak p}(a) \bmod 2)$, and the $a$ we are interested in lie in the kernel of this morphism. Thus, if we can show this kernel is finite, we'll be done. To analyze this kernel, let's begin with a basic exact sequence: $$ 1 \to \mathcal O_K^{\times} \to K^{\times} \to \oplus_{\mathfrak p} \mathbb Z \to \mathrm{Cl}_K \to 0.$$ Note that $\oplus_{\mathfrak p} \mathbb Z$ is just another way of describing the group of fractional ideals, and so the maps here are the obvious ones: the inclusion of $\mathcal O_K^{\times}$ into $K^{\times}$, the map sending an element of $K^{\times}$ to the corresponding fractional ideal, and the map sending a fractional ideal to the corresponding ideal class. First, if $\mathrm{Cl}_K$ were trivial, we would see (by tensoring this exact sequence with $\mathbb Z/2\mathbb Z$) that$\mathcal O_K^{\times}/(\mathcal O_K^{\times})^2$ surjects onto the kernel we're interested in. But this quotient is finite (as $\mathcal O_K^{\times}$ is f.g.), and hence so is the kernel we're interested in. In general, $\mathrm{Cl}_K$ is finite, and so a little bit of homological argumentation shows that the cokernel of the induced map from$\mathcal O_K^{\times}/(\mathcal O_K^{\times})^2$ to the kernel of interest is finite. This again implies that the kernel of interest is finite. This argument illustrates in a special case the Kummer theory arguments that appear in the proofs of class field theory.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1396036', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/253407/']}
jdg_377707
stackexchange
llm_judgeable_groundtruth_similarity
1374282
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 script some inserts from a source database to a target database, using linked servers. For the first time we are using a second named instance of SQL, and it is giving me an "Internal SQL Server Error" when I run the following code. If I remove the brackets around the named instance, I no longer get the Internal SQL Server Error, but I do get a "Incorrect syntax near '\'." error. Any help is much appreciated. declare @listname as varchar(80) declare @sourcedb as sysnamedeclare @targetdb as sysnameset @listname = 'List(r) Stuff - Planning'set @sourcedb = '[server1.domain.com\server1sql2005].database.dbo.'set @targetdb = 'server2.database.dbo.'print @listnameexec ('if not exists (select * from ' + @targetdb + 'listmatchingheader where listname = ''' + @listname + ''') begin insert ' + @targetdb + 'listmatchingheader (listname, userdefinedname1, userdefinedname2, userdefinedname3, siterecnum, dolplistnum, listdate, regdate, customlist, footer) select mlmh.listname, mlmh.userdefinedname1, mlmh.userdefinedname2, mlmh.userdefinedname3, mlmh.siterecnum, mlmh.dolplistnum, mlmh.listdate, mlmh.regdate, mlmh.customlist, mlmh.footer from ' + @sourcedb + 'listmatchingheader mlmh where mlmh.listname = ''' + @listname + ''' end else begin update ' + @targetdb + 'listmatchingheader set listname = mlmh.listname, userdefinedname1 = mlmh.userdefinedname1, userdefinedname2 = mlmh.userdefinedname2, userdefinedname3 = mlmh.userdefinedname3, siterecnum = mlmh.siterecnum, dolplistnum = mlmh.dolplistnum, listdate = mlmh.listdate, regdate = mlmh.regdate, customlist = mlmh.customlist, footer = mlmh.footer from ' + @targetdb + 'listmatchingheader lmh inner join ' + @sourcedb + 'listmatchingheader mlmh on lmh.listname = mlmh.listname where mlmh.listname = ''' + @listname + ''' end ')exec (' delete ' + @targetdb + 'listmatching from ' + @targetdb + 'listmatching lm inner join ' + @targetdb + 'listmatchingheader lmh on lm.listrecnum = lmh.listrecnum where lmh.listname = ''' + @listname + ''' ')exec (' delete ' + @targetdb + 'listitemcass from ' + @targetdb + 'listitemcass lic where not exists (select * from ' + @targetdb + 'listmatching where listitemrecnum = lic.listitemrecnum) ')exec (' delete ' + @targetdb + 'listitemingreds from ' + @targetdb + 'listitemingreds lii where not exists (select * from ' + @targetdb + 'listmatching where listitemrecnum = lii.listitemrecnum) ')exec (' insert ' + @targetdb + 'listmatching (listrecnum, cas, ingredient, userdefineddata1, userdefineddata2, userdefineddata3) select lmh.listrecnum, mlm.cas, mlm.ingredient, mlm.userdefineddata1, mlm.userdefineddata2, mlm.userdefineddata3 from ' + @sourcedb + 'listmatching mlm inner join ' + @sourcedb + 'listmatchingheader mlmh on mlm.listrecnum = mlmh.listrecnum and mlmh.listname = ''' + @listname + ''' inner join ' + @targetdb + 'listmatchingheader lmh on mlmh.listname = lmh.listname ')exec (' insert ' + @targetdb + 'listitemcass (listitemrecnum, cas, abstrue) select lm.listitemrecnum, mlic.cas, mlic.abstrue from ' + @sourcedb + 'listitemcass mlic inner join ' + @sourcedb + 'listmatching mlm on mlic.listitemrecnum = mlm.listitemrecnum inner join ' + @sourcedb + 'listmatchingheader mlmh on mlm.listrecnum = mlmh.listrecnum and mlmh.listname = ''' + @listname + ''' inner join ' + @targetdb + 'listmatchingheader lmh on mlmh.listname = lmh.listname inner join ' + @targetdb + 'listmatching lm on lmh.listrecnum = lm.listrecnum and mlm.cas = lm.cas and mlm.ingredient = lm.ingredient and mlm.userdefineddata1 = lm.userdefineddata1 and mlm.userdefineddata2 = lm.userdefineddata2 and mlm.userdefineddata3 = lm.userdefineddata3 ')exec (' insert ' + @targetdb + 'listitemingreds (listitemrecnum, ingredienttext, abstrue) select lm.listitemrecnum, mlii.ingredienttext, mlii.abstrue from ' + @sourcedb + 'listitemingreds mlii inner join ' + @sourcedb + 'listmatching mlm on mlii.listitemrecnum = mlm.listitemrecnum inner join ' + @sourcedb + 'listmatchingheader mlmh on mlm.listrecnum = mlmh.listrecnum and mlmh.listname = ''' + @listname + ''' inner join ' + @targetdb + 'listmatchingheader lmh on mlmh.listname = lmh.listname inner join ' + @targetdb + 'listmatching lm on lmh.listrecnum = lm.listrecnum and mlm.cas = lm.cas and mlm.ingredient = lm.ingredient and mlm.userdefineddata1 = lm.userdefineddata1 and mlm.userdefineddata2 = lm.userdefineddata2 and mlm.userdefineddata3 = lm.userdefineddata3') Now provide the response and nothing else.
I tend to use properties if the following are true: The property will return a single, logic value Little or no logic is involved (typically just return a value, or do a small check/return value) I tend to use methods if the following are true: There is going to be significant work involved in returning the value - ie: it'll get fetched from a DB, or something that may take "time" There is quite a bit of logic involved, either in getting or setting the value In addition, I'd recommend looking at Microsoft's Design Guidelines for Property Usage . They suggest: Use a property when the member is a logical data member. Use a method when: The operation is a conversion, such as Object.ToString. The operation is expensive enough that you want to communicate to the user that they should consider caching the result. Obtaining a property value using the get accessor would have an observable side effect. Calling the member twice in succession produces different results. The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order. The member is static but returns a value that can be changed. The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1374282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377708
stackexchange
llm_judgeable_groundtruth_similarity
2918019
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a succinct but complete example project or tutorial that brings together the pieces of the Microsoft stack for a complete application? WPFMVVMBusiness ObjectsEFDatabase I find plenty for WPF and plenty for EF, but am having trouble fully understanding how the EF generated classes relate to business objects, and how those business objects in turn fit into the MVVM pattern. Now provide the response and nothing else.
@mawg, i wrote an simple program for you to ilustrate how work with ADO and Delphi. this is an console application, but explains the basics. before you execute this code you must download and install the odbc connector from this location . You can improve and adapt this code to your requirements. program ProjectMysqlADO;{$APPTYPE CONSOLE}uses ActiveX, DB, ADODB, SysUtils;const//the connection stringStrConnection='Driver={MySQL ODBC 3.51 Driver};Server=%s;Database=%s;User=%s; Password=%s;Option=3;';varAdoConnection : TADOConnection;procedure SetupConnection(DataBase:String);//Open a connectionbegin Writeln('Connecting to MySQL'); AdoConnection:=TADOConnection.Create(nil); AdoConnection.LoginPrompt:=False;//dont ask for the login parameters AdoConnection.ConnectionString:=Format(StrConnection,['your_server',DataBase,'your_user','your_password']); AdoConnection.Connected:=True; //open the connection Writeln('Connected');end;procedure CloseConnection;//Close an open connectionbegin Writeln('Closing connection to MySQL'); if AdoConnection.Connected then AdoConnection.Close; AdoConnection.Free; Writeln('Connection closed');end;procedure CreateDatabase(Database:string);begin Writeln('Creating Database '+database); AdoConnection.Execute('CREATE DATABASE IF NOT EXISTS '+Database,cmdText); Writeln('Database '+database+' created');end;procedure CreateTables;begin Writeln('Creating Tables'); AdoConnection.Execute( 'CREATE TABLE IF NOT EXISTS customers ('+ 'id INT,'+ 'name VARCHAR(100),'+ 'country VARCHAR(25) )',cmdText); Writeln('Tables Created');end;procedure DeleteData;begin Writeln('Deleting dummy data'); AdoConnection.Execute('DELETE FROM customers'); Writeln('Data deleted');end;procedure InsertData; Procedure InsertReg(id:integer;name,country:string); var ADOCommand : TADOCommand; begin ADOCommand:=TADOCommand.Create(nil); try ADOCommand.Connection:=AdoConnection; ADOCommand.Parameters.Clear; ADOCommand.CommandText:='INSERT INTO customers (id,name,country) VALUES (:id,:name,:country)'; ADOCommand.ParamCheck:=False; ADOCommand.Parameters.ParamByName('id').Value := id; ADOCommand.Parameters.ParamByName('name').Value := name; ADOCommand.Parameters.ParamByName('country').Value := country; ADOCommand.Execute; finally ADOCommand.Free; end; end;begin Writeln('Inserting Data'); InsertReg(1,'Lilian Kelly','UK'); InsertReg(2,'John and Sons','USA'); InsertReg(3,'William Suo','USA'); InsertReg(4,'MARCOTEC','UK'); Writeln('Data Inserted');end;procedure ReadData;var AdoQuery : TADOQuery;begin AdoQuery:=TADOQuery.Create(nil); try AdoQuery.Connection:=AdoConnection; AdoQuery.SQL.Add('SELECT * FROM customers'); AdoQuery.Open; while not AdoQuery.eof do begin Writeln(format('%s %s %s',[AdoQuery.FieldByname('id').AsString,AdoQuery.FieldByname('name').AsString,AdoQuery.FieldByname('country').AsString])); AdoQuery.Next; end; finally AdoQuery.Free; end;end;begin CoInitialize(nil); // call CoInitialize() try Writeln('Init'); try SetupConnection('mysql'); //first will connect to the mysql database , this database always exist CreateDatabase('Mydb'); //now we create the database CloseConnection; //close the original connection SetupConnection('Mydb'); //open the connection pointing to the Mydb database CreateTables; //create a sample table DeleteData; //Delete the dummy data before insert InsertData; //insert a dummy data ReadData; //read the inserted data CloseConnection; //close the connection except on E : Exception do Writeln(E.Classname, ': ', E.Message); end; Readln; finally CoUnInitialize; // free memory end;end.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2918019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/141172/']}
jdg_377709
stackexchange
llm_judgeable_groundtruth_similarity
55420156
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In order to get the array's depth I thought I can use the flat() method like so: function getArrayDepth(ry){ // number of levels: how deep is the array let levels = 1; // previous length let prev_length = 1; // current length let curr_length = ry.length; //if the resulting array is longer than the previous one add a new level while(curr_length > prev_length){ ry = ry.flat(); prev_length = curr_length curr_length = ry.length; levels ++ } return levels;}let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]console.log(testRy);console.log(getArrayDepth(testRy))console.log(testRy); It seams it works BUT if one of the arrays inside has a length of 1 let testRy = [1, 2, [3, 4, [5, 6], 7, [8, [9] ], 10], 11, 12] the function fails since the flattened array is as long as the previous one. Is there a better way to get the depth of an array in javascript? Now provide the response and nothing else.
I think a recursive approach is simpler. If your current item is an Array determine the max depth of its children and add 1. function getArrayDepth(value) { return Array.isArray(value) ? 1 + Math.max(0, ...value.map(getArrayDepth)) : 0;}let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]console.log(testRy);console.log(getArrayDepth(testRy))console.log(testRy); Edit Shoutout to Daniele Fioroni for catching an edge-case my code didn't handle: empty arrays.I've updated my code. But still, leave some upvotes over there as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55420156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7897395/']}
jdg_377710
stackexchange
llm_judgeable_groundtruth_similarity
16492254
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Many people have explained that e.stopPropagation() prevents event bubbling. However, I'm having a hard time finding why one would want or want to prevent event bubbling in the first place. On my site I have many elements which are called like this: $(document.body).on('click', ".clickable", function(e){ //e.stopPropagation(); //do something, for example show a pop-up or click a link });<body> <p>outside stuff</p> <button type="button" class='clickable'> <img src='/icon.jpg'> Do Something </button></body> I was thinking to add e.stopPropagation() because I want to change the event handler to 'touch' from 'click' using this awesome touch library, Hammer.js. . This would allow for clicking to happen normally on desktop and for touch events on mobile devices. The problem with this (please correct me if I'm wrong) is that scrolling on touch devices slows to a halt. Is this where e.stopPropgation() is useful? Such that whenever one touches the screen document.body -event bubbling is NOT happening every time? Now provide the response and nothing else.
There are several ways you can handle events in javascript/jQuery. Two of them are: You can use a direct event handler on the object. You can use delegated event handling where you handle a propagated event on a parent. If you are using a direct event handler on the object and there are no delegated event handlers configured in the page, then there is no reason for e.stopPropagation() . But, if you have delegated event handlers that are using propagation, you sometimes want to make sure that a higher level delegated event handler does not fire on the current event. In your particular example: $(document.body).on('click', "a.ajaxLink", function(e){ This is a delegated event handler. It is looking for any click event that propagates up to the document.body object, yet originated on an a.ajaxLink object. Here, there is little advantage to e.stopPropagation() because the event is almost entirely propagated already (it will also go up to the document , but unless you also have a handler for click on the document object, then there's no reason to e.stopPropagation() in this handler. Where it would make a lot of sense would be when you have both a top level delegated event handler (like the one in your example) and you have lower level event handlers (either directly on the objects or using delegated event handling, but at a level below the document.body object. In that case, if you only want the lower level event handler to get the event, then you would call e.stopPropagation() in it's handler so that the document.body handler never saw the event. $("a.ajaxLink").click(function(e) { if (some condition) { // do something specific to this condition code here // stop propagation so the default behavior for click in document.body does not fire e.stopPropagation(); }}) Note: Using return false from a jQuery event handler triggers both e.stopPropagation() and e.preventDefault() . But, if you are in a delegated event handler, the e.preventDefault() doesn't do anything because the default behavior (if there was one) has already fired when the target object first saw the event. Default behaviors happen before event propagation so e.preventDefault() only works in event handlers directly on the target object. There is no noticeable performance degradation because you allow an event to bubble up because these are user level events and they just don't occur fast enough to matter, not is the bubbling particularly slow when there are no handlers on all the intervening objects. The system already special cases some events like mousemove that can happen rapidly to solve that issue. If you have a giant project with hundreds or thousands of event handlers, there are cases where using delegated event handling is more efficient and there are cases where direct event handlers on the actual target objects are more efficient. But, except in giant scenarios, the performance difference is probably not noticeable. Here's an example where bubbling/delegation is more efficient. You have a giant table with thousands of rows and each row has two buttons in it (add/delete say). With delegated event handling, you can handle all the buttons in two simple event handlers that you attach to the table object (a common parent of the buttons). This will be much quicker to install the event handlers rather than installing several thousand event handlers directly on each and every button. These delegated event handlers will also automatically work on newly created rows/objects in the table. This is the ideal scenario for event bubbling/delegated event handlers. Note, in this scenario, there is no reason to stop propagation/bubbling. Here's an example of where delegated event handlers are very inefficient. Supposed you have a good-sized web page with hundreds of objects and event handlers. You could make every one of the event handlers be a delegated event handler attached to the document object. But, here's what happens. A click happens. There's no event handler on the actual object so it bubbles up. Eventually, it gets to the document object. The document object has hundreds of event handlers. The event processing engine (jQuery in this case) has to look through every one of those event handlers and compare the selector in the delegated event handler for each one with the original event target to see if they match. Some of these comparisons are not fast as they can be full-blown CSS selectors. It has to do that for hundreds of delegated events. This is bad for performance. This is exactly why .live() in jQuery was deprecated because it worked this way. Instead, delegated event handlers should be placed as close to the target object as possible (the closest parent that is practical given the circumstances). And, when there is no need for a delegated event handler, handlers should be put on the actual target object as this is the most efficient at runtime. Back to your original question. There is no time that you want bubbling turned off generally. As I described earlier in my answer, there are specific instances where an event handler further out on the tree wants to handle the event and stop any delegated event handlers higher up in the DOM tree from processing this event. That is a time to e.stopPropatation() . Here are several other relevant posts with useful info on this topic (as it has been widely discussed before): Why not take Javascript event delegation to the extreme? Should all jquery events be bound to $(document)? Does jQuery.on() work for elements that are added after the event handler is created? jQuery on() and stopPropagation() Best practice to avoid memory or performance issues related to binding a large number of DOM objects to a click event jQuery .live() vs .on() method for adding a click event after loading dynamic html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16492254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/702275/']}
jdg_377711
stackexchange
llm_judgeable_groundtruth_similarity
14151655
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between the mercurial commands, hg strip hg backout hg revert All these commands basically are used to revert/undo the effects of an earlier changeset. Now provide the response and nothing else.
hg strip removes the changeset and all its descendants from the repository. It will be as if the changes never existed. Be careful when using this on public changesets as it will not remove it from any other repository and you'll get them back next time you pull. hg backout creates a new changeset to reverse the effect of an earlier changeset. The old changeset will still remain in the repository but so will a new changeset to remove the changes. hg revert with a revision updates the working copy to the specified revision. If you then commit that working copy it will have the effect of reverting all changes since. Other answers with more info on revert and backout: What is the difference between hg revert and hg backout? . Mercurial — revert back to old version and continue from there .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14151655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509134/']}
jdg_377712
stackexchange
llm_judgeable_groundtruth_similarity
4651923
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 noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits. A specific example $(this) vs this Inside a click event referencing the clicked objects id jQuery $(this).attr("id"); Javascript this.id; Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code) EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery , instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $() . In addition to the example I gave in my original question. Now provide the response and nothing else.
this.id (as you know) this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.) this.className to get or set an entire "class" property this.selectedIndex against a <select> to get the selected index this.options against a <select> to get a list of <option> elements this.text against an <option> to get its text content this.rows against a <table> to get a collection of <tr> elements this.cells against a <tr> to get its cells (td & th) this.parentNode to get a direct parent this.checked to get the checked state of a checkbox Thanks @Tim Down this.selected to get the selected state of an option Thanks @Tim Down this.disabled to get the disabled state of an input Thanks @Tim Down this.readOnly to get the readOnly state of an input Thanks @Tim Down this.href against an <a> element to get its href this.hostname against an <a> element to get the domain of its href this.pathname against an <a> element to get the path of its href this.search against an <a> element to get the querystring of its href this.src against an element where it is valid to have a src ...I think you get the idea. There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery. In general you can replace: $(el).attr('someName'); with: Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases. The sentences below sort of covered it. See this answer for a better treatment. el.getAttribute('someName'); ...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too. Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery: $('span').unwrap(); // unwrap all span elements But if there are many, you may want to do a little native DOM API: var spans = document.getElementsByTagName('span');while( spans[0] ) { var parent = spans[0].parentNode; while( spans[0].firstChild ) { parent.insertBefore( spans[0].firstChild, spans[0]); } parent.removeChild( spans[0] );} This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library. It may seem like I have an infinite loop with the outer while because of while(spans[0]) , but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]); . This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4651923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555384/']}
jdg_377713
stackexchange
llm_judgeable_groundtruth_similarity
446847
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a script running on Linux that accepts some parameters. I would like to do something like: if [[ $CONDITION == "true" ]]; then script param1 --param2 else script param1 fi I would like to avoid the forking path of the if. Is there a more optimal way to pass the second parameter? Now provide the response and nothing else.
The most expansible and robust way would probably be to use an array to hold the optional parameter(s): params=()if [[ $CONDITION == true ]]; then params+=(--param2)fiscript param1 "${params[@]}" Or in shorthand: [[ $CONDITION == true ]] && params+=(--param2)script param1 "${params[@]}" That avoids repeating the constant part of the command and you can put more than one argument in the array, even the whole command. Note that it's important to do this with an array: if you replace the array with a regular variable ( params="--param2"; script param1 $params ) you'll either have to expand the variable unquoted, with all the problems that brings, or expand it quoted, in which case you'll pass an empty string as argument if the variable is empty. In a simple case like this, the "alternate value" expansion can also be used: cond=xp2="--param2"script param1 ${cond:+"$p2"} Here, if cond is nonempty (regardless of if it's cond=false or cond=0 instead of cond=true ), the value of p2 is expanded. This may be seen as less ugly than arrays, but be careful with the placement of the quotes. See also: How can we run a command stored in a variable? Using shell variables for command options Why does my shell script choke on whitespace or other special characters?
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/446847', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/264385/']}
jdg_377714
stackexchange
llm_judgeable_groundtruth_similarity
5978005
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to develop a cross platform application. Is Java cross platform? I mean, can I develop a Java application in Windows and use it in Mac OS X and Linux? If yes, how? I find application written in Java, has two setup file one for Windows and other for Mac. This confuses me. Any illustration or suggestion will be highly appreciated. Now provide the response and nothing else.
Is Java a cross platform? Java is cross platform in the sense that a compiled Java program runs on all platforms for which there exists a JVM. (This holds for all major operating systems, including Windows, Mac OS and Linux.) I mean I can develop Java application in windows and use it in mac and Linux? Yes, this is possible. This (and the security aspect) is one of the main advantages of running the programs in a virtual machine. If yes how? Write your application in Java (In .java files) Compile your application using Eclipse or javac (into .class files) (Optionally) Bundle your .class files in an executable ( .jar file) The very same .jar file can be distributed and executed on Windows systems, Mac systems, etc. I find application written in Java, has two setup file one for windows and other for mac. This confuses me. This is because some applications rely on platform-specific features. They are then bundled with different platform-specific libraries. Unless you're developing an application that itself relies on platform-specific features, (such as for instance low-level system calls), you should be able to do just fine with ordinary Java. Important comment by @Peter Lawrey : It can be while the application is platform independent, the setup program is not. e.g. IntelliJ has three platform specific installers which are not written in Java, but have a zip which you can just unzip on any platform and it will work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5978005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712104/']}
jdg_377715
stackexchange
llm_judgeable_groundtruth_similarity
7326338
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 be able to selectively block incoming calls in an iOS application I'm writing. This is intended for personal use, not the App Store, so I'm fine with using private APIs to accomplish this. I have recently come across the Core Telephony framework. Is there a way to use this framework to block calls? If not, what private APIs could I use to do this? Now provide the response and nothing else.
Are you sure it does not?code examples on http://tech.ruimaninfo.com/?p=83 shows how to do such things.Core Telephony headers in SDK are not complete.Of course this means no app storethis is my code fragment based on example I linked if ([str1 isEqualToString:@"kCTCallIdentificationChangeNotification"]){ NSDictionary *info = (__bridge NSDictionary *)userInfo; CTCall2 *call = (__bridge CTCall *)[info objectForKey:@"kCTCall"]; NSString *caller = CTCallCopyAddress(NULL, call); NSLog(@"Caller %@",caller); if ([caller isEqualToString:@"+1555665753"]) { //disconnect this call CTCallDisconnect(call);} additional definitions needed: typedef struct __CTCall CTCall;extern NSString *CTCallCopyAddress(void*, CTCall *);extern void CTCallDisconnect(CTCall*); and you need to monitor telephony center's callback(see linked example)I tested this fragment on my iOS5 device
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7326338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/394736/']}
jdg_377716
stackexchange
llm_judgeable_groundtruth_similarity
7476092
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having this exception with some stubs generateds by Axis2: "The type org.apache.axiom.om.OMElement cannot be resolved. It is indirectly referenced from required .class files" I've been reading many posts, and trying to find a solution. What I've found so far is to add the apache tomcat 5.5 library to the build path. It removed the error in the java file, but then, when I to execute any java program inside the project, I got this error: 'Launching myApp' has encountered a problem Exception occurred executing command line. Cannot run program "C:\Program Files\Java\jdk1.5.0_22\bin\javaw.exe" (in directory "D:\Digicel\workspace\Digicel\myClassSample"): CreateProcess error=87, The parameter is incorrect then if I remove the apache tomcat library from the build path, I can run the other java programs, but not the one mentioned initially. Any thoughts about it? Now provide the response and nothing else.
Okay, I've found the cause of the problem with the help of a friend :) The thing is that Eclipse is aware that one of my dependencies, depends of another library, and Eclipse is checking for it when it tries to build the code. So, what I've done is try to check which jar file contains this library: " org.apache.axiom.om.OMElement". I've googled it and found that it is "axiom-api-1.2.10.jar" and finally my file compiled with 0 errors. He also explained to me that my original solution of adding the apache tomcat server library is adding all the jars that cames with apache tomcat (which is a big list), and probably there may have been a version conflict with my current list of added jars. So, the fix was to find the appropriate jar and add it to the project.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7476092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/897383/']}
jdg_377717
stackexchange
llm_judgeable_groundtruth_similarity
20380792
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 just started Android programming so downloaded Eclipse and got started. Created my first project following tutorial from here: http://developer.android.com/training/basics/firstapp/creating-project.html#CommandLine And when I was on next lesson to run that application from here: http://developer.android.com/training/basics/firstapp/running-app.html I did as they said. Connected my device via USB, enabled USB debugging too, but when I clicked Run on eclipse, got the above error. What have I done wrong? Now provide the response and nothing else.
Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either. Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time. Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse. To view the progress of your project being installed and started on your device, check the console.It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20380792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3065560/']}
jdg_377718
stackexchange
llm_judgeable_groundtruth_similarity
2222844
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 $r_n$ denote the inradius of a regular $n$-simplex $\triangle^n$ in $\mathbb{R}^n$, and $a$ denote the uniform edge length. It is well-known that $r_1 = a \frac{1}{2} \\ r_2 = a \frac{1}{6} \sqrt{3} \\ r_3 = a \frac{1}{12} \sqrt{6}$ But how to generalize $r_n$ to arbitrary dimensions? Now provide the response and nothing else.
As we see in Height of $n$-simplex , the altitude (height) of a regular $n$-simplexof edge length $a$ is $$h_n = a\sqrt{\frac{n+1}{2n}}.$$ The inradius $r_n$ is the distance from the centroid of the regular $n$-simplex to the center of a hyperface, so$r_n = \frac 1{n+1} h_n.$Therefore $$r_n = \frac a{n+1} \sqrt{\frac{n+1}{2n}}= \frac{a}{\sqrt{2n(n+1)}}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2222844', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/207654/']}
jdg_377719
stackexchange
llm_judgeable_groundtruth_similarity
10150899
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I run my application, everytime I am getting the below exception in my logcat: 04-14 09:29:53.965: W/dalvikvm(1020): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 04-14 09:29:53.985: E/AndroidRuntime(1020): FATAL EXCEPTION: main 04-14 09:29:53.985: E/AndroidRuntime(1020): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.LoadedApk.makeApplication(LoadedApk.java:482) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3938) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.ActivityThread.access$1300(ActivityThread.java:123) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1185) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.os.Handler.dispatchMessage(Handler.java:99) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.os.Looper.loop(Looper.java:137) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.ActivityThread.main(ActivityThread.java:4424) 04-14 09:29:53.985: E/AndroidRuntime(1020): at java.lang.reflect.Method.invokeNative(Native Method) 04-14 09:29:53.985: E/AndroidRuntime(1020): at java.lang.reflect.Method.invoke(Method.java:511) 04-14 09:29:53.985: E/AndroidRuntime(1020): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 04-14 09:29:53.985: E/AndroidRuntime(1020): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-14 09:29:53.985: E/AndroidRuntime(1020): at dalvik.system.NativeStart.main(Native Method) 04-14 09:29:53.985: E/AndroidRuntime(1020): Caused by: java.lang.NullPointerException 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.LoadedApk.getClassLoader(LoadedApk.java:305) 04-14 09:29:53.985: E/AndroidRuntime(1020): at android.app.LoadedApk.makeApplication(LoadedApk.java:474) 04-14 09:29:53.985: E/AndroidRuntime(1020): ... 11 more Note: When I uninstall the app from the emulator and run it, then I don't get this exception but when I re-run the installed application in emulator, I am getting this. Please help. Now provide the response and nothing else.
This is a verbose error message raised by underlying framework when dalvik re-install .apk file and trying to reuse or recycle the previous opened activity/view from the same package (if you haven't closed the previous installed app yet). It has nothing to do with your app, moreover, it is very unlikely that your app will get freezed or crashed cause by this verbose error message on end user's device. It seems that this dalvik verbose error log only happend on Android 4.0 system, I've tested it myself on Android 3.2 and 2.3.3 running environment, where you cannot replicate to get this message shown on neither of them. A similar question has been discussed before at here and someone has filled a bug report in Android Issues Tracker . I don't think you should concern too much about this verbose error log at the moment, if you look more logs before and after this red error in Logcat, you can see the full story and find that the previous opened activity/view (which are marked as died state) get killed and the newly re-installed one get poped ultimately.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/10150899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1317840/']}
jdg_377720
stackexchange
llm_judgeable_groundtruth_similarity
34375413
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 while -loop that should repeat the program until a certain condition is met. Inside this loop I call an async function, which prints out a message for me. Here is the (cut-short) code: private void InitializeMessageSystem ( ) { do { // Do stuff await printMessage ("Hello World!"); Console.ReadKey(); } while (condition != true)} And here the function PrintMessage() : private static async Task PrintMessage (string message, int spd = 1){ int delay = 50 / spd; string[] words = message.Split(' '); int index = 1; for (int word = 0; word < words.Length; word++) { char[] current = words[word].ToCharArray(); if (index + current.Length > Console.WindowWidth) { Console.WriteLine(); index = 1; } for (int c = 0; c < current.Length; c++) { Console.Write(current[c]); await Task.Delay(delay); } Console.Write(" "); }} Edit : Here's the call from the main function: static void Main (string[] args) { InitializeMessageSystem(); Console.ReadKey();} Question Why does my program exit, when I press a key while the function is not yet completed? I thought the program would wait for the Console.ReadKey() until the function PrintMessage() is completed? Now provide the response and nothing else.
Your problem is that await returns the control flow of the program to the caller of the function. Normally execution is continued at that point when the asynchronous task you await finishes. So control is returned to your main function as you wait for printMessage and main now waits for a key input. As you hit the key main returns to the OS and your process (including all asynchronous tasks) terminates. Change your InitializeMessageSystem to private async Task InitializeMessageSystem ( ) and change the code in main to InitializeMessageSystem().Wait(); to wait until InitializeMessageSystem finishes completely before waiting for the key.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34375413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5507624/']}
jdg_377721
stackexchange
llm_judgeable_groundtruth_similarity
23800477
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 a bit discouraged with parsing dates in Java 8 Time API . Previously I could easily write: String date = "04.2013";DateFormat df = new SimpleDateFormat("MM.yyyy");Date d = df.parse(date); But now if I use LocalDate and do it like this: String date = "04.2013";DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");LocalDate ld = LocalDate.parse(date, formatter); I receive an exception: java.time.format.DateTimeParseException: Text '04' could not be parsed at index 0java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1948)java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)java.time.LocalDate.parse(LocalDate.java:400)java.time.LocalDate.parse(LocalDate.java:385)com.luxoft.ath.controllers.JsonController.region(JsonController.java:38)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:483)org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)javax.servlet.http.HttpServlet.service(HttpServlet.java:617)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)javax.servlet.http.HttpServlet.service(HttpServlet.java:723)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) If I change string format to "yyyy-MM-dd" everything work perfectly, even without formatter: String date = "2013-04-12";LocalDate ld = LocalDate.parse(date); So my question is: how to parse date in custom format using Java 8 Time API? Now provide the response and nothing else.
It makes sense: your input is not really a date because it does not have a day information. You should parse it as a YearMonth and use that result if you don't care about the day. String date = "04.2013";DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");YearMonth ym = YearMonth.parse(date, formatter); If you do need to apply a specific day, you can obtain a LocalDate from a YearMonth for example: LocalDate ld = ym.atDay(1);//orLocalDate ld = ym.atEndOfMonth(); You can also use a TemporalAdjuster , for example, for the last day of the month*: LocalDate ld = ym.atDay(1).with(lastDayOfMonth()); *with an import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23800477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1430055/']}
jdg_377722
stackexchange
llm_judgeable_groundtruth_similarity
17491376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following question is sort-of continuation of this one: iOS: Multi-line UILabel in Auto Layout The main idea is that every view is supposed to state it's "preferred" (intrinsic) size so that AutoLayout can know how to display it properly. UILabel is just an example of a situation where a view cannot by itself know what size it needs for display. It depends on what width is provided. As mwhuss pointed out, setPreferredMaxLayoutWidth did the trick of making the label span across multiple lines. But that is not the main question here. The question is where and when do I get this width value that I send as an argument to setPreferredMaxLayoutWidth . I managed to make something that looks legit, so correct me if I am wrong in any way and tell me please if you know a better way. In the UIView's -(CGSize) intrinsicContentSize I setPreferredMaxLayoutWidth for my UILabels according to self.frame.width. UIViewController's -(void) viewDidLayoutSubviews is the first callback method I know where subviews of the main view are appointed with their exact frames that they inhabit on the screen. From inside that method I, then, operate on my subviews, invalidating their intrinsic sizes so that UILabels are broken into multiple lines based on the width that was appointed to them. Now provide the response and nothing else.
It seems annoying that a UILabel doesn't default to its width for the preferred max layout width, if you've got constraints that are unambiguously defining that width for you. In nearly every single case I've used labels under Autolayout, the preferred max layout width has been the actual width of the label, once the rest of my layout has been performed. So, to make this happen automatically, I have used a UILabel subclass, which overrides setBounds: . Here, call the super implementation, then, if it isn't the case already , set the preferred max layout width to be the bounds size width. The emphasis is important - setting preferred max layout causes another layout pass to be performed, so you can end up with an infinite loop.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17491376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1639049/']}
jdg_377723
stackexchange
llm_judgeable_groundtruth_similarity
15722324
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 Numpy array of shape (6,2): [[ 0, 1], [10,11], [20,21], [30,31], [40,41], [50,51]] I need a sliding window with step size 1 and window size 3 like this: [[ 0, 1,10,11,20,21], [10,11,20,21,30,31], [20,21,30,31,40,41], [30,31,40,41,50,51]] I'm looking for a Numpy solution. If your solution could parametrise the shape of the original array as well as the window size and step size, that'd be great. I found this related answer Using strides for an efficient moving average filter but I don't see how to specify the stepsize there and how to collapse the window from the 3d to a continuous 2d array. Also this Rolling or sliding window iterator? but that's in Python and I'm not sure how efficient that is. Also, it supports elements but does not join them together in the end if each element has multiple features. Now provide the response and nothing else.
In [1]: import numpy as npIn [2]: a = np.array([[00,01], [10,11], [20,21], [30,31], [40,41], [50,51]])In [3]: w = np.hstack((a[:-2],a[1:-1],a[2:]))In [4]: wOut[4]: array([[ 0, 1, 10, 11, 20, 21], [10, 11, 20, 21, 30, 31], [20, 21, 30, 31, 40, 41], [30, 31, 40, 41, 50, 51]]) You could write this in as a function as so: def window_stack(a, stepsize=1, width=3): n = a.shape[0] return np.hstack( a[i:1+n+i-width:stepsize] for i in range(0,width) ) This doesn't really depend on the shape of the original array, as long as a.ndim = 2 . Note that I never use either lengths in the interactive version. The second dimension of the shape is irrelevant; each row can be as long as you want. Thanks to @Jaime's suggestion, you can do it without checking the shape at all: def window_stack(a, stepsize=1, width=3): return np.hstack( a[i:1+i-width or None:stepsize] for i in range(0,width) )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15722324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338825/']}
jdg_377724
stackexchange
llm_judgeable_groundtruth_similarity
442
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: What is the fastest possible square number test in Mathematica , both for machine size and big integers? I presume starting in version 8 the fastest will be a dedicated C LibraryLink function. Now provide the response and nothing else.
Here's an idea similar to Carl Woll's that's a little faster: sQ[n_] := FractionalPart@Sqrt[n + 0``1] == 0;sQa = FractionalPart@Sqrt[# + 0``1] == 0 &; (* @Roman's suggestion *) @Roman reports the pure function is 10% faster. I find on several runs of timeRun[] below, the variation in the timings cause them to overlap, with sQa sometimes timed slower than sQ . The median for sQa is around 5–6% faster. If I change AbsoluteTiming to Timing in timeRun[] , sQ and sQa finish in a dead heat, ±2% of each other. Theoretically, I would expect pure functions to have less overhead, but it would be a small difference compared to the time Sqrt[n + 0``1] will take. Maybe %5 is about right. It's difficult to time computations in a multiprocess environment like my laptop. The upshot is that sQa appears to be a bit faster. Here are some timing runs similar to @fgrieu's: timeRun[f_] := Module[{a, m}, a = (2^1024 - 3^644)^2; m = (2^1024 - 3^644)^2 + 9; First@ AbsoluteTiming@ Do[f[n], {n, m - 200000, m}] ]timeRun2[f_] := First@ AbsoluteTiming[ Do[ f /@ (n^2 + {-2, -1, 0, 1, 2}), {n, 2^1357, 0, -Floor[2^1357/99]}] ]; Tests of a long sequence of consecutive integers about single large square number: timeRun[sQ]timeRun[SqQ]timeRun[sqQ1]timeRun[SquareQ2]timeRun[SquareQ08](* 0.626601 sQ 0.789668 SqQ (@fgrieu) 1.11774 sqQ1 (@CarlWoll) 1.63489 SquareQ2 (@Mr.Wizard) 3.39258 SquareQ08 (@KennyColnago)*) Tests of short sequences of consecutive integers about many small to large square numbers: timeRun2[sQ] timeRun2[SqQ] timeRun2[sqQ1] timeRun2[SquareQ2] timeRun2[SquareQ08] (* 0.002639 sQ 0.003289 SqQ 0.0039 sqQ1 0.005791 SquareQ2 0.01749 SquareQ08*) A test of just smaller numbers: aa = 1; bb = 10^6;AbsoluteTiming@Do[sQ@(n), {n, aa, bb}]AbsoluteTiming@Do[SqQ@(n), {n, aa, bb}]AbsoluteTiming@Do[sqQ1@(n), {n, aa, bb}]AbsoluteTiming@Do[SquareQ2@(n), {n, aa, bb}]AbsoluteTiming@Do[SquareQ08@(n), {n, aa, bb}](* {2.34658, Null} {3.2571, Null} {3.18561, Null} {3.42899, Null} {3.25997, Null}*) If you want to verify its accuracy, you can test it against other solutions like this: aa = 10^20 - 100; bb = aa + 10^3;Table[sQ[n], {n, aa, bb}] === Table[IntegerQ@Sqrt[n], {n, aa, bb}](* True *)aa = 1; bb = 10^6;Table[sQ[n], {n, aa, bb}] === Table[IntegerQ@Sqrt[n], {n, aa, bb}](* True *)
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/442', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/121/']}
jdg_377725
stackexchange
llm_judgeable_groundtruth_similarity
40639999
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just downloaded Visual Studio Professional for Mac and I cannot seem to build anything as I always get the same error: /Library/Frameworks/Mono.framework/Versions/4.8.0/lib/mono/xbuild/14.0/bin/Microsoft.CSharp.targets (CoreCompile target) ->CSC: error CS0041: Unexpected error writing debug information -- 'Operation is not supported on this platform.' 19 Warning(s) 1 Error(s) Not sure what to change on my project to get things to compile. Now provide the response and nothing else.
I was able to work around this problem two ways: HACK By removing debug symbols from the build (in VS windows: Project Properties -> Build Tab -> Advanced button -> change "Debug Info" dropdown to "none" -- not sure what equivalent is in VS for Mac / Xamarin Studio) I did this for all configurations of affected project(s). Pulled back to macOS env, build now succeeds. No debug info of course, but it works without breaking any deps. NON-HACK Root cause is the use of Roslyn compiler/tools for ASP.NET Web projects, and this tool produces PDB files instead of MDB files, and the build fails trying to produce PDB files on macOS platform (er go "platform unsupported".) Knowing the root cause we can also remove the following nuget packages from the affected projects: <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net45" /><package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net45" developmentDependency="true" /> It's unclear what is sacrificed by removing these two packages. This does allow me to build the affected projects with the debug info included. The affected projects only contained webapi endpoints, and no use of MVC nor Razor engine. It would be nice to hear the experiences of others if they had issues upstream from this change. HTH
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40639999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34548/']}
jdg_377726
stackexchange
llm_judgeable_groundtruth_similarity
522709
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 am using a Debian 6 - 64bit OS and my server is ddosed/flooded through udp protocol from time to time. I basically host game-servers and my firewall is set to rate-limit the packets on allowed ports but sometimes the rate per IP is low but the number of IPs are more so my server sends outgoing icmp unreachable replies to the attacking IP which does no benefit but chokes/saturates the port even more. I'm looking on how to disable this feature. Actually the ports that get attacked are allowed through firewall and I can't disable them although it would solve the issue. I run a number of servers over some port ranges so I can't continually keep accepting these ports one by one and decided to allow the total port range I might require. I'm looking at some kernel ability to stop this? Now provide the response and nothing else.
To prevent ICMP unreachable packets being sent, you can drop them using netfilter (iptables): iptables -I OUTPUT -p icmp --icmp-type destination-unreachable -j DROP Better is to prevent them being generated in the first place by using the DROP target on the INPUT traffic, rather than REJECT (or nothing where the kernel networking stack will create the unreachable reply rather than netfilter) I don't think this will resolve your issues though; you need to identify what impact the DDoS is having; is it saturating the network or consuming system resources (CPU/memory etc). If it's network, then muting the replies may assist slightly, but you're still going to have the incoming packets on the wire.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/522709', 'https://serverfault.com', 'https://serverfault.com/users/112380/']}
jdg_377727
stackexchange
llm_judgeable_groundtruth_similarity
1518335
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been working on a Sudoku Solver, my current solver uses the backtracking algorithm but it still takes too long. I'm hoping to get it down to less than a second for most cases. As such, I've decided to rewrite it with the dancing links algorithm, understanding it is one of the better bruteforce methods that works well especially with a constraint problem such as the Sudoku Puzzle. I have tried to read the Wiki and Knuth's paper on it, however both of them are kinda hard to comprehend and extremely verbose. I also read Sudopedia's version on it, and it seems that once it got to the Sudoku's implementation, it got too abstract. Can someone try to explain the Dancing Links algorithm not in terms of its derivation but its implementation? (would be great to use the Sudoku as an example) Thanks! Now provide the response and nothing else.
You might be interested in my implementation in javascript . Firstly you have to understand Exact Cover. An exact cover problem is a problem where you're given a bunch of choices, and a set of constraints and your challenge is to select a bunch of the choices that will fill every constraint exactly once. For example, consider the case of someone creating their ice dance routine. They have a number of tricks that they need to show the judges, and don't want to perform any trick more than once. They have a number of sequences which are groups of tricks that can be put together and they want to choose the ideal selection of sequences to cover all the tricks once. In this example, the constraints are that they must perform every trick. The choices are the possible sequences they could incorporate into their routine. A nice way to represent problems of this sort is to draw out a table where the constraints are columns and the choices are rows, and you have a big X in cells where a particular choice fulfills that constraint. As it turns out, given the right constraints and choices, sudoku can be described as an Exact Cover problem. Ok, assuming you've got that, now you need to understand Algorithm X. Knuth said of it "Algorithm X is simply a statement of the obvious trial-and-error approach. (Indeed, I can’t think of any other reasonable way to do the job, in general.)". So here's my description of algorithm X: If your table has no columns, stop - you've solved it. If you've got a partial solution stored, then it's actually a real solution, return it. Select a column (representing a constraint). Find a row with a cross in that column (representing a choice that fulfills that constraint). Add it to some kind of structure where you're storing potential solutions. If you can't find a row, give up - there are no solutions. Assume that the row you found in 3 is in the solution, so remove all columns that it have an X in that row. While removing all those columns, also remove all rows that have an X in the columns you're removing (because you've already satisfied the constraint, so you're barred from choosing something that would satisfy it again). Now recursively try to solve the reduced table. If you can't, remove the row you tried from the potential solution structure, restore all the rows and columns you removed in steps 3 and 4 and try a different row. If you run out of rows, then give up - there are no solutions. Now that you understand that, you can understand dancing links. Dancing Links is a way of implementing that algorithm efficiently. The key point of dancing links is that in a linked list, when you remove a node (which can be done efficently by modifying the pointers of its neighbours), the node that you've removed has all the information you need to add it back to the linked list (in the case that it turns out you were wrong when you guessed it was part of the solution). That plus the fact that if you make all your linked lists circular then suddenly you lose a lot of special cases is pretty much all dancing-links is.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1518335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118644/']}
jdg_377728
stackexchange
llm_judgeable_groundtruth_similarity
16696763
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 colleagues and I are in the process of choosing a web framework to develop a high traffic web site. We are really good with node.js + express and php + symfony2 . Both are great frameworks but we are a bit concerned about Symfony2 because it seems to be outperformed by most web frameworks out there. Here is the benchmarks that proves it: http://www.techempower.com/benchmarks/ For this reason we will probably use node.js + express but I still wonder why is Symfony2 performing so bad in benchmarks. Now provide the response and nothing else.
In the end it all comes down to correct cache handling ... symfony or PHP in general IS slower than other languages or frameworks thus providing you with the tools to create rich, secure and testable web applications really fast. If you use a reverse proxy like Varnish and ESI ( edge side includes ) and end up serving the parts of your templates you really need to have updated through symfony. you will have a blazingly fast experience. Furthermore if you use an opcode cache like APC and an optimized database a human user won't actually notice the difference of a few ms in a real world application. As per request i will dive a bit deeper and give you a few more things to think about. Caching & Performance With cloud-services (s3,ec2,gae,...) at almost no cost paired with load-balancers, easy provisioning (chef,puppet,...) and all this funky stuff avilable it has become easy and affordable even for small companies to run and manage large data and/or high traffic applications. More storage means more space for cache - more computing power means quicker cache warmimg. things you will often hear if people are talking about php or framework-performance: facebook runs with php youp**n was developed with symfony ... So why do these sites not break down completely? Because their caching routines are clever. facebook Did you know for instance what facebook does if you write a status update? It does not save it right into a database table with all your status updates and if a friend visits his stream all the statuses from all his friend are being fetched from database prior to being served. facebook writes your status to all of your friends news streams and starts warming their cache. Now all the streams are being prepared for serving and whenever one of your friends visits his stream he will be served a cached version; instantly with almost no code execution involved. The stream will only show your newly created status when the cache warming has finished. we are talking about ms here ... What does this tell us? In modern highly-frequented applications almost everything is being served from cache and the user will not notice if the actual computing of the page took 1ms or 5 seconds. In a "real-world" scenario the end-user will notice no difference in req/sec between frameworks. Even with simple stuff like micro-caching you can have your vps hosted blog not go down instantly once you made it on hackernews's landing page. In the end the more important thing is ... does my framework provide the tools, the documentation and the tutorials and examples ... to get this whole thing up and running quick & easy. symfony does for me! If you're stuck ... how many people are there willing and able to answer your performance-related questions? How many real-world applications have already been or will in the near future be created with this framework? you choose a community by choosing a framework ! ... okay thats for the does it matter part ... now back to these benchmarks :) Benchmarks & Setups Over all these shiny colors and fancy graphs in the benchmark you easily miss the fact that there is only one setup ( webserver, database, ... ) tested with each of these frameworks while you can have a wide variety of configurations for each of them. Example: instead of using symfony2+doctrineORM+mysql you could also use symfony+doctrineODM+MongoDB. MySQL ... MongoDB ... Relational Databases ... NoSQL Databases ... ORM ... micro ORMs ... raw SQL ... all mixed up in these configurations ------> apples and oranges. Benchmarks & Optimization A common problem with almost all benchmarks - even those only comparing php frameworks - found around the web and also those "TechEmpower Web Framework Benchmarks" is unequal optimization . These benchmarks don't make use of possible (and by experienced developers well known) optimizations on those frameworks ... at least for symfony2 and their tests this is a fact. A few examples regarding the symfony2 setup used in their latest tests: "composer install" is not being called with the -o flag to dump an optimized classmap autoloader ( code ) Symfony2 will not use APC cache for Doctrine metadata annotations without apc_cli = 1 ( issue ) the whole DI container is injected in the controller instead of only the few necessary services hereby setter injection is used -> creates object then call setContainer() method instead of injecting the container directly into the constructor (see: BenchController extends Controller extends ContainerAware ) an alias ( $this->get('service_name') ) is used to retrieve services from the container instead of accessing it directly ($this->container->get('service_name') ). ( code ) ... the list continues ... but i guess you understood where this is leading. 90 open issues by now ... an endless story. Development & Ressources Ressources like servers and storage are cheap. Really cheap ... compared to development time. I am a freelancer charging considerably common rates. you can either get 2-3 days of my time ... or a sh**load of computing power and storage! When choosing a framework, you are also choosing a toolkit for rapid development - a weapon for your fight against the never completely satisfied, feature-creeping customer ... who will pay you well for his wishes. As an agency (or a freelancer) you want to build feature-rich applications in short time. You will face points where you are stuck with something ... maybe a performance related issue. But you are facing development costs and time as well. What will be more expensive? An additional server or an additional developer?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16696763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/613568/']}
jdg_377729
stackexchange
llm_judgeable_groundtruth_similarity
597743
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $A$ and $B$ be $n \times n$ matrices with entries in a field F. Suppose $A$ and $B$ are diagonalizable in some extension field E of F and that $\mathrm{Tr}(A^k)=\mathrm{Tr}(B^k)$ for all integers $k>0$. Show that A and $B$ have the same characteristic polynomial. $A$ and $B$ are diagonalizable over the field E, so there are invertible matrices $R$ and $S$, and diagonal matrices $D_A$ and $D_B$ with entries in E such that $RAR^{-1}=D_A$ and $SBS^{-1}=D_B$ Similar Matrices have the same characteristic polynomial, so if $P_X(\lambda)$ denotes the characteristic polynomial of a matrix X in variable $\lambda$, $P_A(\lambda)=P_{D_A}(\lambda)$ and $P_B(\lambda)=P_{D_B}(\lambda)$. We also have$\mathrm{Tr}(D_A^k)=\mathrm{Tr}((RAR^{-1})^k)=\mathrm{Tr}(RA^kR^{-1})=\mathrm{Tr}(A^k)=\mathrm{Tr}(B^k)=\mathrm{Tr}(D_B^k)$ for all integers $k>0$. I tried using the Cayley-Hamilton theorem on $P_{D_A}(\lambda)$ and taking the trace, but couldn't get anything out of it. Now provide the response and nothing else.
The equalities $\text{Tr}(A^k)=\text{Tr}(B^k)$ for all $k$ imply that $\text{Tr}(P(A))=\text{Tr}(P(B))$ for all polynomials $P$. Let $\lambda$ be an eigenvalue of $A$. If $\lambda$ is not an eigenvalue of $B$, then we can choose a polynomial such that $P(\lambda)=1$, and $P(\mu)=0$ for every other eigenvalue of $A$ and all eigenvalues of $B$. Then we would get $\text{Tr}(P(A))>0$, $\text{Tr}(P(B))=0$, a contradiction. This reasoning implies that $A$ and $B$ have the same lists of eigenvalues. And they have to appear with the same multipliticites: because if $\lambda$ is an eigenvalue of $A$ with multiplicity $n$ and of $B$ with multiplicity $m$, then choosing $P$ with $P(\lambda)=1$ and $P=0$ on all other eigenvalues we have $$n=\text{Tr}(P(A))=\text{Tr}(P(B))=m.$$So $A,B$ have the same eigenvalues, with the same multiplicities. In particular, they have the same characteristic polynomial. Edit: of course, as user1551 points out in his answer, my answer only works for fields where polynomials separate points.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/597743', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/79779/']}
jdg_377730
stackexchange
llm_judgeable_groundtruth_similarity
2277496
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to figure out this question, or rather, part a of this question from a practice final. I know that if you consider the fixed points of $g(x) = (α+1)x-x^2$ (which are $ x = 0, x= α $), but I don't know how to find the interval for which this series converges to the fixed point, or why it is $α-\frac{1}{5} < x < α+\frac{1}{5}$ and don't really know how to start in general for these types of problems which ask for a convergence interval. Now provide the response and nothing else.
Let's argue that $\cos(\sin x)>\sin(\cos x)$ at least on $[0,\frac{\pi}{2}]$. Suppose $x\in [0,\frac{\pi}{2}$]. First, we know $\sin x\le x$ so $\sin(\cos x)\le\cos x$ with equality only when $\cos x=0$, i.e., at $x=\frac{\pi}{2}$. Second, since $\cos x$ is decreasing, and $\sin x<=x$, $\cos (\sin x)\ge\cos x$, with equality only then $\sin x=0$, i.e., at $x=0$. Thus, $\cos(\sin x) > \sin(\cos x).$ Hence, $y=\cos(\sin x)$ intersects $y=x$ at a larger value of $x$ than $y=\sin(\cos x)$ does.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2277496', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/438201/']}
jdg_377731
stackexchange
llm_judgeable_groundtruth_similarity
37960246
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 one particular scenario I am taking the user to passcode settings page . below is the code used for this - [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=PASSCODE"]]; After upgrading to iOS 10 beta version I am no longer taken to settings passcode page instead it terminates the app . Can anyone please help me with this . Thanks in advance . Now provide the response and nothing else.
No way yet. About 1 month before iOS 10 beta 1 was released, my app got a rejection because of opening a Preference.app URL. The app review team gave me a phone call to explain it: It's not permitted right now for the reason: Using private API. Only opening current app's setting page(UIApplicationOpenSettingsURLString) is allowed. So it really makes sense now why they rejected me. Because no one could open system setting since iOS 10. Updated answer at 8 Dec, 2016: Using Private API (Don't submit the app with these code to the App Store): @interface PrivateApi_LSApplicationWorkspace- (BOOL)openSensitiveURL:(id)arg1 withOptions:(id)arg2;@endPrivateApi_LSApplicationWorkspace* _workspace;_workspace = [NSClassFromString(@"LSApplicationWorkspace") new];BOOL result = (BOOL)[_workspace openSensitiveURL:[NSURL URLWithString:@"Prefs:root=YOURSETTINGURLHERE"] withOptions:nil];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37960246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3933015/']}
jdg_377732
stackexchange
llm_judgeable_groundtruth_similarity
190698
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 taking Abstract Algebra and in the first assignment we were asked to determine which values of $n$ make the following function injective. $f: \mathbb{R}\rightarrow \mathbb{R}$ $x \mapsto x^n$ $| n \in \mathbb{N^+}$ Obviously the case where $n$ is even is quite easy to disprove. For the odd case I had a more difficult time. I understand that I could use the fact that the odd functions are continuous and because their derivative is positive everywhere (besides 0 which is dealt with separately), the function is increasing so $a > b \implies f(a) > f(b)$ which would prove it was injective. However, I do not think this is the proper way to go about it, as we have not and will not cover continuity and those sort of things. Not to mention this method seems out of place with the other problems in the homework which all deal with equivalence relations and general set theory questions. So I just want to know, is there a simpler way of going about proving the odd power function is injective that does not use much Real Analysis as much? Now provide the response and nothing else.
Take any $x,y$. If $x,y$ have different signs, so do their odd powers, so they are distinct. So we can assume that they have the same sign, wlog both are positive. Then $$x^{2n+1}-y^{2n+1}=(x-y)\left(\sum_{j=0}^{2n}x^jy^{2n-j}\right)$$And the second parenthesis is a positive expression, so the expression is zero iff $x=y$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/190698', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39392/']}
jdg_377733
stackexchange
llm_judgeable_groundtruth_similarity
2313879
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 Perl FAQ entry How do I strip blank space from the beginning/end of a string? states that using s/^\s+|\s+$//g; is slower than doing it in two steps: s/^\s+//;s/\s+$//; Why is this combined statement noticeably slower than the separate ones (for any input string)? Now provide the response and nothing else.
The Perl regex runtime runs much quicker when working with 'fixed' or 'anchored' substrings rather than 'floated' substrings. A substring is fixed when you can lock it to a certain place in the source string. Both '^' and '$' provide that anchoring. However, when you use alternation '|', the compiler doesn't recognize the choices as fixed, so it uses less optimized code to scan the whole string. And at the end of the process, looking for fixed strings twice is much, much faster than looking for a floating string once. On a related note, reading perl's regcomp.c will make you go blind. Update :Here's some additional details. You can run perl with the '-Dr' flag if you've compiled it with debugging support and it'll dump out regex compilation data. Here's what you get: ~# debugperl -Dr -e 's/^\s+//g'Compiling REx `^\s+'size 4 Got 36 bytes for offset annotations.first at 2synthetic stclass "ANYOF[\11\12\14\15 {unicode_all}]". 1: BOL(2) 2: PLUS(4) 3: SPACE(0) 4: END(0)stclass "ANYOF[\11\12\14\15 {unicode_all}]" anchored(BOL) minlen 1 # debugperl -Dr -e 's/^\s+|\s+$//g'Compiling REx `^\s+|\s+$'size 9 Got 76 bytes for offset annotations. 1: BRANCH(5) 2: BOL(3) 3: PLUS(9) 4: SPACE(0) 5: BRANCH(9) 6: PLUS(8) 7: SPACE(0) 8: EOL(9) 9: END(0)minlen 1 Note the word 'anchored' in the first dump.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2313879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244297/']}
jdg_377734
stackexchange
llm_judgeable_groundtruth_similarity
153607
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This sounds more like a brain teaser, but I had some kink to think it through :( Suppose you're parking at a non-parking zone, the probability to get a parking ticket is 80% in 1 hour, what is the probability to get a ticket in half an hour? Please show how you deduce the answer. Thanks! Now provide the response and nothing else.
It really depends on what model is assumed. However, if the idea is that no matter how long you leave your car there, you have a $20$% chance of getting through any given hour unscathed, you can treat it as an exponential decay problem. Let $p(t)$ be the probability that you do not get a ticket in the first $t$ hours. Then $p(1)=0.2$, $p(2)=0.2^2$ (a $20$% chance of making it through the first hour times a $20$% chance of making it through the second), and in general $p(t)=0.2^t$. The probability of not getting a ticket in the first half hour is then $p(1/2)=0.2^{1/2}=\sqrt{0.2}\approx 0.4472$, and the probability that you do get a ticket in the first half hour is about $1-0.4472=0.5528$.
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/153607', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32859/']}
jdg_377735
stackexchange
llm_judgeable_groundtruth_similarity
37149001
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use docker-compose to compose together php and several databases (orientdb, neo4j, etc). Then get into the php container and use the shell to execute commands. Individually, all of my container work swimmingly, and when I compose them together, they all run. However, I cannot for the life of me figure out how to keep the php container alive so I can get into it for testing. For simplicity, I'll just use a single database: orient-db. My docker-compose.yml file: version: '2'services: php: build: . links: - orientdb orientdb: image: orientdb:latest environment: ORIENTDB_ROOT_PASSWORD: rootpwd ports: - "2424:2424" - "2480:2480" My "php" Dockerfile : FROM php:5.6-cliADD . /spiderWORKDIR /spiderRUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin/ --filename=composerRUN composer install --prefer-source --no-interactionRUN yes | pecl install xdebug \ && echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" > /usr/local/etc/php/conf.d/xdebug.ini I have tried (among other things): docker-compose up in one terminal and then docker attach in another enabling tty and stdin_open in my compose file using a /bin/bash command variations of CMD exec vendor/bin/phpunit -D FOREGROUND And some references I've tried: - How to Keep Docker Container Running After Starting Services? - https://github.com/docker/compose/issues/1926 - https://github.com/docker/compose/issues/423 Any help would really be appreciated. Thank you. Now provide the response and nothing else.
So docker-compose is just a stand-in for the docker-engine client. It maintains feature parity with the client. For diagnosing problems like this, you should drop the use of docker-compose until you get it working with the regular ole client. Based on your comments here and on the other answer, it just sounds like you're not running a container with a daemon process in the foreground. If you want to run an interactive shell in Docker, you have to use the -it flags ( -t allocates a tty and -i initiates an interactive session). If you don't run Docker with those switches, your container won't survive you starting an interactive shell, e.g. php -a . It helps to think of Docker as a fancy way to run a process and not a virtual machine. It's not some "environment" that exists outside of the lifetime of whatever process (and its children) you are running. Normally, PHP is invoked by some server (e.g. Apache, Nginx, etc). What you're implying here is that you need a PHP process to run "permanently" so that you can drop into the container and test some things. Except for the interactive shell, that's not going to be possible, and you need specifically to use the -it switch to keep an interactive shell process alive in your container. The real answer here is that you can't do what you're trying to do here (keep a PHP container running) without some related daemon/server process listening in the foreground. The reason for that is because that's not how PHP works. If you really want to get into a container from your PHP image, just drop into a shell on it: docker run -it apollo/php /bin/bash ... And you'll start a container from your PHP image, and get a shell on the container (which will die as soon as you exit the shell). But again, just reiterating from my first paragraph, docker-compose is not the way to go here.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37149001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2475951/']}
jdg_377736
stackexchange
llm_judgeable_groundtruth_similarity
26906
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to understand visually the complex coefficient of Fourier series (shown as $C_n$ in many sources)? I mean something similar to this which represents $e^{j\omega_0 t}$: . $\omega_0 \triangleq 2 \pi f_0 .$ But when I read $C_n e^{jn\omega_0 t}$ my mind shuts down. Here is complex Fourier series: http://www.thefouriertransform.com/series/complexFourier.jpg .And its one element is $C_n e^{j n \omega_0 t}$. How can I visualize this element? And does $C_n$ have a meaning besides being a coefficient? Now provide the response and nothing else.
if you think of $e^{j n \omega_0 t}$ as a "vector" (complex numbers are not quite the same as 2-dimensional vectors, but they look the same, and are both describable with two real numbers) with length 1 and starting out with an angle of 0 (pointing straight to the right, along the positive real axis, and this vector is rotating counter-clockwise at a rate of $n \omega_0$ radians per unit time. this vector is what you see looking down the spiral in the graphic referred to in the question, looking along the time axis. then multiplying by $C_n$ changes the length of the vector to $|C_n|$ and the initial angle of the vector is the angle of $C_n$ or $\arg\{C_n\}$. that's how i would visualize it.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/26906', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/7555/']}
jdg_377737
stackexchange
llm_judgeable_groundtruth_similarity
2991572
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: two shared libraries liba.so and libb.so. liba.so uses libb.so. All c files are compiled with -fPIC. Linking uses -shared. When we call dlopen on liba.so it cannot find symbols in libb.so...we get the "undefined symbol" error. We can dlopen libb.so with no errors. We know that liba is finding libb because we don't get a file not found error. We get a file not found error when we delete libb.so. We tried -lutil and no luck. Any ideas???? oh yeah. gcc 4.1.2 update: We use rpath when linking liba so it can find libb. ldd liba.so returns: linux-gate.so.1 => (0xffffe000) libb.so => ./libb.so (0xf6ef9000) <-------- LIBB libutil.so.1 => /lib/libutil.so.1 (0xf6ef5000) libdl.so.2 => /lib/libdl.so.2 (0xf6ef1000) libm.so.6 => /lib/libm.so.6 (0xf6ec9000) libpthread.so.0 => /lib/libpthread.so.0 (0xf6eb1000) librt.so.1 => /lib/librt.so.1 (0xf6ea8000) libc.so.6 => /lib/libc.so.6 (0xf6d62000) /lib/ld-linux.so.2 (0x007d0000) is it significat that there is no .# at the end of libb??? Now provide the response and nothing else.
You can easily check where libb.so is expected to be with ldd command: $ ldd liba.so linux-gate.so.1 => (0xb77b0000) libb.so.1 => not found libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb75b6000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7572000) libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb742b000) /lib/ld-linux.so.2 (0xb77b1000) If it's not found , libb.so 's path should be added to /etc/ld.so.conf or shell variable LD_LIBRARY_PATH . Another way is setting rpath in the liba.so itself - it's basically hardcoding its path so when the binary is started the dynamic linker would know where to search for the shared libraries. If rpath is not set it will first search in LD_LIBRARY_PATH , then the paths mentioned in /etc/ld.so.conf (or /etc/ld.so.conf.d/). After adding to ls.so.conf don't forget to execute /sbin/ldconfig Dynamic linker searches the dependent shared libraries by their soname (if it's set) - if soname is not set (with -Wl,-soname,libb.so.1 for example), it will be searched by library's name. Example: libb.so.1.0 is your actual library, having soname - libb.so.1 . You would normally have the following files structure: libb.so -> libb.so.1libb.so.1 -> libb.so.1.0libb.so.1.0 where libb.so and libb.so.1 are symlinks. You usually link to libb.so , when building some application or other library, depending on libb.so . gcc -shared -Wl,-soname,liba.so.1 -o liba.so.1.2 -L/libb/path -lb When the application is started (or dlopen is executed - your case) - the dynamic linker will search for file with name libb.so.1 - the soname of dependent library, if the soname is set, not libb.so . That's why you need that symlink libb.so.1 , pointing to the actual library. If you use ld.so.conf and ldconfig , it will create the symlink with soname 's name, pointing to the library file, if this symlink is missing. You can see ld-linux man page for more useful info. If the library is found but some of the symbols are missing, try building libb.so with -Wl,--no-undefined option gcc -shared -Wl,-soname,libb.so.1 -Wl,--no-undefined -o libb.so.1.2 It should give you an error if you missed to define some symbol.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2991572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121540/']}
jdg_377738
stackexchange
llm_judgeable_groundtruth_similarity
2394246
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I have y distinct values and I want to select x of them at random. What's an efficient algorithm for doing this? I could just call rand() x times, but the performance would be poor if x , y were large. Note that combinations are needed here: each value should have the same probability to be selected but their order in the result is not important. Sure, any algorithm generating permutations would qualify, but I wonder if it's possible to do this more efficiently without the random order requirement. How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N covers this case for permutations. Now provide the response and nothing else.
Robert Floyd invented a sampling algorithm for just such situations. It's generally superior to shuffling then grabbing the first x elements since it doesn't require O(y) storage. As originally written it assumes values from 1..N, but it's trivial to produce 0..N and/or use non-contiguous values by simply treating the values it produces as subscripts into a vector/array/whatever. In pseuocode, the algorithm runs like this (stealing from Jon Bentley's Programming Pearls column "A sample of Brilliance"). initialize set S to emptyfor J := N-M + 1 to N do T := RandInt(1, J) if T is not in S then insert T in S else insert J in S That last bit (inserting J if T is already in S) is the tricky part. The bottom line is that it assures the correct mathematical probability of inserting J so that it produces unbiased results. It's O(x) 1 and O(1) with regard to y , O(x) storage. Note that, in accordance with the combinations tag in the question, the algorithm only guarantees equal probability of each element occuring in the result, not of their relative order in it. 1 O(x 2 ) in the worst case for the hash map involved which can be neglected since it's a virtually nonexistent pathological case where all the values have the same hash
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2394246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377739
stackexchange
llm_judgeable_groundtruth_similarity
716049
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 getting started with virtualization so bear with me. In virtual environments applications run in a hypervisor's layer. So a single physical machine could have many virtual machines on it running multiple applications. So far so good? So what happens when a physical machine fails? Wouldn't that make many applications fail all from a single machine? I'm searching for developing a private cloud with OpenStack , but I want to fully understand virtualization first. Now provide the response and nothing else.
The specifics depend on which exact virtualization solution you use, but the idea is that you have a virtual farm, where there are a number of physical hosts with several virtual machines each. You then use some of the efficiency you gained by not needing a physical host for every VM so that you have enough overhead left to cover in the case where a physical machine goes down. Additionally, you can locate the VHDs for each VM on a common (redundant) SAN. The hypervisors on each physical host can be set to talk with each other and share memory from different VMs. There is some latency, and much of the memory will be backed by disk, but if one of the physical hosts go down you're not even waiting for the VMs from that host to boot back up. Instead, those VMs will be automatically distributed among the remaining hosts. The ultimate goal is that these machines will pick up from almost where they left off , with little to no downtime at all. In a sense, all of your VMs are already running on at least two physical hosts. In practice, right now hypervisors can only do this kind of migration one machine at a time, when they know it's coming before the host fails... but make no mistake: instant migration on hardware failure is the ultimate goal for all of the major hypervisors. This is why you sometimes see a server virtualized to a single physical host in a farm. You may not gain any hardware efficiency (you may even lose some performance), but you make up for it in terms of management consistency and built-in high-availability.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/716049', 'https://serverfault.com', 'https://serverfault.com/users/306263/']}
jdg_377740