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
544228
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: Question : Is the following true for any $m\in\mathbb N$? $$\begin{align}\sum_{k=1}^{m-1}\frac{1}{\sin^2\frac{k\pi}{m}}=\frac{m^2-1}{3}\qquad(\star)\end{align}$$ Motivation : I reached $(\star)$ by using computer. It seems true, but I can't prove it. Can anyone help? By the way, I've been able to prove $\sum_{n=1}^{\infty}\frac{1}{n^2}=\frac{{\pi}^2}{6}$ by using $(\star)$. Proof : Let $$f(x)=\frac{1}{\sin^2x}-\frac{1}{x^2}=\frac{(x-\sin x)(x+\sin x)}{x^2\sin^2 x}.$$We know that $f(x)\gt0$ if $0\lt x\le {\pi}/{2}$, and that $\lim_{x\to 0}f(x)=1/3$. Hence, letting $f(0)=1/3$, we know that $f(x)$ is continuous and positive at $x=0$. Hence, since $f(x)\ (0\le x\le {\pi}/2)$ is bounded, there exists a constant $C$ such that $0\lt f(x)\lt C$. Hence, substituting $x={(k\pi)}/{(2n+1)}$ for this, we get$$0\lt \frac{1}{\frac{2n+1}{{\pi}^2}\sin^2\frac{k\pi}{2n+1}}-\frac{1}{k^2}\lt\frac{{\pi}^2C}{(2n+1)^2}.$$Then, the sum of these from $1$ to $n$ satisfies $$0\lt\frac{{\pi}^2\cdot 2n(n+1)}{(2n+1)^2\cdot 3}-\sum_{k=1}^{n}\frac{1}{k^2}\lt\frac{{\pi}^2Cn}{(2n+1)^2}.$$Here, we used $(\star)$. Then, considering $n\to\infty$ leads what we desired. Now provide the response and nothing else.
Consider the polynomial $S_m(x)$, satisfying $S_m(\sin^2 \theta)=\sin^2(m\theta)$. These are known as spread polynomials, and may easily be derived from the Chebyshev polynomials $T_m(x)$, via $$1-2S_m(\sin^2(\theta)=1-2\sin^2(m\theta)=\cos(m(2\theta))=T_m(\cos(2\theta))=T_m(1-2\sin^2 \theta)$$ so $1-2S_m(x)=T_m(1-2x)$. Note that \begin{align}&S_{m+1}(\sin^2 \theta)+S_{m-1}(\sin^2 \theta) \\& =\sin^2(m\theta+\theta)+\sin^2(m\theta-\theta) \\&=(\sin(m\theta)\cos \theta+\cos(m\theta)\sin \theta)^2+(\sin(m\theta)\cos \theta-\cos(m\theta)\sin \theta)^2 \\&=2\sin^2(m \theta)\cos^2 \theta+2\cos^2(m \theta) \sin^2(m\theta) \\&=2(1-\sin^2 \theta)S_m(\sin^2 \theta)+2\sin^2 \theta(1-S_m(\sin^2 \theta))\end{align} Thus $S_{m+1}(x)=2(1-2x)S_m(x)-S_{m-1}(x)+2x$. (We could also have used the more well known recurrence $T_{n+1}(x)=2xT_n(x)-T_{n-1}(x)$ and derived the recurrence for $S_m$ from there.) Observe that $\sin^2(\frac{k\pi}{m}), k=0, 1, \ldots, m-1$ are roots of the polynomial equation $S_m(x)=0$. Put $S_m(x)=xP_m(x)$, so that $\sin^2(\frac{k\pi}{m}), k=1, 2, \ldots, m-1$ are roots of the polynomial equation $P_m(x)=0$. The recurrence for $S_m$ gives $$P_{m+1}(x)=2(1-2x)P_m(x)-P_{m-1}(x)+2$$ Now if we write $P_m(x)=a_m+b_mx+x^2Q_m(x)$, it is clear by Vieta's formulas that $$\sum_{k=1}^{m-1}{\frac{1}{\sin^2(\frac{k\pi}{m})}}=\frac{\sum_{k=1}^{m-1}{\prod_{j \not =k}{\sin^2(\frac{j\pi}{m})}}}{\prod_{i=1}^{m-1}{\sin^2(\frac{k\pi}{m})}}=-\frac{b_m}{a_m}$$ We prove by induction on $m$ that $a_m=m^2, b_m=-\frac{(m^2-1)m^2}{3}$. When $m=1$, we have $S_1(x)=x$ so $P_1(x)=1=(1^2)-\frac{(1^2-1)1^2}{3}x$ so the statement is true for $m=1$. When $m=2$, we have $S_2(x)=4x(1-x)$ so $P_2(x)=4-4x=2^2-\frac{(2^2-1)2^2}{3}x$ so the statement is true for $m=2$. Suppose that the statement holds for $m=i-1, i$, where $i \geq 2$. Then \begin{align}P_{i+1}(x)&=2(1-2x)P_i(x)-P_{i-1}(x)+2 \\&=2(1-2x)(a_i+b_ix+x^2Q_i(x))-(a_{i-1}+b_{i-1}x+x^2Q_{i-1}(x))+2 \\&=(2a_i-a_{i-1}+2)+(2b_i-4a_i-b_{i-1})x+x^2(-4b_i+2Q_i(x)-Q_{i-1}(x))\end{align} Thus (after some algebra manipulation) $$a_{i+1}=2a_i-a_{i-1}+2=(i+1)^2$$ and \begin{align}b_{i+1}=2b_i-4a_i-b_{i-1}&=-2\frac{(i^2-1)i^2}{3}-4i^2+\frac{((i-1)^2-1)(i-1)^2}{3} \\&=-\frac{((i+1)^2-1)(i+1)^2}{3}\end{align} We are thus done by induction. Now, $$\sum_{k=1}^{m-1}{\frac{1}{\sin^2(\frac{k\pi}{m})}}=-\frac{b_m}{a_m}=-\frac{-\frac{(m^2-1)m^2}{3}}{m^2}=\frac{m^2-1}{3}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/544228', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78967/']}
jdg_370941
stackexchange
llm_judgeable_groundtruth_similarity
191884
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: Often I like to define my own functions that are almost exactly the same as Mathematica defined functions, apart from a few tweaks. See this question for example. I want to define them properly so they handle optional arguments correctly. What is a general strategy for accomplishing this? Here's a concrete (esoteric) example. I define myListPlot that is almost identical to ListPlot except that is adds a gridline corresponding to the first data point. data = Table[RandomReal[], {x, 1, 10}]myListPlot[data_, opts_] := ListPlot[data, GridLines -> {None, {data[[1]]}}, opts]myListPlot[data, {PlotStyle -> Red, Joined -> True}] Not too bad. However I have to pass the optional arguments as a list. Instead, I would like to pass the optional arguments in the same way one does with ListPlot . In other words, I would like to modify myListPlot so that I would pass arguments like myListPlot[data, PlotStyle -> Red, Joined -> True] Perhaps I'm going about this completely the wrong way. Nevertheless I hope the reader understands what I'm trying to accomplish and can suggest a solution. Now provide the response and nothing else.
If you want to constrain it to only options from ListPlot , you could use OptionsPattern in combination with FilterRules and Options . myListPlot[data_, opts : OptionsPattern[]] := ListPlot[data, GridLines -> {None, {data[[1]]}}, FilterRules[{opts}, Options[ListPlot]]] which results in: myListPlot[data, PlotStyle -> Red, Joined -> True]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/191884', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6328/']}
jdg_370942
stackexchange
llm_judgeable_groundtruth_similarity
1375617
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I'm trying to wrap my head around Objective-C interfaces, delegates and protocols.So I have a question: Does a delegate have to be in a separate file or can it be methods defined in your class? Is a protocol like a java interface? This is the way I understand it at the moment where it basically makes you implement methods if you use this protocol. I'm still confused about interfaces. I'm pretty sure they have no resemblance to what an interface is in java. Maybe it's just a declaration of variables that will be implemented in the class. Now provide the response and nothing else.
A delegate protocol needs to be defined as such @protocol //methods@end it can be put in any .h class, you just need to import i t whenever you are going to use it. A protocol is not like a java interface, a protocol is an adapter that allows two classes to works together. Basically it says, if you want class A to send you messages about its state and actions these are the methods it will call on its delegate that you must implement. Its not like an interface because an interface says if you want to subclass this class you must implement these methods, the protocol says if you want to interact with this class you must implement these methods, so its somewhat different.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1375617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44160/']}
jdg_370943
stackexchange
llm_judgeable_groundtruth_similarity
24290813
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 script that I am writing which relies on functions in an imported module. This script takes a while due to IO (web requests) and I would like to parallize it for hundreds of thousands of iterations of a script block. After attempting several different methods (with little success due to restrictions with Start-Job and other things) the current implementation relies on pre-creating a pool of powershell "shells" created via $shell = [Powershell]::Create() . One of the module methods I have to call to bootstrap the shell (so it's in a correct state) has a call to Write-Host in it. When I call $shell.Invoke() the following error occurs: Write-Host : A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows. Now, since the module is custom I can remove the Write-Host calls, but that reduces user friendliness when it is run directly by end users. I can create a switch parameter that does not execute Write-Host if the parameter is true, but to do that down the line is a good bit of work (feasible, but I'd rather not). Is there any way I can get Write-Host to not error out in this scenario? I don't actually care about the input in this scenario, I just don't want the errors. Now provide the response and nothing else.
The fastest way to get this to work is to define a dummy write-host function in your script, or to simply define it in the runspace independently before running your script. $ps.addscript("function write-host {}").invoke()$ps.commands.clear()# now you can invoke scripts that use write-host# feel free to implement a write-host that writes to a log file Simple as that. The reason you're getting that error is because programmatic invocation like that does not expect user interaction. There are ways to make this work but it employs different APIs.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24290813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231002/']}
jdg_370944
stackexchange
llm_judgeable_groundtruth_similarity
12456579
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: suppose I have following sql statement in sql server 2008: BEGIN TRANSACTION SqlStatement1 EXEC sp1 SqlStatement3COMMIT TRANSACTION The code of sp1 BEGIN TRANSACTIONSqlStatement2ROLLBACK TRANSACTION My question is: Is SqlStatement3 actually executed? Now provide the response and nothing else.
SQL Server doesn't really support nested transactions. There is only one transaction at a time. This one transaction has a basic nested transaction counter, @@TRANCOUNT . Each consecutive begin transaction increments the counter by one, each commit transaction reduces it by one. Only the commit that reduces the counter to 0 really commits the one transaction. A rollback transaction undoes the one transaction and clears @@TRANCOUNT . In your case, the funny result is that SqlStatement3 is run outside a transaction! Your final commit will throw an "The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION" exception, but the effects of SqlStatement3 are permanent. For example: create table #t (col1 int)insert #t (col1) values (1)BEGIN TRANSACTIONupdate #t set col1 = 2 -- This gets rolled backBEGIN TRANSACTIONupdate #t set col1 = 3 -- This gets rolled back tooROLLBACK TRANSACTIONupdate #t set col1 = 4 -- This is run OUTSIDE a transaction!COMMIT TRANSACTION -- Throws errorselect col1 from #t Prints 4 . Really. :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12456579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1091308/']}
jdg_370945
stackexchange
llm_judgeable_groundtruth_similarity
14951931
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm confused by the following code: trait T1 { type S } trait T2 { self: T1 => case class ClS(s: S) } object O extends T2 { } It gives out the following error message: illegal inheritance; tests.O.type does not conform to tests.T2's selftype tests.T2 with tests.T1 What's going wrong? the reason that I extend O with T2 is that I want to reference the class CLS in O , how can I achieve that? Now provide the response and nothing else.
trait T2 has a contract that says: If you inherit from me, you should also inherit from T1 . object O extends T2 with T1 You would then probably get an error that type S is not defined. Which is a good thing since it's used in the definition of CLS
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14951931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1663861/']}
jdg_370946
stackexchange
llm_judgeable_groundtruth_similarity
2719068
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 $K$ be a field; I will say a polynomial $f \in K[X]$ represents an element $a \in K$ if there exists a $b \in K$ such that $f(b) = a$. Denote by $\mathbb{Q}$, $\mathbb{R}$ and $\mathbb{Q}_p$ the fields of rational, real and $p$-adic numbers respectively. Does there exist a polynomial $f \in \mathbb{Q}[X]$ such that $f$ represents only squares over $\mathbb{R}$ (but not all squares need to be represented), $f$ represents only squares over $\mathbb{Q}_2$ (but not all squares need to be represented), for every prime number $p > 2$, $f$ does not represent only squares over $\mathbb{Q}_p$? If so, what is the minimal degree such a polynomial must have? What I have found so far: A polynomial satisfying $1$ and $3$, but not $2$:$$1 + X^2$$ A polynomial satisfying $1$ and $2$ and which I think might also satisfy $3$, but I do not know how to prove it:$$(1 + X^2)(17 + X^2)$$Here, $17$ may be replaced with any positive integer with residue $1$ modulo $16$. Now provide the response and nothing else.
Clearly degree 1 and 3 polynomials do not satisfy property 1. The only degree 2 polynomials in $\mathbb{Q}[X]$ with property 2 are squares. To verify this, after a possible change of variables assume that $aX^2+b$ is a polynomial generating only squares over $\mathbb{Q}_2$ with $b\ne 0$. By setting $X=0$ we know $b$ is a square in $\mathbb{Q}_2$, so multiplying by $b^{-1}$ we can assume $b=1$. Next, write $a=2^nc$ with $n=v_2(a)$ its $2$-adic valuation, so that $c\in \mathbb{Z}_2^{\times}$. If $n$ is even, say $n=2m$, set $X=c2^{1-m}$ to find that $4c^2+1$ is a square in $\mathbb{Q}_2$, but we reach a contradiction as $5$ is not a square modulo $8$. If $n$ is odd, say $n=2m-1$, set $x=2^{-m}$ to yield that $c/2+1$ is a square in $\mathbb{Q}_2$, which is impossible because its valuation is $-1$. Finally, there do exist polynomials of degree 4 satisfying all three properties. In particular $f(X)=(8X^2+1)(8X^2+9)$ does the job. Property 1 is clear, so let us check property 2. The (extended) Hensel's lemma tells you that if a polynomial in $\mathbb{Q}_2[X]$ has a root modulo 8 whose derivative at that root is not divisible by 4, then the polynomial has a root in $\mathbb{Q}_2$. Let $a\in\mathbb{Q}_2$ be arbitrary, and write $a=2^nb$ with $b\in \mathbb{Z}_2^{\times}$. When $n\ge -1$, we can apply the above to $X^2-(8a^2+1)(8a^2+9)$. When $n<-1$, we can see that $$f(a)=2^{2(2n+3)}(b^2+2^{-2n-3})(b^2+9\cdot 2^{-2n-3})$$ and thus apply Hensel's to $X^2-2^{-2(2n+3)}f(a)$. As for property 3 (inspired by user mercio's comment below), Let $p$ be an odd prime and suppose $f(X)$ only generates squares over $\mathbb{Q}_p$. As $f(1)\equiv 3\pmod{9}$, we can assume $p\ne 3$. Then the elliptic curve $$E:y^2=(8x^2+1)(8x^2+9)$$ has good reduction at $p$ (Wolphram tells me the discriminant is $2^{34}\cdot 9$). Under the assumption $f(x)$ is a square mod $p$ for any $x$, the number of points on $E$ must be at least $2p-4$. The Hasse bound yields at most $2\sqrt{p}+p$ points (note we ignore the point at infinity). Thus, $$2p-4\le 2\sqrt{p}+p$$ which is false for $p\ge 5$. In particular there is an $x$ with $(8x^2+1)(8x^2+9)$ not a square mod $p$, thus $f(X)$ cannot generate only squares in $\mathbb{Q}(X)$.(Numerical data suggests in fact that more or less half of the numbers $(8x^2+1)(8x^2+9)$ for $x\in\mathbb{F}_p$ are quadratic residues). The polynomial suggested by the OP works as well, the proof for property three works equally well except additionally one has to exhibit a nonsquare for the prime $17$ ($x=2$ works).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2719068', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/294785/']}
jdg_370947
stackexchange
llm_judgeable_groundtruth_similarity
22124555
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to make my User model RESTful via Django Rest Framework API calls, so that I can create users as well as update their profiles. However, as I go through a particular verification process with my users, I do not want the users to have the ability to update the username after their account is created. I attempted to use read_only_fields, but that seemed to disable that field in POST operations, so I was unable to specify a username when creating the user object. How can I go about implementing this? Relevant code for the API as it exists now is below. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'password', 'email') write_only_fields = ('password',) def restore_object(self, attrs, instance=None): user = super(UserSerializer, self).restore_object(attrs, instance) user.set_password(attrs['password']) return userclass UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = UserSerializer model = User def get_permissions(self): if self.request.method == 'DELETE': return [IsAdminUser()] elif self.request.method == 'POST': return [AllowAny()] else: return [IsStaffOrTargetUser()] Thanks! Now provide the response and nothing else.
It seems that you need different serializers for POST and PUT methods. In the serializer for PUT method you are able to just except the username field (or set the username field as read only). class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = UserSerializer model = User def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'PUT': serializer_class = SerializerWithoutUsernameField return serializer_class def get_permissions(self): if self.request.method == 'DELETE': return [IsAdminUser()] elif self.request.method == 'POST': return [AllowAny()] else: return [IsStaffOrTargetUser()] Check this question django-rest-framework: independent GET and PUT in same URL but different generics view
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22124555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3295758/']}
jdg_370948
stackexchange
llm_judgeable_groundtruth_similarity
9350528
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In a previous question, Accessing scala.None from Java , it seems that people had used javap to figure out how to access scala.None from Java. I would like to know how they did that. FYI, the answer is: scala.Option$.MODULE$.apply(null); which can be shorted to: scala.Option.apply(null); Given this program ( OptionTest.scala ): object OptionTest extends App { val x = scala.None val y = scala.Some("asdf")} I ran javap on it like this: javap -s -c -l -private OptionTest This is a portion of the javap output: public static final scala.None$ x(); Signature: ()Lscala/None$; Code: 0: getstatic #11; //Field OptionTest$.MODULE$:LOptionTest$; 3: invokevirtual #55; //Method OptionTest$.x:()Lscala/None$; 6: areturn I also ran javap on scala.None and scala.Option . How would one figure out from the javap output that: None is a sole object of None.type type which extends Option The apply() method for the companion object is required ? Now provide the response and nothing else.
There are rules how Scala code is compiled to JVM-bytecode. Because of potential name clashes the generated code is not always intuitive to understand but if the rules are known it is possible to get access to the compiled Scala code within Java. Attention: While writing this, I noticed that javac and eclipse-javac behave differently in accessing Scala code from Java. It is possible that the code below compile with one of them but not with the other. Classes, Constructors, Methods There are no special rules here. The following Scala class class X(i: Int) { def m1 = i*2 def m2(a: Int)(b: Int) = a*b def m3(a: Int)(implicit b: Int) = a*b} can be accessed like a normal Java class. It is compiled to a file named X.class : X x = new X(7);x.m1();x.m2(3, 5);x.m3(3, 5); Notice, that for methods without a parameterlist an empty parameterlist is created. Multiple parameterlists are merged to a single one. Fields, Values For a class class X(var i: Int) Getters and Setters are created. For a class class X(val i: Int) only a Getter is created: //Scalaval x = new X(5)x.i = 3 // Setterx.i // Getter//JavaX x = new X(5);x.i_$eq(3); // Setterx.i(); // Getter Notice, that in Java an identifier is not allowed to include special signs. Therefore scalac generates for each of these special signs a specific name. There is a class scala.reflect.NameTransformer which can encode/decode the ops: scala> import scala.reflect.NameTransformer._import scala.reflect.NameTransformer._scala> val ops = "~=<>!#%^&|*/+-:\\?@"ops: String = ~=<>!#%^&|*/+-:\?@scala> ops map { o => o -> encode(o.toString) } foreach println(~,$tilde)(=,$eq)(<,$less)(>,$greater)(!,$bang)(#,$hash)(%,$percent)(^,$up)(&,$amp)(|,$bar)(*,$times)(/,$div)(+,$plus)(-,$minus)(:,$colon)(\,$bslash)(?,$qmark)(@,$at) A class class X { var i = 5 } is translated by the same schema as when the field is created in the constructor. Direct access to the variable i from Java is not possible, because it is private. Objects There is no such thing as a Scala object in Java. Therefore scalac has to do some magic. For an object object X { val i = 5 } two JVM-class files are generated: X.class and X$.class . The first one works like an interface, it includes static methods to access fields and methods of the Scala object. The latter is a singleton class which cannot be instantiated. It has a Field which holds the singleton instance of the class, named MODULE$ , which allows access to the singleton: X.i();X$.MODULE$.i(); Case classes The Scala compiler automatically generates an apply-method for a case class and Getters for fields. The case class case class X(i: Int) is easily accessed: new X(3).i();X$.MODULE$.apply(3); Traits A trait trait T { def m } , which contains only abstract members, is compiled to an interface, which is placed in a class files named T.class . Therefore it can easily implemented by a Java class: class X implements T { public void m() { // do stuff here }} If the trait contains concrete members there is a class file named <trait_name>$class.class generated, additionally to the normal interface. The trait trait T { def m1 def m2 = 5} can also easily implemented within Java. The class file T$class.class contains the concrete members of the trait, but it seems that they are impossible to access from Java. Neither javac nor the eclipse-javac will compile an access to this class. Some more detail about how traits are compiled can be found here . Functions Function literals are compiled as anonymous instances of the classes FunctionN. A Scala object object X { val f: Int => Int = i => i*2 def g: Int => Int = i => i*2 def h: Int => Int => Int = a => b => a*b def i: Int => Int => Int = a => { def j: Int => Int = b => a*b j }} is compiled to the normal class-files, as describes above. Furthermore each function literal gets its own class-file. So, for function values a class file named <class_name>$$anonfun$<N>.class is generated, where N is a continuous number. For function methods (methods, which return a function) a class file named <class_name>$$anonfun$<method_name>$<N>.class is generated. The parts of the function name are separated by dollar signs and in front of the anonfun identifier there are also two dollar signs. For nested functions the name of the nested function is appended to the outer function, this means an inner function will get a class file like <class_name>$$anonfun$<outer_method_name>$<N>$$anonfun$<inner_method_name>$<N>.class . When an inner function does not have a name, as seen in h it gets the name apply . This means in our case we get: X$$anonfun$1.class for f X$$anonfun$g$1.class for g X$$anonfun$h$1$$anonfun$apply$1.class for h X$$anonfun$i$1.class and X$$anonfun$i$1$$anonfun$j$1$1.class for i and j To access them use their apply-method: X.f().apply(7);X.g().apply(7);X.h().apply(3).apply(5);X.i().apply(3).apply(5); Answer the question You should know: a normal Scala class can accessed by their constructors or their apply-methods when there is no constructor than there is an apply-method when there is no constructor and no apply method than there is a another class file named the same way the class is called which appends a dollar sign at the end. Search this class for a MODULE$ field constructors and apply-methods are inherited, so search the super-classes if you can't find anything in the subclasses Some examples Option // javap scala.Optionpublic abstract class scala.Option extends java.lang.Object implements ... { ... public static final scala.Option apply(java.lang.Object); public scala.Option();} javap says it has a constructor and an apply method. Furthermore it says the class is abstract. Thus only the apply-method can used: Option.apply(3); Some // javap scala.Somepublic final class scala.Some extends scala.Option implements ... { ... public scala.Some(java.lang.Object);} It has a constructor and an apply-method (because we know Option has one and Some extends Option). Use one of them and be happy: new Some<Integer>(3);Some.apply(3); None // javap scala.Nonepublic final class scala.None extends java.lang.Object{ ...} It has no constructor, no apply-method and doesn't extend Option. So, we will take a look to None$ : // javap -private scala.None$public final class scala.None$ extends scala.Option implements ... { ... public static final scala.None$ MODULE$; private scala.None$();} Yeah! We found a MODULE$ field and the apply-method of Option. Furthermore we found the private constructor: None$.apply(3) // returns Some(3). Please use the apply-method of Option insteadNone$.MODULE$.isDefined(); // returns falsenew None$(); // compiler error. constructor not visible List scala.collection.immutable.List is abstract, thus we have to use scala.collection.immutable.List$ . It has an apply-method which expects an scala.collection.Seq . So to get a List we need first a Seq. But if we look to Seq there is no apply-method. Furthermore when we look at the super-classes of Seq and at scala.collection.Seq$ we can only find an apply-methods which expects a Seq. So, what to do? We have to take a look how scalac creates an instance of List or Seq. First create a Scala class: class X { val xs = List(1, 2, 3)} Compile it with scalac and look at the class file with javap: // javap -c -private Xpublic class X extends java.lang.Object implements scala.ScalaObject{...public X(); Code: 0: aload_0 1: invokespecial #20; //Method java/lang/Object."<init>":()V 4: aload_0 5: getstatic #26; //Field scala/collection/immutable/List$.MODULE$:Lscala/collection/immutable/List$; 8: getstatic #31; //Field scala/Predef$.MODULE$:Lscala/Predef$; 11: iconst_3 12: newarray int 14: dup 15: iconst_0 16: iconst_1 17: iastore 18: dup 19: iconst_1 20: iconst_2 21: iastore 22: dup 23: iconst_2 24: iconst_3 25: iastore 26: invokevirtual #35; //Method scala/Predef$.wrapIntArray:([I)Lscala/collection/mutable/WrappedArray; 29: invokevirtual #39; //Method scala/collection/immutable/List$.apply:(Lscala/collection/Seq;)Lscala/collection/immutable/List; 32: putfield #13; //Field xs:Lscala/collection/immutable/List; 35: return} The constructor is interesting. It tells us, that an array of ints is created (l. 12) which is filled with 1, 2 and 3. (l. 14-25). After that this array is delivered to scala.Predef$.wrapIntArray (l. 26). This resulting scala.collection.mutable.WrappedArray is again delivered to our List (l. 29). At the end, the List is stored in the field (l. 32).When we wanna create a List in Java, we have to do the same: int[] arr = { 1, 2, 3 };WrappedArray<Object> warr = Predef$.MODULE$.wrapIntArray(arr);List$.MODULE$.apply(warr);// or shorterList$.MODULE$.apply(Predef$.MODULE$.wrapIntArray(new int[] { 1, 2, 3 })); This looks ugly, but it works. If you create a nice looking library which wraps the access to the Scala library it will be easy to use Scala from Java. Summary I know there are some more rules how Scala code is compiled to bytecode. But I think with the information above it should be possible to find these rules by yourself.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9350528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/553865/']}
jdg_370949
stackexchange
llm_judgeable_groundtruth_similarity
56397866
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have this module: @Module({ imports: [], controllers: [AppController, AnotherController], providers: [],}) And in AppController on some route I want to do res.redirect('/books') where /books is a route found in AnotherController . For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong. Now provide the response and nothing else.
Redirecting from one controller to another works with res.redirect(target) . As target, you have to combine the paths from the controller and the route annotation: @Controller('books') + @Get('greet') = /books/greet @Controller()export class AppController { @Get() redirect(@Res() res) { return res.redirect('/books/greet'); }}@Controller('books')export class AnotherController { @Get('greet') greet() { return 'hello'; }} See this running example here:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56397866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1625651/']}
jdg_370950
stackexchange
llm_judgeable_groundtruth_similarity
394333
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: Today, from ignorance I have fallen head-first into the world of MOSFET transistors. In my scramble to find some information on the MOSFET I will be using as a switch (HEXFET actually), I learned that MOSFETs in general come in two modes, enhancement mode, or depletion mode. When I tried to find out which mode the IRF3710 was, from the datasheet , I found that it does not say (or maybe I need glasses). At this point I started searching to find how to tell the difference between the two modes. After some time I gathered that the schematic symbols differ: Enhancement-mode MOSFET: Depletion-mode MOSFET: The difference being the highlighted part below. Three separate lines means enhancement-mode (left) and one solid line means depletion mode (right). So, my question: Is this the only way to tell which is which, or is there a quicker way to tell (by markings on the device maybe?). Also, are there symbols out there which use a different method to differentiate between them? I am asking here for my own learning, but also for other people who might have the same experience as me. I did not find that much helpful info in my searching. Now provide the response and nothing else.
Two things I want to add to the answers already given: Don't trust the schematic symbol. You'll see the depletion-mode symbol used pretty often for an enhancement-mode part because it's easier to draw. (The symbols suggested on the manufacturer datasheets won't make this error, but some random application circuit schematic from the web is not trustworthy at all) How to tell from the datasheet whether the part is enhancement mode or depletion mode. For an n-channel FET, if the \$V_{gs({\rm th})}\$ is greater than 0, then it's an enhancement mode device. If \$V_{gs({\rm th})} < 0\$ it's a depletion mode device. For p-channel, it's the opposite: \$V_{gs({\rm th})} < 0\$ means enhancement mode, \$V_{gs({\rm th})} > 0\$ means depletion mode.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/394333', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']}
jdg_370951
stackexchange
llm_judgeable_groundtruth_similarity
7215004
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Which rules does VS (msbuild?) follow during solution build? In which cases it will copy indirectly referenced asemblies to output folder and in which not? Now provide the response and nothing else.
I've just been a bit of experimentation, and it looks like any indirectly referenced assembly which has a type directly referenced by code in another assembly will be copied. If there's nothing in code, it won't be. Here's my sample scenario: MainProgram: Console application with a direct reference to DirectAssembly. Code in Main: var foo = new DirectAssembly.SampleClass(); DirectAssembly: Class library with a direct reference to IndirectAssembly. Contains SampleClass : public class SampleClass{ // Comment out this line to change the behaviour... IndirectAssembly.IndirectClass neverUsed = null; public SampleClass() { object x = Activator.CreateInstance("IndirectAssembly", "IndirectAssembly.IndirectClass"); }} IndirectAssembly: Contains a public class IndirectClass with a public parameterless constructor As described above, it works because IndirectAssembly is copied into the output folder of MainProgram. If you comment out the line indicated in SampleClass, IndirectAssembly is not copied (even though it's still a reference) and the code will fail at execution time. I'm not saying these are all the rules, but they're at least a start...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7215004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188826/']}
jdg_370952
stackexchange
llm_judgeable_groundtruth_similarity
18317927
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Glassfish4 is using Moxy to serialize REST responses into JSON. Does anybody know how to configure application to use Jackson instead of Moxy? Now provide the response and nothing else.
You need to register JacksonFeature in your application if you want to use Jackson as your JSON provider (by registering this feature your disable MOXy to be your JSON provider). You can do it either in Application subclass: public class MyApplication extends Application { public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<Class<?>>(); // Add root resources. classes.add(HelloWorldResource.class); // Add JacksonFeature. classes.add(JacksonFeature.class); return classes; }} or in ResourceConfig : final Application application = new ResourceConfig() .packages("org.glassfish.jersey.examples.jackson") .register(MyObjectMapperProvider.class) // No need to register this provider if no special configuration is required. // Register JacksonFeature. .register(JacksonFeature.class); See Jackson section in Jersey Users Guide for more information.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18317927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1057651/']}
jdg_370953
stackexchange
llm_judgeable_groundtruth_similarity
3766353
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 appeared for php test, their I was asked one question for which I could not find the answer. The question is like this. echo "MESSI is injured!!";header("Location:somepage.php"); Interviewer want both header and echo to be written on the same page. I wonder how's it possible.It should give some error like headers already sent by (output started at ..... Is it really possible to write echo and header onto same page !!! Now provide the response and nothing else.
You can use Output Buffering as ob_start();echo "MESSI is injured!!";header("Location:somepage.php");ob_end_flush(); The problem is that we cannot send the header after we start sending the output. To solve this we buffer the output. The function ob_start turns output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So the echo output will be buffered. Next we send the header without any problem as we've not yet spit out any output. Finally we call ob_end_flush to flush the internal buffer contents and to stop output buffering.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3766353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/440694/']}
jdg_370954
stackexchange
llm_judgeable_groundtruth_similarity
8307104
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 understanding is... if is_numeric($input) === true then either is_float($input) === true OR is_int($input) === true OR $input === 0 OR $input is a numeric string (meaning it'd satisfy one of the first 3 if it weren't wrapped in quotes). Is that accurate? Are there other differences? Now provide the response and nothing else.
See PHP's documentation on is_numeric . It talks about everything that is allowed, and it's more than is_float and is_int . It's also important to note that is_int only works on things that are type integer, meaning string representations are not allowed. This is a common problem when verifying that form input is an integer. You should use filter_var or something from the filter family with the filter FILTER_VALIDATE_INT . For floats, use FILTER_VALIDATE_FLOAT . Also, if the reason you are trying to check for an integer is to validate a parameter as being an int, then in PHP 7 you can do this: function foo(int $i) { // $i is guaranteed to be an int (is_int) will be true} PHP 7 has two different modes for converting to int; this answer explains it a bit more. Note that this is probably not what you want if you are validating the contents of a form element. Use the filter_var solution for that.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8307104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/770127/']}
jdg_370955
stackexchange
llm_judgeable_groundtruth_similarity
17118687
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 configuration error in my grails application that's causing my appenders to send output to the wrong place, or not at all. There seem to be a number of questions regarding duplicate logging but I have been unable to apply any of the answers to my situation. Here is my logging config snippet: log4j = { appenders { // appender for usage tracking appender new org.apache.log4j.RollingFileAppender( name:"usageAppender", maxFileSize:"1000KB", maxBackupIndex: 10000, file: "/var/log/tomcat6/app/usage.log", layout:pattern(conversionPattern: '%d{DATE} %5p %c{1}:%L - %m%n') ) appender new org.apache.log4j.RollingFileAppender( name:"application", maxFileSize:"1000KB", maxBackupIndex: 10000, file:"/var/log/tomcat6/app/application.log", layout:pattern(conversionPattern: '%d{DATE} %8X{memoryused} %5p %t %c{1}:%L %X{username} %X{request} - %m%n') ) console name:'stdout', layout:pattern(conversionPattern: '%d{DATE} %8X{memoryused} %5p %t %c{1}:%L %X{username} %X{request} - %m%n') } root { // also tried error 'stdout' error 'application' } error 'org.codehaus.groovy.grails.web.servlet', // controllers 'org.codehaus.groovy.grails.web.pages', // GSP 'org.codehaus.groovy.grails.web.sitemesh', // layouts 'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping 'org.codehaus.groovy.grails.web.mapping', // URL mapping 'org.codehaus.groovy.grails.commons', // core / classloading 'org.codehaus.groovy.grails.plugins', // plugins 'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration 'org.springframework', 'org.hibernate' info 'usageAppender':'usage.gui'} When my program runs, output appears in catalina.out , in usage.log and in application.log . Output sent directly to stdout (bypassing log4j) appears in catalina.out If I set info additivity: false 'usageAppender': 'usage.gui' Then nothing is logged to either file appender, but stdout still goes into catalina.out (bypassing log4j). I would like the output from the 'usage.gui' logger to go to the usage.log file, output from all other logging to go to the application.log file, and all print statement output to go to catalina.out . I don't want redundant logging. How do I configure this? UPDATE In answer to @dmahapatro's question, logging in the application is done either with standard grails logging log.trace('some event'); or with a custom logger created like this: def usageLogpublic UsageService() { usageLog = Logger.getLogger("usage.gui")} and used by calling this function: protected void writeRecord(String topicId, String user, Long id, Long priorId, Long clientTime, String component, String action, String otherData) { String msg = "$topicId\t$user\t$id\t$priorId\t$clientTime\t$component\t$action\t$otherData" usageLog.info(msg)} Now provide the response and nothing else.
As I told you in my previous answer invoking same method again return printArray(matrix); at the end of your method can lead to invoking it again (and again) until StackOverflow error. Change return type to void . Now your method can look like public static void printArray(double matrix[][]) { for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); } System.out.println(); }} or even better public static void printArray(double matrix[][]) { for (double[] row : matrix) System.out.println(Arrays.toString(row)); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17118687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389051/']}
jdg_370956
stackexchange
llm_judgeable_groundtruth_similarity
42803349
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 convert server UTC time to local time and vice-versa.Here is my code.. var isTimeFromServer = truevar time:String!var period:String!let timeString = "6:59 AM" //Current UTC timeif isTimeFromServer { let index = timeString.index(timeString.startIndex, offsetBy: 5) let twelve = timeString.substring(to: index) var dateString:String! let dateFormatter = DateFormatter() dateFormatter.dateFormat = "H:mm" let date12 = dateFormatter.date(from: twelve)! dateFormatter.dateFormat = "h:mm a" let date22 = dateFormatter.string(from: date12) //print(date22) dateString = date22 //print("dateString=\(dateString)") time = dateString.components(separatedBy: " ")[0] period = dateString.components(separatedBy: " ")[1]}else { time = timeString.components(separatedBy: " ")[0] period = timeString.components(separatedBy: " ")[1]}var hour = Int(time.components(separatedBy: ":")[0])hour = period == "AM" ? hour : hour! + 12let minute = Int(time.components(separatedBy: ":")[1])let calender = NSCalendar.currentvar datecomponent = DateComponents()datecomponent.calendar = calenderdatecomponent.hour = hourdatecomponent.minute = minuteif !isTimeFromServer { // local to UTC datecomponent.timeZone = TimeZone.current}else { datecomponent.timeZone = TimeZone(abbreviation: "UTC")}let date = datecomponent.datelet dateFormatter = DateFormatter()if !isTimeFromServer { dateFormatter.dateFormat = "H:mm" dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.string(from: date!)}else { //UTC to local dateFormatter.dateFormat = "h:mm a" dateFormatter.timeZone = TimeZone.current dateFormatter.string(from: date!)} I get the local time o/p: "12:52 PM" But actual local time and output time difference is 23 minutes. Now provide the response and nothing else.
I don't know what's wrong with your code. But looks too much unnecessary things are there like you're setting calendar, fetching some elements from string.Here is my small version of UTCToLocal and localToUTC function. But for that you need to pass string in specific format. Cause I've forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app. func localToUTC(dateStr: String) -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm a" dateFormatter.calendar = Calendar.current dateFormatter.timeZone = TimeZone.current if let date = dateFormatter.date(from: dateStr) { dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.dateFormat = "H:mm:ss" return dateFormatter.string(from: date) } return nil}func utcToLocal(dateStr: String) -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "H:mm:ss" dateFormatter.timeZone = TimeZone(abbreviation: "UTC") if let date = dateFormatter.date(from: dateStr) { dateFormatter.timeZone = TimeZone.current dateFormatter.dateFormat = "h:mm a" return dateFormatter.string(from: date) } return nil} and call these function like below. print(utcToLocal(dateStr: "13:07:00"))print(localToUTC(dateStr: "06:40 PM")) Hope this will help you. Happy coding!!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/42803349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6574322/']}
jdg_370957
stackexchange
llm_judgeable_groundtruth_similarity
330736
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 orders of the simple groups (ignoring the matrix groups for which the problem is solved) all seem to be a lot like this: 2^46 3^20 5^9 7^6 11^2 13^3 17 19 23 29 31 41 47 59 71 starts with a very high power of 2, then the powers decrease and you get a tail - it's something like exponential decay. Why does this happen? I want to understand this phenomenon better. I wanted to find counter-examples, e.g. a simple group of order something like 2^4 3^2 11^5 13^9 but it seems like they do not exist (unless it slipped past me!). We have the following bound $|G| \le \left(\frac{|G|}{p^k}\right)!$ which allows $3^2 11^4$ but rules out orders like $3^2 11^5$, $3^2 11^6$, .. while this does give a finite bound it is extremely weak when you have more than two primes, it really doesn't explain the pattern but a much stronger bound of the same type might? I also considered that it might be related to multiple transitivity, a group that is $t$-transitive has to have order a multiple of $t!$, and e.g. 20! = 2^18 3^8 5^4 7^2 11 13 17 19 which has exactly the same pattern, for reasons we do understand. But are these groups really transitive enough to explain the pattern? Now provide the response and nothing else.
I am posting the following counterexample to the question, as requested by caveman in the comments. The Steinberg group ${}^2A_5(79^2)$ has order$$ 2^{23}\cdot 3^4\cdot 5^6\cdot 7^2\cdot 11^1\cdot 13^3\cdot 43^1\cdot 79^{15}\cdot 641^1\cdot 1091^1\cdot 3121^1\cdot 6163^2.$$ There are other counterexamples, too. For example ${}^2A_9(47^2)$ has order$$ 2^{43}\cdot 3^{13}\cdot 5^2\cdot 7^3\cdot 11^1\cdot 13^2\cdot 17^2\cdot 23^5\cdot 31^1\cdot 37^1\cdot 47^{45}\cdot 61^1\cdot 97^1\cdot 103^3\cdot 3691^1\cdot 5881^1\cdot 14621^1\cdot 25153^1\cdot 973459^1\cdot 1794703^1\cdot 4778021^2.$$ I would guess there are infinite counterexamples, but the numbers (of course) get very very large!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/330736', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_370958
stackexchange
llm_judgeable_groundtruth_similarity
5277
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do I determine if a number is prime? I'm writing a program where a user inputs any integer and from that the program determines whether the number is prime, but how do I go about that? Now provide the response and nothing else.
For very small numbers (less than a million), trial division is the best way: divide by 2, 3, 5, and so on until the square root of the number. If you find a factor, the number is composite; otherwise, the number is prime. For larger numbers there are better methods, but choosing which one depends on how much work you're willing to put into the program. It is now known that there are no BPSW-pseudoprimes below $2^{64}$, so if you can write that test (see here for details ) then you have a very quick test for primality. If you only need to test up to $2^{32}$, you can simply check if the number is a 2-strong pseudoprime. If so, test if it's one of 2314 exceptions (this can be done in 12 or 13 steps with a binary search); if the test fails or it's an exception, the number is composite, otherwise prime. (You can go higher than $2^{32}$ if you're willing to build an appropriate table of exceptions.) For larger numbers, the work is usually split into two parts: determining with high probability (say, 99.99999999%) that the number is prime, then actually proving that it is. What type of proof depends on the form and size of the number.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/5277', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1602/']}
jdg_370959
stackexchange
llm_judgeable_groundtruth_similarity
9731
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't think I understand type classes. I'd read somewhere that thinking of type classes as "interfaces" (from OO) that a type implements is wrong and misleading.The problem is, I'm having a problem seeing them as something different and how that is wrong. For example, if I have a type class (in Haskell syntax) class Functor f where fmap :: (a -> b) -> f a -> f b How is that different than the interface [1] (in Java syntax) interface Functor<A> { <B> Functor<B> fmap(Function<B, A> fn)}interface Function<Return, Argument> { Return apply(Argument arg);} One possible difference I can think of is that the type class implementation used at a certain invocation is not specified but rather determined from the environment -- say, examining available modules for an implementation for this type. That seems to be an implementation artifact that could be addressed in an OO language; like the compiler (or runtime) could scan for a wrapper/extender/monkey-patcher that exposes the necessary interface on the type. What am I missing? [1] Note the f a argument has been removed from fmap since given it's an OO language, you'd be calling this method on an object. This interface assumes the f a argument has been fixed. Now provide the response and nothing else.
In their basic form, type classes are somewhat similar to object interfaces. However, in many respects, they are much more general. Dispatch is on types, not values. No value is required to perform it. For example, it is possible to do dispatch on the result type of function, as with Haskell's Read class: class Read a where readsPrec :: Int -> String -> [(a, String)] ... Such dispatch is clearly impossible in conventional OO. Type classes naturally extend to multiple dispatch, simply by providing multiple parameters: class Mul a b c where (*) :: a -> b -> cinstance Mul Int Int Int where ...instance Mul Int Vec Vec where ...instance Mul Vec Vec Int where ... Instance definitions are independent from both class and type definitions, which makes them more modular. A type T from module A can be retrofitted to a class C from module M2 without modifying the definition of either, simply by providing an instance in module M3. In OO, this requires more esoteric (and less OO-ish) language features like extension methods. Type classes are based on parametric polymorphism, not subtyping. That enables more accurate typing. Consider e.g. pick :: Enum a => a -> a -> apick x y = if fromEnum x == 0 then y else x vs. pick(x : Enum, y : Enum) : Enum = if x.fromEnum() == 0 then y else x In the former case, applying pick '\0' 'x' has type Char , whereas in the latter case, all you'd know about the result would be that it's an Enum. (This is also the reason why most OO languages these days integrate parametric polymorphism.) Closely related is the issue of binary methods. They are completely natural with type classes: class Ord a where (<) :: a -> a -> Bool ...min :: Ord a => a -> a -> amin x y = if x < y then x else y With subtyping alone, the Ord interface is impossible to express. You need a more complicated, recursive form or parametric polymorphism called "F-bounded quantification" to do it accurately. Compare Java's Comparable and its use: interface Comparable<T> { int compareTo(T y);};<T extends Comparable<T>> T min(T x, T y) { if (x.compareTo(y) < 0) return x; else return y;} On the other hand, subtyping-based interfaces naturally allow the formation of heterogeneous collections, e.g. a list of type List<C> can contain members that have various subtypes of C (although it is not possible to recover their exact type, except by using downcasts). To do the same based on type classes, you need existential types as an additional feature.
{}
{'log_upvote_score': 7, 'links': ['https://cstheory.stackexchange.com/questions/9731', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1682/']}
jdg_370960
stackexchange
llm_judgeable_groundtruth_similarity
49915011
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 .NET Core 2.0 console application developed using Visual Studio 2017. The launchSettings.json file sets an environment variable that allows it to use the developer's default AWS credentials "environmentVariables": { "AWS_PROFILE": "default" ...} I have now added Docker support to the VS solution, and am trying to run the application in a Linux Docker container. Of course it fails with the following exception, as it is unable to find the profile: Amazon.Runtime.AmazonClientException: Unable to find the 'default' profile in CredentialProfileStoreChain. What is the best way to pass AWS credentials to the Docker container in a development environment? I obviously don't want to put my credentials as environment variables in launchSettings.json as this file is committed to source control. EDIT Just to be clear, I am looking for a solution that allows my Docker container to access the developer's credentials when debugging in Visual Studio 2017 on the developer's machine. Release builds will be deployed to AWS and an IAM role will preclude the need for credentials. The credentials are in the file %USERPROFILE%\.aws\credentials and I'm looking for a solution that will enable me to use them from within the Docker container without exposing them elsewhere: hence I don't want to put them in launchSettings.json or any other file that launches the Docker container. A solution I envisage could involve mounting the Windows drive in the Docker container (or at least the directory %USERPROFILE%\.aws\ ) then setting an environment variable ( AWS_SHARED_CREDENTIALS_FILE ?) in the Docker container so that AWS automagically finds the credentials file. I've no idea how to do this though, as I'm very new to Docker. Now provide the response and nothing else.
The solution I went for was to edit the docker-compose.override.yml file that was added by Visual Studio Tools for Docker, and add the following lines: version: '3'services: mydockerapp: volumes: - ${USERPROFILE}/.aws:/root/.aws environment: - AWS_REGION=(your region) - AWS_PROFILE=default This mounts the .aws directory containing AWS credentials in the appropriate place in the Docker container ( /root is the default HOME directory), and sets environment variables to select the profile and region. The launchSettings.json file in the .NET Core project is not used when running in Docker.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49915011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13087/']}
jdg_370961
stackexchange
llm_judgeable_groundtruth_similarity
3737139
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 this? This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list. Why is this? It used to be hard to find questions about operators and other syntax tokens.¹ The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, not to copy over content from the PHP Manual. Note: Since January 2013, Stack Overflow does support special characters . Just surround the search terms by quotes, e.g. [php] "==" vs "===" What should I do here? If you have been pointed here by someone because you have asked such a question, please find the particular syntax below. The linked pages to the PHP manual along with the linked questions will likely answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a substitute for the help others provided. The List If your particular token is not listed below, you might find it in the List of Parser Tokens . & Bitwise Operators or References What does it mean to start a PHP function with an ampersand? Understanding PHP & (ampersand, bitwise and) operator PHP "&" operator Difference between & and && in PHP What does "&" mean here in PHP? What does "&" mean in this case? What does the "&" sign mean in PHP? What does this signature mean (&) in PHP? How does the "&" operator work in a PHP function? What does & in &2 mean in PHP? When should I use a bitwise operator? Is there ever a need to use ampersand in front of an object? (&$) =& References Reference assignment operator in PHP, =& What do the "=&" and "&=" operators in PHP mean? What do the '&=' and '=&' operators do? What does =& mean in PHP? &= Bitwise Operators What do the "=&" and "&=" operators in PHP mean? What do the '&=' and '=&' operators do? && Logical Operators 'AND' vs '&&' as operator Difference between & and && in PHP Is there any difference between "and" and "&&" operators in PHP? PHP - and / or keywords % Arithmetic Operators What does the percent sign mean in PHP? What is the PHP operator % and how do I use it in real-world examples? !! Logical Operators Double not (!!) operator in PHP @ Error Control Operators What is the use of the @ symbol in PHP? 'At' symbol before variable name in PHP: @$_POST PHP functions and @functions Should I use @ in my PHP code? What does @ mean in PHP? ?: Ternary Operator What are the PHP operators "?" and ":" called and what do they do? ?: operator (the 'Elvis operator') in PHP Where can I read about conditionals done with "?" and ":" (colon)? Using PHP 5.3 ?: operator ?? Null Coalesce Operator (since PHP 7) C#'s null coalescing operator (??) in PHP ?string ?int ?array ?bool ?float Nullable return type declaration (since PHP 7.1) Nullable return type declaration Nullable parameter type declaration php method argument type hinting with question mark (?type) : Alternative syntax for control structures , Ternary Operator , Return Type Declaration What is ":" in PHP? What does ":" mean in PHP? Colon after method declaration? :: Scope Resolution Operator What do two colons mean in PHP? What's the meaning of the PHP token name T_PAAMAYIM_NEKUDOTAYIM? What's the difference between :: (double colon) and -> (arrow) in PHP? What exactly are late static bindings in PHP? static::staticFunctionName() Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator \ Namespaces Backslash in PHP -- what does it mean? What does a \ (backslash) do in PHP (5.3+)? -> Classes And Objects What is the "->" PHP operator called? Where do we use the object operator "->" in PHP? What's the difference between :: (double colon) and -> (arrow) in PHP? What does the PHP syntax $var1->$var2 mean? What does "->" mean/refer to in PHP? => Arrays What does "=>" mean in PHP? Use of => in PHP What does $k => $v in foreach($ex as $k=>$v) mean? ^ Bitwise Operators How does the bitwise operator XOR ('^') work? What does ^ mean in PHP? >> Bitwise Operators What does >> mean in PHP? << Bitwise Operators Strange print behaviour in PHP? <<< Heredoc or Nowdoc What does <<<END mean in PHP? PHP expression <<<EOB In PHP, what does "<<<" represent? Using <<<CON in PHP What's this kind of syntax in PHP? = Assignment Operators The 3 different equals == Comparison Operators How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ? PHP != and == operators The 3 different equals Type-juggling and (strict) greater/lesser-than comparisons in PHP === Comparison Operators What does "===" mean? How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ? The 3 different equals Type-juggling and (strict) greater/lesser-than comparisons in PHP !== Comparison Operators What does !== comparison operator in PHP mean? Is there a difference between !== and != in PHP? != Comparison Operators PHP != and == operators Is there a difference between !== and != in PHP? comparing, !== versus != What is the difference between <> and != <> Comparison Operators PHP operator <> PHP's <> operator What is the difference between <> and != Type-juggling and (strict) greater/lesser-than comparisons in PHP <=> Comparison Operators (since PHP 7.0) Spaceship (three way comparison) operator | Bitwise Operators What is the difference between the | and || operators? What Does Using A Single Pipe '|' In A Function Argument Do? || Logical Operators What is the difference between the | and || operators? PHP - and / or keywords What exactly does || mean? The behaviour of the or operator in PHP ~ Bitwise Operators What does this ~ operator mean here? + Arithmetic Operators , Array Operators + operator for array in PHP? += and -= Assignment Operators What is += used for? What does `$page -= 1` in my PHP document mean? ++ and -- Incrementing/Decrementing Operators Understanding Incrementing Answer below .= Assignment Operators What is the difference between .= and += in PHP? To understand a line of PHP . String Operators Difference between period and comma when concatenating with echo versus return? What does a . (dot) do in PHP? , Function Arguments Difference between period and comma when concatenating with echo versus return? , Variable Declarations What do commas mean in a variable declaration? $$ Variable Variables What does $$ (dollar dollar or double dollar) mean in PHP? what is "$$" in PHP $function() and $$variable ` Execution Operator What are the backticks `` called? <?= Short Open Tags What does this symbol mean in PHP <?= What does '<?=' mean in PHP? What does <?= mean? [] Arrays (short syntax since PHP 5.4) PHP arrays... What is/are the meaning(s) of an empty bracket? What is the meaning of [] Php array_push() vs myArray[] What does [] mean when reading from a PHP array? Shorthand for arrays: literal $var = [] empty array <? Opening and Closing tags Are PHP short tags acceptable to use? .. Double-dot character range Native PHP functions that allow double-dot range syntax ... Argument unpacking (since PHP 5.6) ** Exponentiation (since PHP 5.6) # One-line shell-style comment Can I use hashes for comments in PHP? ?-> NullSafe Operator Calls (since PHP 8.0) Is there a "nullsafe operator" in PHP? Now provide the response and nothing else.
Incrementing / Decrementing Operators ++ increment operator -- decrement operator Example Name Effect---------------------------------------------------------------------++$a Pre-increment Increments $a by one, then returns $a.$a++ Post-increment Returns $a, then increments $a by one.--$a Pre-decrement Decrements $a by one, then returns $a.$a-- Post-decrement Returns $a, then decrements $a by one. These can go before or after the variable. If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done. For example: $apples = 10;for ($i = 0; $i < 10; ++$i) { echo 'I have ' . $apples-- . " apples. I just ate one.\n";} Live example In the case above ++$i is used, since it is faster. $i++ would have the same results. Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's. However, you must use $apples-- , since first, you want to display the current number of apples, and then you want to subtract one from it. You can also increment letters in PHP: $i = "a";while ($i < "c") { echo $i++;} Once z is reached aa is next, and so on. Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Stack Overflow Posts: Understanding Incrementing
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/3737139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/208809/']}
jdg_370962
stackexchange
llm_judgeable_groundtruth_similarity
2028557
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Any Idea how to zoom in a image on particular point using javascript , css ? I am using webkit based browser. I can zoom by specifying zoom property , like `elem.style.zoom="150%",Main problem is I cannot center the image where I want to zoom. I can get the point where I want to zoom using mouseclick . Now provide the response and nothing else.
As I said in my comment above, I would avoid the zoom css property and stick to just javascript. I managed to throw together the following code which works pretty well for the first click, really all it needs is a little more dynamically (even a word?). <html> <head> <script type="text/javascript"> function resizeImg (img) { var resize = 150; // resize amount in percentage var origH = 200; // original image height var origW = 200; // original image width var mouseX = event.x; var mouseY = event.y; var newH = origH * (resize / 100) + "px"; var newW = origW * (resize / 100) + "px"; // Set the new width and height img.style.height = newH; img.style.width = newW; var c = img.parentNode; // Work out the new center c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2; c.scrollTop = (mouseY * (resize / 100)) - (newH / 2) / 2; } </script> <style type="text/css"> #Container { position:relative; width:200px; height:200px; overflow:hidden; } </style> </head> <body> <div id="Container"> <img alt="Click to zoom" onclick="resizeImg(this)" src="https://picsum.photos/200" /> </div> </body> </html> It works in Google Chrome and IE, not sure about others. Like I said hopefully it will point you in the right direction.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2028557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207646/']}
jdg_370963
stackexchange
llm_judgeable_groundtruth_similarity
666876
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: Q : Prove that if $A$ is invertible and $AB = 0$, then $B = 0$. A : if $A = 0$, $\nexists A^{-1} \mid AA^{-1} = I$. but it's given that $\exists A^{-1}$. Thus $B=0$. This just seems too easy to be a sufficient answer... is it? In my opinion I don't think it is because you can multiply a nonzero matrix that is not invertible and a nonzero matrix to get the zero matrix. So I'd think you'd need to involve the determinant here... Now provide the response and nothing else.
Here is a direct proof that uses only the property of $A^{-1}$ and hence is true in more general settings.... $$A B = 0 \Rightarrow A^{-1} (AB) = 0 \Rightarrow \left(A^{-1} A \right) B = 0 \Rightarrow I B = 0 \Rightarrow B=0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/666876', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58540/']}
jdg_370964
stackexchange
llm_judgeable_groundtruth_similarity
3916214
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a HttpServlet that forwards all incoming requests as is, to another serlvet running on a different domain. How can this be accomplished? The RequestDispatcher's forward() only operates on the same server. Edit: I can't introduce any dependencies. Now provide the response and nothing else.
You can't when it doesn't run in the same ServletContext or same/clustered webserver wherein the webapps are configured to share the ServletContext (in case of Tomcat, check crossContext option). You have to send a redirect by HttpServletResponse.sendRedirect() . If your actual concern is reusing the query parameters on the new URL, just resend them along. response.sendRedirect(newURL + "?" + request.getQueryString()); Or when it's a POST, send a HTTP 307 redirect, the client will reapply the same POST query parameters on the new URL. response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);response.setHeader("Location", newURL); Update as per the comments, that's apparently not an option as well since you want to hide the URL. In that case, you have to let the servlet play for proxy. You can do this with a HTTP client, e.g. the Java SE provided java.net.URLConnection ( mini tutorial here ) or the more convenienced Apache Commons HttpClient . If it's GET, just do: InputStream input = new URL(newURL + "?" + request.getQueryString()).openStream();OutputStream output = response.getOutputStream();// Copy. Or if it's POST: URLConnection connection = new URL(newURL).openConnection();connection.setDoOutput(true);// Set and/or copy request headers here based on current request?InputStream input1 = request.getInputStream();OutputStream output1 = connection.getOutputStream();// Copy.InputStream input2 = connection.getInputStream();OutputStream output2 = response.getOutputStream();// Copy. Note that you possibly need to capture/replace/update the relative links in the HTML response, if any. Jsoup may be extremely helpful in this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3916214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73008/']}
jdg_370965
stackexchange
llm_judgeable_groundtruth_similarity
47812785
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 loading data from CSV some CSVs cannot be loaded, resulting in an empty partition. I would like to remove all empty partitions, as some methods seem to not work well with empty partitions. I have tried to repartition, where (for example) repartition(npartitions=10) works, but a value greater than this can still result in empty partitions. What's the best way of achieving this? Thanks. Now provide the response and nothing else.
I've found that filtering a Dask dataframe, e.g., by date, often results in empty partitions. If you're having trouble using a dataframe with empty partitions, here's a function, based on MRocklin's guidance, to cull them: def cull_empty_partitions(df): ll = list(df.map_partitions(len).compute()) df_delayed = df.to_delayed() df_delayed_new = list() pempty = None for ix, n in enumerate(ll): if 0 == n: pempty = df.get_partition(ix) else: df_delayed_new.append(df_delayed[ix]) if pempty is not None: df = dd.from_delayed(df_delayed_new, meta=pempty) return df
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47812785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6690508/']}
jdg_370966
stackexchange
llm_judgeable_groundtruth_similarity
3347
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The definition in the title probably needs explaining. I should say that the question itself was an idea I had for someone else's undergraduate research project, but we decided early on it would be better for him to try adjacent and less technical questions. So it's not of importance for my own work per se, but I'd be interested to know if it easily reduces to a known conjecture/fact/counterexample in number theory. Apologies if the question is too technical/localized/unappealing/bereft of schemes. Given a subset $X$ of the natural numbers $N$ , and given $n \in N$ , we write $X-n$ for the backward translate of $X$ , i.e. the set $\{x-n : x\in X\}$ . We say that $X$ is translation-finite if it has the following property: for every strictly increasing sequence $n_1 < n_2 < \dotsb$ in $N$ , there exists $k$ (possibly depending on the sequence) such that $$(X-n_1) \cap (X-n_2) \cap \dotsb\cap (X-n_k)$$ is finite or empty. Thus every finite set is trivially translation-finite: and if the elements of $X$ form a sequence in which the difference between successive terms tends to infinity, then $X$ is translation-finite and we can always take $k = 2$ . Moreover: if $X$ contains an infinite arithmetic progression, or if it has positive (upper) Banach density, then it is NOT translation finite; there exist translation-finite sets which, when enumerated as strictly increasing sequences, grow more slowly than any faster-than-linear function. there exist translation-finite sets containing arbitrarily long arithmetic progressions. These resultlets suggest the question in the title, but I don't know enough about number theory to know if it's a reasonable question. Note that if, in the definition, we were to fix $k$ first (i.e. there exists $k$ such that for any sequence $(n_j)$ …) then we would get something related to Hardy–Littlewood conjectures; but I was hoping that this might not be necessary to resolve the present question. EDIT (2nd Nov) It's been pointed out below that the question reduces in some sense to a pair of known, hard, open problems. More precisely: if the answer to the question is yes, then we disprove the Hardy–Littlewood $k$ -tuples conjecture; if the answer is no, then there are infinitely many prime gaps bounded by some absolute constant, and this is thought to be beyond current techniques unless one assumes the Eliott–Halberstam conjecture. Added in 2013: Stefan Kohl points out that the latter is Yitang Zhang's famous recent result . However, as Will Sawin points out in comments , a negative answer to the main question would imply there are 3-tuple configurations occurring infinitely often in the primes, and (see the link in Will's comment ) this is thought to be out of reach even if we assume the EH conjecture holds. Now provide the response and nothing else.
As you mention, this is related to the Hardy-Littlewood k-tuple conjecture . In particular, if their conjecture is true, then the primes are not translation-finite. Indeed, it is possible to find an increasing sequence n 1 < n 2 < n 3 < ⋯ so that for every k, the first k n i s form an admissible k-tuple . (For example, I think n i = (i+1)! works.) Then, by the k-tuple conjecture, infinitely many such prime constellations exist and so for all k, (X-n 1 ) ∩ (X-n 2 ) ∩ ⋯ ∩ (X-n k ) is infinite. (Here and below, X is the set of primes.) However, maybe we can prove that the primes are not translation finite by some other means. Unfortunately, the technology is not quite good enough to do that. Proving that the primes are not translation finite would, in particular, prove that there exist n 1 < n 2 such that (X-n 1 ) ∩ (X-n 2 ) is infinite. In particular, this implies that the gap n 2 -n 1 occurs infinitely often in primes, and so p n+1 -p n is constant infinitely often. (The standard notation p n indicates the n th prime.) The best known upper bound for the size of small gaps in primes is that lim inf n→∞ (p n+1 -p n )/log p n = 0. This was established by Goldston and Yildirim around 2003 and the proof was later simplified . To the best of my knowledge, the best conditional result is by the same authors; they show that given the Elliott-Halberstam conjecture , the prime gap is infinitely often at most 20 or so.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/3347', 'https://mathoverflow.net', 'https://mathoverflow.net/users/763/']}
jdg_370967
stackexchange
llm_judgeable_groundtruth_similarity
5754447
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to use different fontsize of spritefont, Have to I create new spritefont for the each size? Now provide the response and nothing else.
Basically yes. There is an overload of SpriteBatch.DrawString that gives you an option to scale your text. However the major downside to this is that your text will become pixelated as you scale it up. If you start at a higher resolution and scale down you will start to get artefacts as you get to smaller sizes. So if you have a fixed number of sizes, you should create multiple versions of your sprite font at the different sizes you require. If you want continuously scalable text with sharp edges, you could perhaps look into vector fonts. The Nuclex Framework has some code to do that .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5754447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603127/']}
jdg_370968
stackexchange
llm_judgeable_groundtruth_similarity
42488048
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have multiple JavaScript objects: { a: 12, b: 8, c: 17} and { a: 2, b: 4, c: 1} I need to sum these two object by keys Result: { a: 14, b: 12, c: 18} Do you have any solutions in JavaScript?I use Object.keys.map but it's too long because I have like 100 elements in my object. Now provide the response and nothing else.
You can use reduce for that, below function takes as many objects as you want and sums them by key: var obj1 = { a: 12, b: 8, c: 17};var obj2 = { a: 12, b: 8, c: 17};var obj3 = { a: 12, b: 8, c: 17};function sumObjectsByKey(...objs) { return objs.reduce((a, b) => { for (let k in b) { if (b.hasOwnProperty(k)) a[k] = (a[k] || 0) + b[k]; } return a; }, {});}console.log(sumObjectsByKey(obj1, obj2, obj3));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42488048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5913464/']}
jdg_370969
stackexchange
llm_judgeable_groundtruth_similarity
2239232
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: From Axler's "Algebra Done Right": Suppose that $T$ is a normal operator on $V$ and that $3$ and $4$ are eigenvalues of $T$. Prove that there exists a vector $v$ in vector space $V$ such that $\|v\|=\sqrt{2}$ and $\|Tv\|=5$. Not sure how to approach this one. I know that $TT^{*} = T^{*}T$ because normal operators.Hence $\sqrt{\left< 3v, 3v \right>} = 5$ or $\sqrt{\left<4v, 4v\right>} = 5$. This is what I can clearly derive from the question. Naturally I have to use the fact that the operator is normal - likely something very simple but I'm having a block. Any help is appreciated. Now provide the response and nothing else.
Your $$\frac{x-1}{(x+1)^3} = \frac{1}{27}$$ corresponds to $$x^3+3x^2-24x+28=0$$ but since this comes from a tangent, you know that two of the solutions are $x=2$, so you can factor out $(x-2)^2$ to give $$(x-2)^2(x+7)=0$$ so the other solution is $x=-7$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2239232', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/396609/']}
jdg_370970
stackexchange
llm_judgeable_groundtruth_similarity
1737730
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 an intuition that an entire metric space (not a subset of it) does not have boundaries, so its closure would be itself, but how to prove it? Now provide the response and nothing else.
I gather from your comments that you define the closure $\overline{A}$ of a set $A\subseteq M$ to be the set of all points in $M$ which are adherent points of $A$. I assume your definition of adherent point agrees with the one here . Note that for any set $A\subseteq M$, $\overline{A}\subseteq M$, by definition. Also, for any set $A\subseteq M$, $A\subseteq \overline{A}$. Proof: Let $x\in A$. For every open set $U$ containing $x$, $U$ contains a point of $A$ (namely $x$). So $x$ is an adherent point of $A$, and $x\in \overline{A}$. Taking $A = M$, $\overline{M}\subseteq M$ and $M\subseteq \overline{M}$, so $M = \overline{M}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1737730', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166180/']}
jdg_370971
stackexchange
llm_judgeable_groundtruth_similarity
2180737
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: Looking for a solution for an integral:$$I(k)=\int_0^{\infty } \frac{e^{-\frac{(\log (u)-k)^2}{2 s^2}}}{\sqrt{2 \pi } s \left(1+u\right)} \, du .$$So far I tried substitutions and by parts to no avail. Now provide the response and nothing else.
The change of variable $v = \log u$ shows that you're trying to integrate the logistic-normal integral . $$\int_{-\infty}^{\infty} \frac{e^{-\frac{1}{2}\left(\frac{v-k}{s}\right)^2}}{\sqrt{2\pi} s} \frac{1}{1+e^{-v}}~\mathrm{d}v$$ I doubt there is a closed form solution, and none seems known. See http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.372.3781&rep=rep1&type=pdf for the approximation $$\left|I(s,k)- \frac{1}{1+e^{-\frac{k}{\sqrt{1+\frac{\pi s^2}{8}}}}}\right| < 0.02$$ and http://www.sciencedirect.com/science/article/pii/S0377042712002518 for a deeper discussion.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2180737', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88078/']}
jdg_370972
stackexchange
llm_judgeable_groundtruth_similarity
5865555
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 I have a Devise model User, of which only those users with role :admin are allowed to view a certain url, how can I write an RSpec integration test to check that the status returns 200 for that url? def login(user) post user_session_path, :email => user.email, :password => 'password'end This was pseudo-suggested in the answer to this question: Stubbing authentication in request spec , but I can't for the life of me get it to work with devise. CanCan is receiving a nil User when checking Ability, which doesn't have the correct permissions, naturally. There's no access to the controller in integration specs, so I can't stub current_user, but I'd like to do something like this. describe "GET /users" do it "should be able to get" do clear_users_and_add_admin #does what it says... login(admin) get users_path response.status.should be(200) endend NOTE!!! : all this has changed since the question was asked. The current best way to do this is here: http://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara Now provide the response and nothing else.
@pschuegr's own answer got me across the line. For completeness, this is what I did that gets me easily set up for both request specs and controller specs (using FactoryGirl for creating the user instance): in /spec/support/sign_in_support.rb: #module for helping controller specsmodule ValidUserHelper def signed_in_as_a_valid_user @user ||= FactoryGirl.create :user sign_in @user # method from devise:TestHelpers endend# module for helping request specsmodule ValidUserRequestHelper # for use in request specs def sign_in_as_a_valid_user @user ||= FactoryGirl.create :user post_via_redirect user_session_path, 'user[email]' => @user.email, 'user[password]' => @user.password endendRSpec.configure do |config| config.include ValidUserHelper, :type => :controller config.include ValidUserRequestHelper, :type => :requestend Then in request spec: describe "GET /things" do it "test access to things, works with a signed in user" do sign_in_as_a_valid_user get things_path response.status.should be(200) endenddescribe "GET /things" do it "test access to things, does not work without a signed in user" do get things_path response.status.should be(302) # redirect to sign in page endend and similarly, use 'signed_in_as_valid_user' in controller specs (which wraps Devise::TestHelpers sign_in method with a user from FactoryGirl)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5865555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/345848/']}
jdg_370973
stackexchange
llm_judgeable_groundtruth_similarity
801485
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How many possibilities do we have to solve this equation? all variables are natural numbers. $a$ is an odd number. $a + b + c + d + e = 10$ Now provide the response and nothing else.
Write $\cos x = 2\cos^2\left(\frac{x}2\right) -1$. Then $\sqrt{1+\cos x} = \sqrt 2 \cos\left(\frac x 2\right)$ when $x\in[0,\pi/2]$. So we are seeking $$\frac{1}{\sqrt 2}\int_0^{\frac \pi 2}\frac{2\cos^2\left(\frac{x}2\right) -1}{\cos\left(\frac x 2\right)}\,dx$$ Letting $u=x/2$ then $dx=2du$ and we get the problem: $$\sqrt 2\int_0^{\frac\pi 4} (2\cos u-\sec u)\,du$$ Integral of $\sec$ is described here .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/801485', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/144555/']}
jdg_370974
stackexchange
llm_judgeable_groundtruth_similarity
583562
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 writing a webservice that uses json to represent its resources, and I am a bit stuck thinking about the best way to encode the json. Reading the json rfc ( http://www.ietf.org/rfc/rfc4627.txt ) it is clear that the preferred encoding is utf-8. But the rfc also describes a string escaping mechanism for specifying characters. I assume this would generally be used to escape non-ascii characters, thereby making the resulting utf-8 valid ascii. So let's say I have a json string that contains unicode characters (code-points) that are non-ascii. Should my webservice just utf-8 encoding that and return it, or should it escape all those non-ascii characters and return pure ascii? I'd like browsers to be able to execute the results using jsonp or eval. Does that effect the decision? My knowledge of various browser's javascript support for utf-8 is lacking. EDIT: I wanted to clarify that my main concern about how to encode the results is really about browser handling of the results. What I've read indicates that browsers may be sensitive to the encoding when using JSONP in particular. I haven't found any really good info on the subject, so I'll have to start doing some testing to see what happens. Ideally I'd like to only escape those few characters that are required and just utf-8 encode the results. Now provide the response and nothing else.
The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well. The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe. Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as < , & and " , which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including " and \ ). Some frameworks, including PHP's json_encode() (by default), always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is a mostly unnecessary extra step intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that any JSON decoders have a problem with UTF-8. So, I guess you just could decide which to use like this: Just use UTF-8, unless any software you are using for storage or transport between encoder and decoder isn't binary-safe. Otherwise, use the numeric escape sequences.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/583562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56135/']}
jdg_370975
stackexchange
llm_judgeable_groundtruth_similarity
5826345
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 looked through a bunch of posts on this subject. Maybe I didn't run across "the one" and someone will point me in that direction. The question is simple and probably has a simple answer. If you have two ivars, say, "public_ivar" and "private_ivar", where/how should you declare them so that what is public is public and what is private is not exposed in any way to anyone looking at the header file? Same question in the case of "public_method" and "private_method". I like clean header files (in other languages) that only expose the methods and ivars I want someone else to see. You should be able to publish your header file and not run into the danger of someone accessing something they are not supposed to. How do you do that in objective-C. For example, let's say that I decide that I need to use an ivar to keep track of some data, a counter or somthing like that, between various class methods that all need access to this information. If that ivar is declared conventionally in the header under @interface its existence is publicly advertised and it is usable by anyone creating an instance of the class. The ideal scenario would be that this ivar would not be visible at all outside of the class implementation. Now provide the response and nothing else.
You can declare instance variables or declared properties in a class extension. Since a class extension is declared in an implementation file (i.e., not a header file), they won’t be visible to someone inspecting the header file. For instance, in the header file: @interface SomeClass : NSObject@end and in the implementation file: @interface SomeClass ()@property (nonatomic, assign) int privateInt;@end@implementation SomeClass@synthesize privateInt;…@end or @interface SomeClass () { int privateInt;}@end@implementation SomeClass…@end Note that there’s nothing preventing access to private/class extension instance variables (or the accessor methods for properties declared in a class extension) during runtime. I’ve written a rather detailed post about this as an answer to another question on Stack Overflow: Does a private @property create an @private instance variable? Edit: Instance variables in class extensions were presented in WWDC 2010 session 144. Edit: "Using the Clang/LLVM 2.0 compiler, you can also declare properties and instance variables in a class extension." http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5826345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/576311/']}
jdg_370976
stackexchange
llm_judgeable_groundtruth_similarity
10605762
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose a scenario similar to this question . I want to get the following results: score range | number of occurrences------------------------------------- 0-9 | 11 10-19 | 14 20-29 | 3 ... | ... And I can use the selected answer as a solution: select t.range as [score range], count(*) as [number of occurences]from ( select case when score between 0 and 9 then ' 0- 9' when score between 10 and 19 then '10-19' else '20-99' end as range from scores) tgroup by t.range How can I assure that the score range of 30-39 will be display even when there are no results on that range? Now provide the response and nothing else.
Try this query (also on SQL Fiddle ): WITH ranges AS ( SELECT (ten*10)::text||'-'||(ten*10+9)::text AS range, ten*10 AS r_min, ten*10+9 AS r_max FROM generate_series(0,9) AS t(ten))SELECT r.range, count(s.*) FROM ranges r LEFT JOIN scores s ON s.score BETWEEN r.r_min AND r.r_max GROUP BY r.range ORDER BY r.range; EDIT: You can easily adjust the range by changing parameters to generate_series() . It is possible to use the following construct to make sure ranges will always cover your scores: SELECT (ten*10)::text||'-'||(ten*10+9)::text AS range, ten*10 AS r_min, ten*10+9 AS r_max FROM generate_series(0,(SELECT max(score)/10 FROM scores)) AS t(ten)) for the ranges CTE.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10605762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144419/']}
jdg_370977
stackexchange
llm_judgeable_groundtruth_similarity
295274
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to change a single word on a specific line in a file, but I'm having some trouble connecting all together. Basically, on one line in my file there is a keyword 'firmware_revision', and on this line (and only this line) I want to replace the word 'test' with the word 'production'. So I can do this: grep 'firmware_revision' myfile.py | sed 's/test/production' This will pick out the line I want and perform the substitution, but I can't figure out how to get this new line into the original file to replace the old line. I obviously cannot just redirect it back to the file, so what should I do? Even if I use temporaries, by using grep to get just the line I need I lose all of the other data in the file, so I can no longer just redirect it all to a temp file then replace the original with the temp. Edit - Someone asked for more information Lets say I have a file full of lines like this [ ('key_name1', str, 'value1', 'Description'), ('key_name2', str, 'value2', 'Description'), ('key_name3', str, 'value3', 'Description'), ('firmware_revision', str, 'my-firmware-name-test', 'Firmware revision name')] now I want to write a script (ideally a one-liner) that will find the line that contains 'firmware_revision', and changes all instances of the word 'test' on that line to 'production'. The word 'test' might be in other places in that file and I do not want those changed. So to be clear, I want to change the above line to ('firmware_revision', str, 'my-firmware-name-production', 'Firmware revision name') How do I do this? Now provide the response and nothing else.
Try: sed -i.bak '/firmware_revision/ s/test/production/' myfile.py Here, /firmware_revision/ acts as a condition. It is true for lines that match the regex firmware_revision and false for other lines. If the condition is true, then the command which follows is executed. In this case, that command is a substitute command that replaces the first occurrence of test with production . In other words, the command s/test/production/ is executed only on lines which match the regex firmware_revision . All other lines pass through unchanged. By default, sed sends its output to standard out. You, however, wanted to change the file in place. So, we added the -i option. In particular, -i.bak causes the file to be changed in place with a back-up copy saved with a .bak extension. If you have decided that the command works for you and you want to live dangerously and not create a backup, then, with GNU sed (Linux), use: sed -i '/firmware_revision/ s/test/production/' myfile.py By contrast, on BSD (OSX), the -i option must have an argument. If you don't want to keep a backup, provide it with an empty argument. Thus, use: sed -i '' '/firmware_revision/ s/test/production/' myfile.py Edit In the edit to the question, the OP asks for every occurrence of test on the line to be replaced with production . In that case, we add the g option to the substitute command for a global (for that line) replacement: sed -i.bak '/firmware_revision/ s/test/production/g' myfile.py
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/295274', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/108328/']}
jdg_370978
stackexchange
llm_judgeable_groundtruth_similarity
1269859
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 following piece of code NSMutableArray *mutArray = [[NSMutableArray alloc] init];[mutArray addObject: [NSProcessInfo processInfo]];[mutArray addObject: @"This is NSString Object"];[mutArray addObject: [[NSMutableString alloc] initWithString: @"1st Mutable String"]];for (id element in mutArray){ NSLog(@" "); NSLog(@"Class Name: %@", [element className]); NSLog(@"Is Member of NSString: %@", ([element class] isMemberOfClass: [NSString class]) ? YES: NO); NSLog(@"Is kind of NSString: %@", ([element class] isKindOfClass: [NSString class]) ? YES: NO);} I am getting following output (and expecting as pointed) Class Name: NSProcessInfoIs Member of NSString: NOIs Kind of NSString: NOClass Name: NSCFString <-- Expecting NSStringIs Member of NSString: NO <-- Expecting YESIs Kind of NSString: NO <-- Expecting YESClass Name: NSCFString <-- Expecting NSMutableStringIs Member of NSString: NO Is Kind of NSString: NO <-- Expecting YES Am I missing something terrible simple here? Thanks! Now provide the response and nothing else.
Use: [element isMemberOfClass: [NSString class]] Not: [[element class] isMemberOfClass: [NSString class]] NSString and NSMutableString are implemented as a class cluster (see "String Objects" in the iOS version of the documentation ). So isKindOfClass: should return true but isMemberOfClass: will return false since NSString isn't the exact type of the object.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1269859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154967/']}
jdg_370979
stackexchange
llm_judgeable_groundtruth_similarity
10118172
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a div with id="div_register" . I want to set its width dynamically in JavaScript. I am using this following code: getElementById('div_register').style.width=500; but this line of code isn't working. I also tried using the units px like the following, still no luck: getElementById('div_register').style.width='500px'; and getElementById('div_register').style.width='500'; and getElementById('div_register').style.width=500px; but none of this code is working for me. I don't know what's going wrong. I am using Mozilla Firefox. EDIT <html> <head> <title>Untitled</title> <script> function show_update_profile() { document.getElementById('black_fade').style.display='block'; //document.getElementById.('div_register').style.left=((window.innerWidth)-500)/20; document.getElementById('div_register').style.height= "500px"; document.getElementById('div_register').style.width= '500px'; //alert('kutta'); document.getElementById('div_register').style.display='block'; document.getElementById('register_flag').value= 1; document.getElementById('physical_flag').value= 0; document.getElementById('cultural_flag').value= 0; document.getElementById('professional_flag').value= 0; document.getElementById('lifestyle_flag').value= 0; document.getElementById('hobby_flag').value= 0; //alert(window.innerWidth); } </script> <style> .white_content { display:none; } </style> </head> <body> <div id="main"> <input type="button" onclick="javascript:show_update_profile();" id="show" name="show" value="show"/> </div> <div id="div_register"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td> welcome </td> </tr> </table> </div> </body></html> Now provide the response and nothing else.
The properties you're using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following: document.getElementById('div_register').setAttribute("style","width:500px"); For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties: document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");document.getElementById("mydiv").style.display = "block";document.getElementById("mydiv").style.cursor = "hand"; Thus, the most cross-browser compatible example for you would be: document.getElementById('div_register').setAttribute("style","display:block;width:500px");document.getElementById('div_register').style.width='500px'; I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you'll actually make friends with your Web designers! document.getElementById("div_register").setAttribute("class","wide");.wide { display:block; width:500px;}.hide { display:none;}.narrow { display:block; width:100px;} Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized. This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/10118172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1170507/']}
jdg_370980
stackexchange
llm_judgeable_groundtruth_similarity
27594959
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 dataset containing 10 events occuring at a certain time on a given day, with corresponding value for each event: d1 <- data.frame(date = as.POSIXct(c("21/05/2010 19:59:37", "21/05/2010 08:40:30", "21/05/2010 09:21:00", "21/05/2010 22:29:50", "21/05/2010 11:27:34", "21/05/2010 18:25:14", "21/05/2010 15:16:01", "21/05/2010 09:41:53", "21/05/2010 15:01:29", "21/05/2010 09:02:06"), format ="%d/%m/%Y %H:%M:%S"), value = c(11313,42423,64645,643426,1313313,1313,3535,6476,11313,9875)) I want to aggregate the results every 3 minutes, in a standard dataframe format (from "21/05/2010 00:00:00" to "21/05/2010 23:57:00", so that the dataframe has 480 bins of 3 minutes each) First, I create a dataframe containing bins of 3 minutes each: d2 <- data.frame(date = seq(as.POSIXct("2010-05-21 00:00:00"), by="3 min", length.out=(1440/3))) Then, I merge the two dataframes together and remove NAs: library(dplyr)m <- merge(d1, d2, all=TRUE) %>% mutate(value = ifelse(is.na(value),0,value)) Finally, I use period.apply() from the xts package to sum the values for each bin: library(xts)a <- period.apply(m$value, endpoints(m$date, "minutes", 3), sum) Is there a more efficient way to do this ? It does not feel optimal. Update #1 I adjusted my code after Joshua's answer: library(xts)startpoints <- function (x, on = "months", k = 1) { head(endpoints(x, on, k) + 1, -1) }m <- seq(as.POSIXct("2010-05-21 00:00:00"), by="3 min", length.out=1440/3)x <- merge(value=xts(d1$value, d1$date), xts(,m))y <- period.apply(x, c(0,startpoints(x, "minutes", 3)), sum, na.rm=TRUE) I wasn't aware that na.rm=TRUE could be used with period.apply() , which now allows me to skip mutate(value = ifelse(is.na(value),0,value)) . It's a step forward and I'm actually pleased with the xts approach here but I would like to know if there is a pure dplyr solution I could use in such a situation. Update #2 After trying Khashaa's answer, I had an error because my timezone was not specified. So I had: > tail(d4) interval sumvalue476 2010-05-21 23:45:00 NA477 2010-05-21 23:48:00 NA478 2010-05-21 23:51:00 NA479 2010-05-21 23:54:00 NA480 2010-05-21 23:57:00 11313481 2010-05-22 02:27:00 643426> d4[450,] interval sumvalue450 2010-05-21 22:27:00 NA Now, after Sys.setenv(TZ="UTC") , it all works fine. Now provide the response and nothing else.
lubridate-dplyr -esque solution. library(lubridate)library(dplyr)d2 <- data.frame(interval = seq(ymd_hms('2010-05-21 00:00:00'), by = '3 min',length.out=(1440/3)))d3 <- d1 %>% mutate(interval = floor_date(date, unit="hour")+minutes(floor(minute(date)/3)*3)) %>% group_by(interval) %>% mutate(sumvalue=sum(value)) %>% select(interval,sumvalue) d4 <- merge(d2,d3, all=TRUE) # better if left_join is usedtail(d4)# interval sumvalue#475 2010-05-21 23:42:00 NA#476 2010-05-21 23:45:00 NA#477 2010-05-21 23:48:00 NA#478 2010-05-21 23:51:00 NA#479 2010-05-21 23:54:00 NA#480 2010-05-21 23:57:00 NAd4[450,]# interval sumvalue#450 2010-05-21 22:27:00 643426 If you are comfortable working with Date (I am not), you can dispense with lubridate , and replace the final merge with left_join .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27594959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4064778/']}
jdg_370981
stackexchange
llm_judgeable_groundtruth_similarity
38001223
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to the git rm documentation , --cachedUse this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone. But according to this resource unstaging a file is done with git reset HEAD <file> What is the difference? Is there one? Now provide the response and nothing else.
With git rm --cached you stage a file for removal, but you don't remove it from the working dir. The file will then be shown as untracked. Take a test drive git init test_repocd test_repotouch testgit add testgit commit -m 'Added file testgit rm --cached testgit statusChanges to be committed: (use "git reset HEAD <file>..." to unstage) deleted: test <---- staged for removalUntracked files: (use "git add <file>..." to include in what will be committed) test <-- still in the working dir With git reset <file> you can unstage a file. In the example above you might want to use git reset test to unstage the removal. git reset testgit statusOn branch masternothing to commit, working directory clean
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38001223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1887370/']}
jdg_370982
stackexchange
llm_judgeable_groundtruth_similarity
10476057
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 I use malloc along with Automatic Reference Counting, do I still have to manually free the memory? int a[100];int *b = malloc(sizeof(int) * 100);free(b); Now provide the response and nothing else.
Yes, you have to code the call to free yourself. However, your pointer may participate in the reference counting system indirectly if you put it in an instance of a reference-counted object: @interface MyObj : NSObject { int *buf;}@end@implementation MyObj-(id)init { self = [super init]; if (self) { buf = malloc(100*sizeof(int)); }}-(void)dealloc { free(buf);}@end There is no way around writing that call to free - one way or the other, you have to have it in your code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10476057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737842/']}
jdg_370983
stackexchange
llm_judgeable_groundtruth_similarity
420895
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on creating a call back function for an ASP.NET cache item removal event. The documentation says I should call a method on an object or calls I know will exist (will be in scope), such as a static method, but it said I need to ensure the static is thread safe. Part 1: What are some examples of things I could do to make it un-thread safe? Part 2: Does this mean that if I have static int addOne(int someNumber){ int foo = someNumber; return foo +1; } and I call Class.addOne(5); and Class.addOne(6); simutaneously, Might I get 6 or 7 returned depending on who which invocation sets foo first? (i.e. a race condition) Now provide the response and nothing else.
That addOne function is indeed thread safe because it doesn't access any data that could be accessed by another thread. Local variables cannot be shared among threads because each thread gets its own stack. You do have to make sure, however, that the function parameters are value types and not reference types. static void MyFunction(int x) { ... } // thread safe. The int is copied onto the local stack.static void MyFunction(Object o) { ... } // Not thread safe. Since o is a reference type, it might be shared among multiple threads.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/420895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33264/']}
jdg_370984
stackexchange
llm_judgeable_groundtruth_similarity
4804
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: In images of the Earth taken from spacecraft (or composite images thereof), the color rendering seems to be really inconsistent. Examples (Source: NASA, https://visibleearth.nasa.gov/images/57735/the-blue-marble-land-surface-ocean-color-sea-ice-and-clouds ) This is one of NASA's composite images. Here, the Sahara is yellow. (Source: NASA, https://visibleearth.nasa.gov/images/55418/the-blue-marble-from-apollo-17 ) This is a photo from an Apollo mission. Here, the Sahara is an orange/red ochre. This is a very different color. I realize that there are annual variations to be expected in the color of the landscape, but the above differences seem to be too large to be accounted for by that effect. Is the Sahara ochre or yellow? Now provide the response and nothing else.
Neither. The Sahara Desert is heterogenous. It’s yellow, red, orange, brown, black, and even green in certain places and at certain times of year. Slightly less cheeky answer: neither. Both examples are both approximations of human vision, displayed on computer screens that can be highly variable. The 2002 version of the Blue Marble is a composite of 4 months of atmospherically-corrected data in narrow wavelength bands. The composite data is scaled to approximate the nonlinear response of human vision. In particularly bright areas the image is clipped in some bands, leading to incorrect hue and loss of contrast. For all the gory details, here’s the user’s guide for the MODIS land surface reflectance product (which has always looked slightly greenish to me): http://modis-sr.ltdri.org/guide/MOD09_UserGuide_v1.4.pdf The Apollo 17 Blue Marble is a color-corrected scan of 40-year-old film (stored in a freezer at NASA’s Johnson Space Center) and is also not a particularly good representation of what an astronaut would see (as Pont commented earlier). The best description of the appearance of the Earth from space is from astronaut Piers Sellers, who said it’s “brilliant blue, and too bright to look at directly—like sunlight reflected off snow while skiing at high altitude”. Brutally honest answer: neither. To paraphrase Mapbox’s Charlie Loyd, there’s an irreducible subjectivity to color. How we perceive color is affected by ambient light, adjacent colors, overall amount of light, individual physiology, our age, and probably mood and what we had to eat for breakfast. Viewed from space there are even more variables: particularly atmospheric conditions (which influence both incident and reflected light) and viewing angle. Current state-of-the-art is probably NOAA View, http://www.nnvl.noaa.gov/view/#TRUE which uses a multi-band algorithm to simulate true color with Visible Infrared Imaging Radiometer Suite (VIIRS) data. According to that algorithm, the Sahara is more red than yellow. For the record, I’ve worked on color-correcting MODIS imagery, the Blue Marble datasets, and astronaut photography on the NASA Earth Observatory & Visible Earth sites (including the referenced version of AS17-148-22727—unfortunately I can’t find the original TIFF.) Perhaps that means I think the Sahara is both ochre and yellow. I also wrote the guide to color-correcting Landsat imagery linked by Jezibelle (thank you).
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/4804', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/669/']}
jdg_370985
stackexchange
llm_judgeable_groundtruth_similarity
32594710
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 tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I'm not quite sure how to best implement it. I have my code and problem below. The first 12 digits of pi are 314159265358. We can make these digits into an expression evaluating to 27182 (first 5 digits of e) as follows: 3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182 or 3 + 1 - 415 * 92 + 65358 = 27182 Notice that the order of the input digits is not changed. Operators (+,-,/, or *) are simply inserted to create the expression. Write a function to take a list of numbers and a target, and return all the ways that those numbers can be formed into expressions evaluating to the target For example: f("314159265358", 27182) should print: 3 + 1 - 415 * 92 + 65358 = 271823 * 1 + 4 * 159 + 26535 + 8 = 271823 / 1 + 4 * 159 + 26535 + 8 = 271823 * 14 * 15 + 9 + 26535 + 8 = 271823141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182 This problem is difficult since you can have any combination of numbers and you don't consider one number at a time. I wasn't sure how to do the combinations and recursion for that step. Notice that parentheses are not provided in the solution, however order of operations is preserved. My goal is to start off with say {"3"}then{"31", "3+1", "3-1", "3*1" "3/1"}then{"314", "31+4", "3+1+4", "3-1-4", "31/4", "31*4", "31-4"} etc. then look at the every value in the list each time and see if it is target value. If it is, add that string to result list. Here is my code public static List<String> combinations(String nums, int target) { List<String> tempResultList = new ArrayList<String>(); List<String> realResultList = new ArrayList<String>(); String originalNum = Character.toString(nums.charAt(0)); for (int i = 0; i < nums.length(); i++) { if (i > 0) { originalNum += nums.charAt(i); //start off with a new number to decompose } tempResultList.add(originalNum); char[] originalNumCharArray = originalNum.toCharArray(); for (int j = 0; j < originalNumCharArray.length; j++) { //go through every character to find the combinations? // maybe recursion here instead of iterative would be easier... } for (String s : tempResultList) { //try to evaluate int temp = 0; if (s.contains("*") || s.contains("/") || s.contains("+") || s.contains("-")) { //evaluate expression } else { //just a number } if (temp == target) { realResultList.add(s); } } tempResultList.clear(); } return realResultList; } Could someone help with this problem? Looking for an answer with coding in it, since I need help with the generation of possibilities Now provide the response and nothing else.
I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly: static void check(double sum, double previous, String digits, double target, String expr) { if (digits.length() == 0) { if (sum + previous == target) { System.out.println(expr + " = " + target); } } else { for (int i = 1; i <= digits.length(); i++) { double current = Double.parseDouble(digits.substring(0, i)); String remaining = digits.substring(i); check(sum + previous, current, remaining, target, expr + " + " + current); check(sum, previous * current, remaining, target, expr + " * " + current); check(sum, previous / current, remaining, target, expr + " / " + current); check(sum + previous, -current, remaining, target, expr + " - " + current); } } } static void f(String digits, double target) { for (int i = 1; i <= digits.length(); i++) { String current = digits.substring(0, i); check(0, Double.parseDouble(current), digits.substring(i), target, current); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32594710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2476537/']}
jdg_370986
stackexchange
llm_judgeable_groundtruth_similarity
72717
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 have an API written in nodejs and I have a frontendapp written in angularjs. I want my API to be called only through my frontendapp and not from any other source. e.g. I have an endpoint called myhost.com/posts/id and when the method is delete it deletes the posts. I dont want an attacker to access this end point and deletes my posts. How can I prevent it? Now provide the response and nothing else.
I believe that this is not possible in a failsafe way, unfortunately. Let me explain why. You want your frontend app to have a way to identify itself to the API. In other words, you want authentication. But authentication requires the existence of some kind of unique, secret data that the frontend app can use to distinguish itself from other applications. This can be a shared secret (password, "API key"), a private asymmetric crypto key, or something else yet. But whatever it is, it has to remain a secret, since if another app can copy it, it can pass as your frontend app. So the question is, where are you going to store that secret? If it is stored inside of the application code itself, or directly accessible to it, then it is vulnerable to reverse engineering or exploits on your front-end app, no matter how many layers of cryptographic indirection you use to hide it. This is the fundamental security flaw that led to the failure of almost all DRM schemes devised to date. If it is stored on some tamper-proof location of the client machine (e.g. TPM chip, trusted OS key management facility), then the question becomes, how does it get there initially? And how are you going to access it from Javascript code, which has limited low-level OS access capabilities? If it is stored remotely, then you are only shifting the issue of app authentication elsewhere: how is your front-end app going to authenticate on the remote server? Or in other words, what is preventing another app from accessing that remote server in exactly the same way? My conclusion is that there is no truly secure way to authenticate a piece of JS software. You'll have to design your API in a fashion that is secure from malicious client input and, if you do want a way to ban compromised clients anyway, provide clients with revocable "API keys" that you can easily ban on the server side, the way most web services (and newer DRMs) do it.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/72717', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/20657/']}
jdg_370987
stackexchange
llm_judgeable_groundtruth_similarity
629524
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 have been interested in this particular switch with a built-in LED . According to the website, the forward voltage for the LED inside the switch is "about 3 V". It then goes on to recommend a resistor of ateast 220 Ω resistor as do some other sources. I plan on powering the LED through the Pi Pico VBUS pin which, if I understand correctly, is roughly 5 V. Also, after some research I came to the conclusion that the blue LED is most likely in the 25 mA current draw ballpark. So with that info in mind... 5 V - 3 V = 2 V 2 V / 0.025 A = 80 Ω Now, although the current draw was a guess on my part, I figured that even if it is slightly different than the number I gave it wouldn't be enough to change what I am trying to convey. I don't quite understand the disparity between what articles say and what Ohm's law seems to say. Ohm's law, at least on paper, seems to indicate a resistor in the ballpark quite a bit lower than the 220 Ω I see on Adafruit as well as other articles. Is it just because 220 Ω is much more standard and easier to find? If so, will the decreased current resulting from the 220 Ω resistor cause enough of a difference in brightness in the LED for it to matter, or can I just use 220 Ω and be done with it? Now provide the response and nothing else.
LEDs are not very fussy about the current you apply, but will be dimmer with lower currents. The 25 mA you mention is around the Absolute Maximum rating for common LEDs. If you exceed the Absolute Maximum rating for a part, the part may be damaged. I find most common LEDs are bright enough for indicator use with 10 mA or less. I once had to reduce the current for a green LED to under 1 mA to get it dim enough for my application! If you have a few resistors on hand, try various values in series with different LEDs to see what effects they have on the brightness. If you are just using the LEDs as indicators, you will probably find quite low currents are adequate. If you are using the LEDs for general lighting, you will want to operate the LED near the Absolute Maximum rating to get most brightness.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/629524', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/289504/']}
jdg_370988
stackexchange
llm_judgeable_groundtruth_similarity
1929722
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I find all ordered pairs of real numbers $(x, y)$ such that $x^2y^2 + 2xy^2 + 5x^2 + 3y^2 + 10x + 5 = 0$? I don't see a pattern, I don't know how to proceed. Any answer is greatly appreciated. Now provide the response and nothing else.
$$ y^2 \; ( x^2 + 2x + 3) = -5(x^2 + 2 x + 1) $$$$ y^2 = -5 \; \; \frac{(x+1)^2 }{2 + (x+1)^2} $$The right hand side is never positive. It is only zero when $x=-1$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1929722', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/366525/']}
jdg_370989
stackexchange
llm_judgeable_groundtruth_similarity
245188
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 creating a mobile app which has chat feature in it. Since I wanted to make it secure, I'll do some encryption to messages and the data. I'm thinking of using End-To-End encryption for it but I've got some issues. Each user will have private and public keys to encrypt and decrypt the data (asymmetric key encryption) and I figured out how to exchange this keys between. So End-To-End encrypted messaging is done. Here are my issues: If user changes the device or reinstalls the app, the private key which stored on client will be lost. I know I can create new key pairs for future messages but how can I restore the old ones? I thought storing the private key in server but it won't be secure at all. I thought storing the private key after encrypting it with user password, it would be secure since I don't know the user's password, but it fails too if user lost his/her password and re-creates one with a "lost my password email". And another issue is if some legal issue happens, I can't give the chat logs to police because I don't have the decrypted messages or I don't know how to decrypt them because I don't have the private key. So, how should I handle this issues? How does WhatsApp do it while using End-To-End encryption? You can restore the old messages in WhatsApp after changing device, updating or re-installing the app etc... I read something about re-encrypting and re-sending the messages from the other user. (Receiver-Sender) But I don't know how effective it would be tho. Any help would be great. Thanks for all information and help. Now provide the response and nothing else.
You have found another example of the balance security vs usability. If you want true E2E encryption, end users are responsible for their keys and for possible backups of their messages. Full stop. If you stray from that path, you will fall in a grey zone where everything is E2E encrypted but some features allow to recover messages. Said differently: even if traffic were encrypted, the software can still access old messages - which defeats the point of E2E. WhatsApp, for example, chose to implement the ability for a user to ask for a re-send of all their passed (received) messages without the sender being aware of that. If a user genuinely changes their smartphone, they "automagically" recover all of their old messages. Great... But that means that the application contains all what is required for the system to ask to send everything to a rogue address. Gulp... That being said, you will have to make some executive decisions here. Provided that you and your users are aware that any recovery option does lower the overall security, that will be fine. Do not worry too much -- while most users insist for everything they send or receive to be strongly E2E encrypted, for most users it is far more important to be able to recover their messages than to totally prevent an attacker from accessing them... For better or for worse, most users aren't aware of the full definitions of E2E encryption and strong cryptography , and are usually satisfied with them being claimed
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/245188', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/251564/']}
jdg_370990
stackexchange
llm_judgeable_groundtruth_similarity
18437315
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a simple to do list that automatically moves a task over to a sheet called "Completed" when it's finished and adds a time stamp to the completed task. Everything is working, the only issue is that when the timestamp is added to the completed timestamp column, it is not formatted correctly (the center of the cell). Any input on what could be causing this would be appreciated! Here is my script code: function onEdit(event) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var s = event.source.getActiveSheet(); var r = event.source.getActiveRange(); if(s.getName() == "Uncompleted" && r.getColumn() == 1 && r.getValue() == "Yes") { var row = r.getRow(); var numColumns = s.getLastColumn(); var targetSheet = ss.getSheetByName("Completed"); var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1); s.getRange(row, 1, 1, numColumns).moveTo(target); s.deleteRow(row); var completed = targetSheet.getRange(targetSheet.getLastRow(), 8); var time = s.getRange("H1").getValue(); completed.setValue(time); } } And you can view the working spreadsheet here: https://docs.google.com/spreadsheet/ccc?key=0AiU2vLPIL9GldHgyRUJMMVk5TTlSQVR1cFN1Sk10Tnc&usp=sharing Now provide the response and nothing else.
The Backgroundworker class has the method CancelAsync() which you need to call to cancel the execution of the bgw. You need to set the Backgroundworker.WorkerSupportsCancellation property to true and inside the while loop you need to check the CancellationPending property wether the value is true which indicates a call to the CancelAsync() method. If CancellationPending evaluates to true, you would ( which you should have done already ) call one of the overloaded ReportProgress() ( Docu ) methods to set your ProgressBar value to the desired value. EDIT: You should set the Cancel property of the DoWorkEventArgs to true so you can check the Cancelled property of the RunWorkerCompletedEventArgs inside the RunworkerCompleted event. You also shouldn not access any controls which lives in the UI thread. You better use the ProgressChanged ( Docu ) event. See: BackgroundWorker Docu
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18437315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1425581/']}
jdg_370991
stackexchange
llm_judgeable_groundtruth_similarity
12288628
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to OCaml, I'm trying to understand how you're supposed to get the value from an 'a option. According to the doc at http://ocaml-lib.sourceforge.net/doc/Option.html , there is a get function of type 'a option -> 'a that does what I want. but when I type: # let z = Some 3;;val z : int option = Some 3# get z;;Error: Unbound value get# Option.get z;;Error: Unbound module Option Why isnt this working? Now provide the response and nothing else.
The traditional way to obtain the value inside any kind of constructor in OCaml is with pattern-matching. Pattern-matching is the part of OCaml that may be most different from what you have already seen in other languages, so I would recommend that you do not just write programs the way you are used to (for instance circumventing the problem with ocaml-lib) but instead try it and see if you like it. let contents = match z with Some c -> c;; Variable contents is assigned 3 , but you get a warning: Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: None In the general case, you won't know that the expression you want to look inside is necessarily a Some c . The reason an option type was chosen is usually that sometimes that value can be None . Here the compiler is reminding you that you are not handling one of the possible cases. You can pattern-match “in depth” and the compiler will still check for exhaustivity. Consider this function that takes an (int option) option : let f x = match x with Some (Some c) -> c | None -> 0 ;; Here you forgot the case Some (None) and the compiler tells you so: Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: Some None
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12288628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650065/']}
jdg_370992
stackexchange
llm_judgeable_groundtruth_similarity
2344227
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: Lets say I want to find the equation of line passing through $z, z^\prime \in \Bbb C$. What I will do is to solve $\Im (z) = m\Re (z) + c$ and $\Im(z^\prime) = m \Re(z^\prime) + c$ for $m$ and $c$, but I want to solve directly into $zz_0 + \bar z \bar z_0 = c$ for $z_0$ and $c$. Is this possible ? If so how can I do it ? Now provide the response and nothing else.
There's really no difference in what you are trying to do between the complex plane and the $x$ - $y$ plane Let $z = \Re(z) + i \Im(z) = x_1 + iy_1 = (x_1, y_1)$ Let $z' = \Re(z') + i \Im(z') = x_2 + iy_2 = (x_2, y_2)$ The equation for the line is $(y - y_1) = \frac {y_2 - y_1}{x_2 - x_1} (x - x_1)$ Or $y = mx + b$ where $m = \frac {y_2 - y_1}{x_2 - x_1}$ (the slope) and $b = y_1 - mx_1$ (the $y$ intercept). So the equation for the line is simple $\frac {\Im(w) - \Im(z)}{\Re(w) - \Re(z)} = \frac {\Im(z') - \Im(z)}{\Re(z') - \Re(z)}$ (or any other equivalent way of writing it). Perhaps a more "mature" way to do it is to express in term of a variable $t$ where $f(0) = z$ and $f(1) = z'$ then $f(t) = t(z'-z)+ z$ . Idea being: $$\begin{align*}f(t) &= t \cdot (\text{distance traveled in a time unit}) + \text{starting point} \\\\&= t \cdot (\text{ending point} - \text{starting point}) + \text{starting point} \\\\&= t \cdot (z' - z) + z. \end{align*}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2344227', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/516330/']}
jdg_370993
stackexchange
llm_judgeable_groundtruth_similarity
9617420
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 know the difference between extracting and packaging libraries into a jar file from eclipse with the runnable jar file creation. If my program (runnable jar) uses other classes which require these external libraries(jars), what should I pick? Now provide the response and nothing else.
If you want to put jars into your generated jar file, you can use packaging method.For example if you are using an Apache library or some other 3rd party jars, you may want to keep these jars preserved in your generated jar. In this case, use packaging. "Packaging required libraries into a jar file" option puts classes of org.eclipse.jdt.internal.jarinjarloader package into your generated file and this package is just under the root directory of the generated jar file. This option also creates a larger jar file in terms of size due to jar loader classes of Eclipse. Extracting required libraries will result in putting classes of 3rd party libraries into your jar file by following the package naming convention, e.g. if you open your jar content you can see some classes under org.apache.. packages. Main class entries are different between the MANIFEST.MF files of these jar files: Main class entry when you package required libraries: Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader Main class entry when you extract required libraries: Main-Class: YourMainClass
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9617420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1213900/']}
jdg_370994
stackexchange
llm_judgeable_groundtruth_similarity
2901319
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 looking for a clean expression of the following combinatorial sum : $$\sum\limits_{k=0}^{n}\frac{{n \choose k}^2}{{{2n} \choose {2k}}}$$I recall being told it does have a neat expression. However, I'm not familiar with combinatorics or anything related to evaluating non trivial finite sums such as this, so I basically lack methods to tacke this. Any insight would be great ! Now provide the response and nothing else.
We can simplify it a bit by rearranging the factorials:$$ \frac{\binom nk^2}{\binom{2n}{2k}} = \frac{\frac{n!\,n!}{k!\,k!\,(n-k)!\,(n-k)!}}{\frac{(2n)!}{(2k)!\,(2n-2k)!}} = \frac{n!\,n!}{(2n)!} \cdot \frac{(2k)!}{k!\,k!} \cdot \frac{(2n-2k)!}{(n-k)!\,(n-k)!} = \frac{\binom{2k}{k} \binom{2(n-k)}{n-k}}{\binom{2n}{n}}.$$So this allows us to factor out a term that does not depend on $n$:$$ \sum_{k=0}^n \frac{\binom nk^2}{\binom{2n}{2k}} = \frac{1}{\binom{2n}{n}} \sum_{k=0}^n \binom{2k}{k}\binom{2(n-k)}{n-k}.$$The sum that's left simplifies nicely using generating functions, though I'm not aware of a good way to do it that avoids them. If we start with the identity$$ \frac1{\sqrt{1-4x}} = \sum_{i \ge 0} \binom{2i}{i} x^i$$then we can conclude that the coefficient of $x^n$ in the square of $\frac{1}{\sqrt{1-4x}}$ is precisely the sum we want: the sum as $k$ goes from $0$ to $n$ represents the coefficient of $x^k$ taken from one factor times the coefficient of $x^{n-k}$ taken from the other. But the coefficient of $x^n$ in $\frac{1}{1-4x}$ is just $4^n$: it's a geometric series. So we conclude that $$ \sum_{k=0}^n \frac{\binom nk^2}{\binom{2n}{2k}} = \frac{1}{\binom{2n}{n}} \sum_{k=0}^n \binom{2k}{k}\binom{2(n-k)}{n-k} = \frac{4^n}{\binom{2n}{n}}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2901319', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/585169/']}
jdg_370995
stackexchange
llm_judgeable_groundtruth_similarity
10501
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: Consider the plot of this discontinuous function: f[x_] := If[2 < x < 3, 0, x]Plot[f[x], {x, 0, 5}] I'd like to plot that without the vertical segments.Modifying the function f is not allowed. ADDED: I should've said more about the restriction on modifying f .In the real application where this came up, f is a messy thing that should be treated as a black box. So we can't pick out the discontinuity, and probably can't invert the function either. Now provide the response and nothing else.
I looked for a way without redefining the function and not using explicit knowledge about it (so it can be generalized) pl[f_, lims_] := Module[{eps = 0.05}, Off[InverseFunction::"ifun"]; Print@Plot[f[u], {u, lims[[1]], lims[[2]]}, Exclusions -> {{f[u] == f[InverseFunction[f][u]], Abs[(f[u] - f[u + eps])] > 10 eps}, {f[u] == f[InverseFunction[f][u]], Abs[(f[u] - f[u - eps])] > 10 eps}}] On[InverseFunction::"ifun"]; ];(* Testing *)f[x_] := If[2 < x < 3, 0, x];pl[f, {0, 5}];pl[Tan, {0, 2 Pi}] Edit Ok, this one does not use InverseFunction, and identifies discontinuities, as far as I tested it: (*Function Definition*)pl[f_, lims_]:= Plot[f[u],{u, lims[[1]], lims[[2]]},Exclusions->{True, f[u] == 1}];(*--------Test--------*)flist = { If[Abs@Sin@# > .5, 1, 0] &, If[2 < # < 3, 0, #] &, 1/Sin@# + 1 &, Tan};pk = Table[{Plot[fun[x], {x, 0, 10}], pl[fun, {0, 10}]}, {fun, flist}];GraphicsGrid[pk] Here are side by side the results from Plot (without Options) and from this function: Edit 2 Found a counterexample, and perhaps some comprehension about what is going on there. f = If[Abs@Sin@# > .5, 2, 5] & Does not work. Why? It's easy ... the discontinuity does not cross f[u]==1 ... Doing a Reap-Sow on the Plot (as in @rcollyer's answer) I saw that adding the Exclusions with f[u]==1 adds a few points to the trace just around f[u]==1 and seems that that is the trigger for excluding the discontinuities from the domain. Now trying to find a way to change the f[u]==1 for something that works better ... Edit 3 Found a way with a discrete derivative, a tricky thing. Like this: (*Function Definition*)pl[f_, lims_] := Plot[f[u], {u, lims[[1]], lims[[2]]}, Exclusions -> {(f[u] - f[u + .1])/.1 == 10, (f[u] - f[u + .1])/.1 == -10}]; Note two issues: I had to remove the "True" or "Automatic" option from the Exlusions Taking Abs[] for joining the two Exclusion equalities does not work since it's monitoring the evolution of the lhs ...
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/10501', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1905/']}
jdg_370996
stackexchange
llm_judgeable_groundtruth_similarity
216184
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: What would be a study path for someone in the level of Hartshorne's Algebraic Geometry to understand and study inter-universal Teichmuller (IUT) theory? I know that it heavily relies on anabelian geometry and earlier works of Mochizuki, but what's the order to study those material? I think I had seen somewhere a complete list of papers to read from beginning to end in order to come to a level of understanding to tackle the original four papers about IUT theory, but I can't find it. Now provide the response and nothing else.
According to Mochizuki himself , the essential prerequisites for the IUTeich papers are: Semi-graphs of Anabelioids (sections 1 to 6) The Geometry of Frobenioids I: The General Theory (complete) The Geometry of Frobenioids II: Poly-Frobenioids (sections 1 to 3) The Etale Theta Function and its Frobenioid-theoretic Manifestations (complete) Topics in Absolute Anabelian Geometry I: Generalities (sections 1 and 4) Topics in Absolute Anabelian Geometry II: Decomposition Groups and Endomorphisms (section 3) Topics in Absolute Anabelian Geometry III: Global Reconstruction Algorithms (sections 1 to 5) Arithmetic Elliptic Curves in General Position (complete) While other sources also recommend: The Hodge-Arakelov Theory of Elliptic Curves: Global Discretization of Local Hodge Theories The Galois-Theoretic Kodaira-Spencer Morphism of an Elliptic Curve A Survey of the Hodge-Arakelov Theory of Elliptic Curves I A Survey of the Hodge-Arakelov Theory of Elliptic Curves II Particularly interesting is Fesenko's recent extended remarks on IUT (and learning IUT): Ivan Fesenko, Arithmetic deformation theory via arithmetic fundamental groups and nonarchimedean theta functions There's also an introductory paper by Yuichiro Hoshi, but at least for the moment it is avaible in japanese only Yuichiro Hoshi, Introduction to inter-universal Teichmüller theory As for the (considerable) gap between Hartshorne and Mochizuki's work, the references on each paper are quite concrete and helpful (see for example the ones on Topics in Absolute Anabelian Geometry I for a good sample).
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/216184', 'https://mathoverflow.net', 'https://mathoverflow.net/users/24541/']}
jdg_370997
stackexchange
llm_judgeable_groundtruth_similarity
1896380
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the sum of following infinite series ? I am not able to find it as modification of $\sin x$ or $\log(1+x)$ series $$\frac{1}{x} + \frac{1}{2x^2} + \frac{1}{3x^3} + \dots$$ Now provide the response and nothing else.
tl;dr: for $x\notin[-1,1]$, $$-\ln\left(1-\frac{1}{x}\right) = \sum_{n=1}^\infty \frac{1}{nx^n}.$$ How to get to the result: Start with the series for $x\mapsto \ln(1+x)$: For $x\in(-1,1)$,$$\ln(1+x) = \sum_{n=1}^\infty \frac{(-1)^{n+1}x^n}{n}$$so, considering $-x$,$$\ln(1-x) = \sum_{n=1}^\infty \frac{(-1)^{n+1}(-1)^nx^n}{n} = -\sum_{n=1}^\infty \frac{x^n}{n}$$and therefore, for $x\in(-1,1)$,$$-\ln(1-x) = \sum_{n=1}^\infty \frac{x^n}{n}.$$Now, this implies that for $x\notin[-1,1]$,$$-\ln\left(1-\frac{1}{x}\right) = \sum_{n=1}^\infty \frac{1}{nx^n}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1896380', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/200394/']}
jdg_370998
stackexchange
llm_judgeable_groundtruth_similarity
1998304
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: how to change the backgrond color of view controller from other controller in the app ? Now provide the response and nothing else.
To change the background color of a 'view' you need to set the backgroundColor property on it. This implies that you have access to it. If it was all in one controller you would just use self.view.backgroundColor = [UIColor redColor]; If it was in a navigation or similar based app, then you can access a views parentViewController and change the color on it as follows: self.parentViewController.view.backgroundColor = [UIColor redColor]; If this is not possible then you can set an iVar on the second view controller when it is created that contains the instance of the viewController that you want to change the background color on. MyViewController* secondViewController = [[MyViewController alloc] init];secondViewController.bgColorNeedsChangingViewController = self; Then in the secondViewController's logic self.bgColorNeedsChangingViewController.view.backgroundColor = [UIColor redColor];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1998304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239457/']}
jdg_370999
stackexchange
llm_judgeable_groundtruth_similarity
32896298
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 problem with this code (inside func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) ) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)if indexPath.row > 1{ tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row-1, inSection: 0)], withRowAnimation: .None)}if tDate[activeRow].count == 0{ tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .None)} is that both reloadRowsAtIndexPaths are animated, although withRowAnimation: .None is specified. What am I missing here? Now provide the response and nothing else.
It is often the case in iOS and OS X that you end up with an implicit animation for one reason or another (for example, the code is being executed by other code that has already triggered animation). It can be especially difficult to control animations with UITableView and UICollectionView in my experience. Your best bet is probably to put the calls to reloadRowsAtIndexPaths:withRowAnimation: into a closure passed to UIView 's performWithoutAnimations: method: UIView.performWithoutAnimation { if indexPath.row > 1{ tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row-1, inSection: 0)], withRowAnimation: .None) } if tDate[activeRow].count == 0{ tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .None) }} Note: It's also not a bad idea to call tableView.beginUpdates() and tableView.endUpdates() before and after multiple updates that happen all at once.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32896298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5373024/']}
jdg_371000
stackexchange
llm_judgeable_groundtruth_similarity
49268267
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 React.JS component that will map the notes variable to display. However, I have run into the problem of having no notes and receiving an error. What is a proper way to approach this? Here is the code: import React, {Component} from 'react';class List extends Component { constructor(props){ super(props); }render(){ var notes = this.props.items.map((item, i)=>{ return( <li className="listLink" key={i}> <p>{item.title}</p> <span>{item.content}</span> </li> ) }); return( <div className='list'> {notes} </div> ); }}export default List; Now provide the response and nothing else.
If you want to render the notes when at least one note exists and a default view when there are no notes in the array, you can change your render function's return expression to this: return( <div className='list'> {notes.length ? notes : <p>Default Markup</p>} </div>); Since empty arrays in JavaScript are truthy, you need to check the array's length and not just the boolean value of an array. Note that if your items prop is ever null, that would cause an exception because you'd be calling map on a null value. In this case, I'd recommend using Facebook's prop-types library to set items to an empty array by default. That way, if items doesn't get set, the component won't break.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49268267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8922507/']}
jdg_371001
stackexchange
llm_judgeable_groundtruth_similarity
41947212
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 limit the number of instances that can run in a subnet to the smallest number of instances possible. This in combination with an IAM role will allow me to limit how many instances a user can create on my AWS account (see https://forums.aws.amazon.com/thread.jspa?threadID=174503 requirement #4 which reflects my motivations). What is the smallest subnet one can create on AWS in the VPC and what would the IPv4 CIDR be? Now provide the response and nothing else.
16 IPs is the smallest range for a VPC Subnet -- /28 netmask. For example, you could create a VPC with the CIDR range 10.0.0.0/26 which would support up to 64 IPs in the range of 10.0.0.0 - 10.0.0.63 . Then you could create 4 subnets, each with 16 available IPs using the following VPC CIDR ranges: 10.0.0.0/28 (10.0.0.0 - 10.0.0.15)10.0.0.16/28 (10.0.0.16 - 10.0.0.31)10.0.0.32/28 (10.0.0.32 - 10.0.0.47)10.0.0.48/28 (10.0.0.48 - 10.0.0.63) NOTE: See important comment below by @sqlbot. Not all 16 in range can be used for instances.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41947212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1413836/']}
jdg_371002
stackexchange
llm_judgeable_groundtruth_similarity
244199
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: Can somebody explain how the properties of logs make it so you can do log linear regressions where the coefficients are interpreted as percentage changes? Now provide the response and nothing else.
For $x_2$ and $x_1$ close to each other, the percent change $\frac{x_2-x_1}{x_1}$ approximates the log difference $\log x_2 - \log x_1$ . Why does the percent change approximate the log difference? An idea from calculus is that you can approximate a smooth function with a line. The linear approximation is simply the first two terms of a Taylor Series . The first order Taylor Expansion of $\log(x)$ around $x=1$ is given by: $$\log(x) \approx \log(1) + \frac{d}{dx} \left. \log (x) \right|_{x=1} \left( x - 1 \right)$$ The right hand side simplifies to $0 + \frac{1}{1}\left( x - 1\right)$ hence: $$ \log(x) \approx x-1$$ So for $x$ in the neighborhood of 1, we can approximate $\log(x)$ with the line $y = x - 1$ Below is a graph of $y = \log(x)$ and $y = x - 1$ . Example: $\log(1.02) = .0198 \approx 1.02 - 1$ . Now consider two variables $x_2$ and $x_1$ such that $\frac{x_2}{x_1} \approx 1$ . Then the log difference is approximately the percent change $\frac{x_2}{x_1} - 1 = \frac{x_2 - x_1}{x_1}$ : $$ \log x_2 - \log x_1 = \log\left( \frac{x_2}{x_1} \right) \approx \frac{x_2}{x_1} - 1 $$ The percent change is a linear approximation of the log difference! Why log differences? Often times when you're thinking in terms of compounding percent changes, the mathematically cleaner concept is to think in terms of log differences. When you're repeatedly multiplying terms together, it's often more convenient to work in logs and instead add terms together. Let's say our wealth at time $T$ is given by: $$ W_T = \prod_{t=1}^T (1 + R_t)$$ Then it might be more convenient to write: $$ \log W_T = \sum_{t=1}^T r_t $$ where $r_t = \log (1 + R_t) = \log W_t - \log W_{t-1}$ . Where are percent changes and the log difference NOT the same? For big percent changes, the log difference is not the same thing as the percent change because approximating the curve $y = \log(x)$ with the line $y = x - 1$ gets worse and worse the further you get from $x=1$ . For example: $$ \log\left(1.6 \right) - \log(1) = .47 \neq 1.6 - 1$$ What's the log difference in this case? One way to think about it is that a difference in logs of .47 is equivalent to an accumulation of 47 different .01 log differences, which is approximately 47 1% changes all compounded together. \begin{align*} \log(1.6) - \log(1) &= 47 \left( .01 \right) \\& \approx 47 \left( \log(1.01) \right) \end{align*} Then exponentiate both sides to get: $$ 1.6 \approx 1.01 ^{47}$$ A log difference of .47 is approximately equivalent to 47 different 1% increases compounded, or even better, 470 different .1% increases all compounded etc... Several of the answers here make this idea more explicit.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/244199', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/113447/']}
jdg_371003
stackexchange
llm_judgeable_groundtruth_similarity
845373
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I understand correctly, one way to get the components of a metric tensor (treating it like a matrix here) is to look at the $ds$ interval. Isn't that interval always in terms of sums of $dr^2+d\theta^2$ etc, meaning that the metric tensor will only have nonzero values for $x^ix^j$ when $i=j$ ? If this is not the case, can anyone give an example? Now provide the response and nothing else.
Being diagonal is a coordinate-dependent concept: the components of the matrix associated to the metric tensor depend on the coordinate system you use. Thus a very simple example of a non-diagonal metric is the standard Euclidean metric $\delta = dx^2 + dy^2$ on $\mathbb R^2$ in the coordinate system $(x,z) = (x, x+y)$, where it has the coordinate expression $$\delta = dx^2 + d(z-x)^2 = 2dx^2 + dz^2 - 2 dx dz.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/845373', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_371004
stackexchange
llm_judgeable_groundtruth_similarity
4262412
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: Find by integration the area of the subset of $R^2$ bounded by the curve: $x^2-2x+4y^2-8y+1=0$ What I have tried: Re-arrange to find for $y$ , I find that $y = \frac{1}{2}\sqrt{2-(x-1)^2}$ when the equation is simplified as $(x-1)^2+4(y-1)^2-2=0$ . From here I'm unsure of how to proceed with integration. I had thought $y$ would take the integral of this form: $$\int_{-\frac{1}{2}\sqrt{2-(x-1)^2}}^{\frac{1}{2}\sqrt{2-(x-1)^2}}$$ By trying to define the equation on a unit circle, however I would deeply appreciate your help on this! Now provide the response and nothing else.
Most proofs of the Nielsen-Schreier theorem proceed by following a recipe for finding generators of the subgroup $H$ in $F$ and then proving that they are free generators. You start by finding a (right) Schreier (= prefix closed) transversal of $H$ in $F$ . Let $X$ be a set of free generators of $F$ and, for $g \in F$ , let $\bar{g}$ denote the unique element of $U$ with $Hg = H\bar{g}$ . Then the subset of non-identity elements of the set $$\{ux \overline{ux}^{-1} : u \in U, x \in X \}$$ freely generates $H$ . In your example, we can take $U = \{1,a\}$ , leading to the free generating set $\{b,a^2,aba^{-1}\}$ of $H$ , which is the same as that found in the answer by kabenyuk. You can check normality of a subgroup $H$ of $F$ by constructing the permutation representation of $F$ on the cosets of $H$ in $F$ , and then checking whether the generators of $H$ all act trivially on this set. The above method of testing for normality is fine for subgroups of moderately small finite index, but for arbitrary finitely generated subgroups, you can use the fact that membership testing in such subgroups is possible (using methods based on Stallings' Folding) and then testing membership of $xgx^{-1}$ and $x^{-1}gx$ in $H$ for all $x \in X$ and generators $g$ of $H$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4262412', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/951714/']}
jdg_371005
stackexchange
llm_judgeable_groundtruth_similarity
44073393
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All documents in my collection in MongoDB have the same fields. My goal is to load them into Python into pandas.DataFrame or dask.DataFrame . I'd like to speedup the loading procedure by parallelizing it. My plan is to spawn several processes or threads. Each process would load a chunk of a collection, then these chunks would be merged together. How do I do it correctly with MongoDB? I have tried similar approach with PostgreSQL. My initial idea was to use SKIP and LIMIT in SQL queries. It has failed, since each cursor, opened for each particular query, started reading data table from the beginning and just skipped specified amount of rows. So I had to create additional column, containing record numbers, and specify ranges of these numbers in queries. On the contrary, MongoDB assigns unique ObjectID to each document. However, I've found that it is impossible to subtract one ObjectID from another, they can be only compared with ordering operations: less, greater and equal. Also, pymongo returns the cursor object, that supports indexing operation and has some methods, seeming useful for my task, like count , limit . MongoDB connector for Spark accomplishes this task somehow. Unfortunately, I'm not familiar with Scala, therefore, it's hard for me to find out how they do it. So, what is the correct way for parallel loading data from Mongo into python? up to now, I've come to the following solution: import pandas as pdimport dask.dataframe as ddfrom dask.delayed import delayed# import other modules.collection = get_mongo_collection()cursor = collection.find({ })def process_document(in_doc): out_doc = # process doc keys and values return pd.DataFrame(out_doc)df = dd.from_delayed( (delayed(process_document)(d) for d in cursor) ) However, it looks like dask.dataframe.from_delayed internally creates a list from passed generator, effectively loading all collection in a single thread. Update . I've found in docs , that skip method of pymongo.Cursor starts from beginning of a collection too, as PostgreSQL. The same page suggests using pagination logic in the application. Solutions, that I've found so far, use sorted _id for this. However, they also store last seen _id , that implies that they also work in a single thread. Update2 . I've found the code of the partitioner in the official MongoDb Spark connector: https://github.com/mongodb/mongo-spark/blob/7c76ed1821f70ef2259f8822d812b9c53b6f2b98/src/main/scala/com/mongodb/spark/rdd/partitioner/MongoPaginationPartitioner.scala#L32 Looks like, initially this partitioner reads the key field from all documents in the collection and calculates ranges of values. Update3 : My incomplete solution. Doesn't work, gets the exception from pymongo, because dask seems to incorrectly treat the Collection object: /home/user/.conda/envs/MBA/lib/python2.7/site-packages/dask/delayed.pyc in <genexpr>(***failed resolving arguments***) 81 return expr, {} 82 if isinstance(expr, (Iterator, list, tuple, set)):---> 83 args, dasks = unzip((to_task_dask(e) for e in expr), 2) 84 args = list(args) 85 dsk = sharedict.merge(*dasks)/home/user/.conda/envs/MBA/lib/python2.7/site-packages/pymongo/collection.pyc in __next__(self) 2342 2343 def __next__(self):-> 2344 raise TypeError("'Collection' object is not iterable") 2345 2346 next = __next__TypeError: 'Collection' object is not iterable What raises the exception: def process_document(in_doc, other_arg): # custom processing of incoming records return out_docdef compute_id_ranges(collection, query, partition_size=50): cur = collection.find(query, {'_id': 1}).sort('_id', pymongo.ASCENDING) id_ranges = [cur[0]['_id']] count = 1 for r in cur: count += 1 if count > partition_size: id_ranges.append(r['_id']) count = 0 id_ranges.append(r['_id']) return zip(id_ranges[:len(id_ranges)-1], id_ranges[1: ]) def load_chunk(id_pair, collection, query={}, projection=None): q = query q.update( {"_id": {"$gte": id_pair[0], "$lt": id_pair[1]}} ) cur = collection.find(q, projection) return pd.DataFrame([process_document(d, other_arg) for d in cur])def parallel_load(*args, **kwargs): collection = kwargs['collection'] query = kwargs.get('query', {}) projection = kwargs.get('projection', None) id_ranges = compute_id_ranges(collection, query) dfs = [ delayed(load_chunk)(ir, collection, query, projection) for ir in id_ranges ] df = dd.from_delayed(dfs) return dfcollection = connect_to_mongo_and_return_collection_object(credentials)# df = parallel_load(collection=collection)id_ranges = compute_id_ranges(collection)dedf = delayed(load_chunk)(id_ranges[0], collection) load_chunk perfectly runs when called directly. However, call delayed(load_chunk)( blah-blah-blah ) fails with exception, mentioned above. Now provide the response and nothing else.
I was looking into pymongo parallelization and this is what worked for me. It took my humble gaming laptop nearly 100 minutes to process my mongodb of 40 million documents. The CPU was 100% utilised I had to turn on the AC :) I used skip and limit functions to split the database, then assigned batches to processes. The code is written for Python 3: import multiprocessingfrom pymongo import MongoClientdef your_function(something): <...> return resultdef process_cursor(skip_n,limit_n): print('Starting process',skip_n//limit_n,'...') collection = MongoClient().<db_name>.<collection_name> cursor = collection.find({}).skip(skip_n).limit(limit_n) for doc in cursor: <do your magic> # for example: result = your_function(doc['your_field'] # do some processing on each document # update that document by adding the result into a new field collection.update_one({'_id': doc['_id']}, {'$set': {'<new_field_eg>': result} }) print('Completed process',skip_n//limit_n,'...')if __name__ == '__main__': n_cores = 7 # number of splits (logical cores of the CPU-1) collection_size = 40126904 # your collection size batch_size = round(collection_size/n_cores+0.5) skips = range(0, n_cores*batch_size, batch_size) processes = [ multiprocessing.Process(target=process_cursor, args=(skip_n,batch_size)) for skip_n in skips] for process in processes: process.start() for process in processes: process.join() The last split will have a larger limit than the remaining documents, but that won't raise an error
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44073393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704329/']}
jdg_371006
stackexchange
llm_judgeable_groundtruth_similarity
266567
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't know if I will be clear about what I am asking for, but here is my problem: how could I create a histogram (with the probability curve, later) when I have many different values (each one with frequency equals to one), in such a way that in the $x$ axis I put ranges (like: $0$ to $80$ , $80$ to $160$ , $160$ to $240$ and so on) and on the $y$ axis I have the frequency, that is the number of values that lie within the $x$ range? To say, the list of my values is: $200,540,563,1031,458,957,200,800,226,314,517,210,900,160,432,380,89,1300,850,120,350,222,243,600,300,173,549,80,500,162,500,450,2000,300,647,371$ I know I have to use BarChart. I just cannot get how to create a range on the $x$ axis and the frequency over $y$ axis. Thank you! Now provide the response and nothing else.
Get into the 21st century and use nonparametric density estimates. In other words, dump the histogram. data = {200, 540, 563, 1031, 458, 957, 200, 800, 226, 314, 517, 210, 900, 160, 432, 380, 89, 1300, 850, 120, 350, 222, 243, 600, 300, 173, 549, 80, 500, 162, 500, 450, 2000, 300, 647, 371};skd = SmoothKernelDistribution[data, "LeastSquaresCrossValidation", {"Bounded", {0, \[Infinity]}, "Gaussian"}];Plot[PDF[skd, x], {x, 0, Max[data]}] And get the CDF: Plot[CDF[skd, x], {x, 0, Max[data]}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/266567', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/36207/']}
jdg_371007
stackexchange
llm_judgeable_groundtruth_similarity
55267701
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 Autocomplete shows the values from an object with this definition: export class Person { id: number; name: string; cityName: string;} This is the autocomplete template: <mat-form-field class="example-full-width"> <input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)"> <mat-option *ngFor="let item of filteredOptions" [value]="item"> {{ item.name }} </mat-option> </mat-autocomplete></mat-form-field> And this is the displayWith function: displayFn(value?: any) { return value ? value.name : undefined;} It works, but the formControl binded to this autocomplete receives the entire item object: { id: 1; name: "John"; cityName: "Dallas"; } How can I get only the "id" value in the formControl ? Now provide the response and nothing else.
You have to do 2 things. Update the template so that the [value] bounds to id instead of the object. Update the displayFn so that the passed in id is used to lookup the object and return the name which will then be displayed in the input. <mat-form-field class="example-full-width"> <input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)"> <mat-option *ngFor="let item of filteredOptions" [value]="item.id"> {{ item.name }} </mat-option> </mat-autocomplete></mat-form-field> displayFn(value?: number) { return value ? this.filteredOptions.find(_ => _.id === value).name : undefined;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55267701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567957/']}
jdg_371008
stackexchange
llm_judgeable_groundtruth_similarity
355887
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This is a Canonical Question about DNS (Domain Name Service). If my understanding of the DNS system is correct, the .com registry holds a table that maps domains (www.example.com) to DNS servers. What is the advantage? Why not map directly to an IP address? If the only record that needs to change when I am configuring a DNS server to point to a different IP address, is located at the DNS server, why isn't the process instant? If the only reason for the delay are DNS caches, is it possible to bypass them, so I can see what is happening in real time? Now provide the response and nothing else.
Actually, it's more complicated than that - rather than one "central registry (that) holds a table that maps domains (www.mysite.com) to DNS servers", there are several layers of hierarchy There's a central registry (the Root Servers) which contain only a small set of entries: the NS (nameserver) records for all the top-level domains - .com , .net , .org , .uk , .us , .au , and so on. Those servers just contain NS records for the next level down. To pick one example, the nameservers for the .uk domain just has entries for .co.uk , .ac.uk , and the other second-level zones in use in the UK. Those servers just contain NS records for the next level down - to continue the example, they tell you where to find the NS records for google.co.uk . It's on those servers that you'll finally find a mapping between a hostname like www.google.co.uk and an IP address. As an extra wrinkle, each layer will also serve up 'glue' records. Each NS record maps a domain to a hostname - for instance, the NS records for .uk list nsa.nic.uk as one of the servers. To get to the next level, we need to find out the NS records for nic.uk are, and they turn out to include nsa.nic.uk as well. So now we need to know the IP of nsa.nic.uk , but to find that out we need to make a query to nsa.nic.uk , but we can't make that query until we know the IP for nsa.nic.uk ... To resolve this quandary, the servers for .uk add the A record for nsa.nic.uk into the ADDITIONAL SECTION of the response (response below trimmed for brevity): jamezpolley@li101-70:~$dig nic.uk ns; <<>> DiG 9.7.0-P1 <<>> nic.uk ns;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 21768;; flags: qr rd ra; QUERY: 1, ANSWER: 11, AUTHORITY: 0, ADDITIONAL: 14;; QUESTION SECTION:;nic.uk. IN NS;; ANSWER SECTION:nic.uk. 172800 IN NS nsb.nic.uk.nic.uk. 172800 IN NS nsa.nic.uk.;; ADDITIONAL SECTION:nsa.nic.uk. 172800 IN A 156.154.100.3nsb.nic.uk. 172800 IN A 156.154.101.3 Without these extra glue records, we'd never be able to find the nameservers for nic.uk. and so we'd never be able to look up any domains hosted there. To get back to your questions... a) What is the advantage? Why not map directly to an IP address? For one thing, it allows edits to each individual zone to be distributed. If you want to update the entry for www.mydomain.co.uk , you just need to edit the information on your mydomain.co.uk 's nameserver. There's no need to notify the central .co.uk servers, or the .uk servers, or the root nameservers. If there was only a single central registry that mapped all the levels all the way down the hierarchy that had to be notified about every single change of a DNS entry all the way down the chain, it would be absolutely swamped with traffic. Before 1982, this was actually how name resolution happened. One central registry was notified about all updates, and they distributed a file called hosts.txt which contained the hostname and IP address of every machine on the internet. A new version of this file was published every few weeks, and every machine on the internet would have to download a new copy. Well before 1982, this was starting to become problematic, and so DNS was invented to provide a more distributed system. For another thing, this would be a Single Point of Failure - if the single central registry went down, the entire internet would be offline. Having a distributed system means that failures only affect small sections of the internet, not the whole thing. (To provide extra redundancy, there are actually 13 separate clusters of servers that serve the root zone. Any changes to the top-level domain records have to be pushed to all 13; imagine having to coordinate updating all 13 of them for every single change to any hostname anywhere in the world...) b) If the only record that needs to change when I am configuring a DNS server to point to a different IP address is located at the DNS server, why isn't the process instant? Because DNS utilises a lot of caching to both speed things up and decrease the load on the NSes. Without caching, every single time you visited google.co.uk your computer would have to go out to the network to look up the servers for .uk , then .co.uk , then .google.co.uk , then www.google.co.uk . Those answers don't actually change much, so looking them up every time is a waste of time and network traffic. Instead, when the NS returns records to your computer, it will include a TTL value, that tells your computer to cache the results for a number of seconds. For example, the NS records for .uk have a TTL of 172800 seconds - 2 days. Google are even more conservative - the NS records for google.co.uk have a TTL of 4 days. Services which rely on being able to update quickly can choose a much lower TTL - for instance, telegraph.co.uk has a TTL of just 600 seconds on their NS records. If you want updates to your zone to be near-instant, you can choose to lower your TTL as far down as you like. The lower your set it, the more traffic your servers will see, as clients refresh their records more often. Every time a client has to contact your servers to do a query, this will cause some lag as it's slower than looking up the answer on their local cache, so you'll also want to consider the tradeoff between fast updates and a fast service. c) If the only reason for the delay are DNS caches, is it possible to bypass them, so I can see what is happening in real time? Yes, this is easy if you're testing manually with dig or similar tools - just tell it which server to contact. Here's an example of a cached response: jamezpolley@host:~$dig telegraph.co.uk NS; <<>> DiG 9.7.0-P1 <<>> telegraph.co.uk NS;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 36675;; flags: qr rd ra; QUERY: 1, ANSWER: 8, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;telegraph.co.uk. IN NS;; ANSWER SECTION:telegraph.co.uk. 319 IN NS ns1-63.akam.net.telegraph.co.uk. 319 IN NS eur3.akam.net.telegraph.co.uk. 319 IN NS use2.akam.net.telegraph.co.uk. 319 IN NS usw2.akam.net.telegraph.co.uk. 319 IN NS use4.akam.net.telegraph.co.uk. 319 IN NS use1.akam.net.telegraph.co.uk. 319 IN NS usc4.akam.net.telegraph.co.uk. 319 IN NS ns1-224.akam.net.;; Query time: 0 msec;; SERVER: 97.107.133.4#53(97.107.133.4);; WHEN: Thu Feb 2 05:46:02 2012;; MSG SIZE rcvd: 198 The flags section here doesn't contain the aa flag, so we can see that this result came from a cache rather than directly from an authoritative source. In fact, we can see that it came from 97.107.133.4 , which happens to be one of Linode's local DNS resolvers. The fact that the answer was served out of a cache very close to me means that it took 0msec for me to get an answer; but as we'll see in a moment, the price I pay for that speed is that the answer is almost 5 minutes out of date. To bypass Linode's resolver and go straight to the source, just pick one of those NSes and tell dig to contact it directly: jamezpolley@li101-70:~$dig @ns1-224.akam.net telegraph.co.uk NS; <<>> DiG 9.7.0-P1 <<>> @ns1-224.akam.net telegraph.co.uk NS; (1 server found);; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23013;; flags: qr aa rd; QUERY: 1, ANSWER: 8, AUTHORITY: 0, ADDITIONAL: 0;; WARNING: recursion requested but not available;; QUESTION SECTION:;telegraph.co.uk. IN NS;; ANSWER SECTION:telegraph.co.uk. 600 IN NS use2.akam.net.telegraph.co.uk. 600 IN NS eur3.akam.net.telegraph.co.uk. 600 IN NS use1.akam.net.telegraph.co.uk. 600 IN NS ns1-63.akam.net.telegraph.co.uk. 600 IN NS usc4.akam.net.telegraph.co.uk. 600 IN NS ns1-224.akam.net.telegraph.co.uk. 600 IN NS usw2.akam.net.telegraph.co.uk. 600 IN NS use4.akam.net.;; Query time: 9 msec;; SERVER: 193.108.91.224#53(193.108.91.224);; WHEN: Thu Feb 2 05:48:47 2012;; MSG SIZE rcvd: 198 You can see that this time, the results were served directly from the source - note the aa flag, which indicates that the results came from an authoritative source. In my earlier example, the results came from my local cache, so they lack the aa flag. I can see that the authoritative source for this domain sets a TTL of 600 seconds. The results I got earlier from a local cache had a TTL of just 319 seconds, which tells me that they'd been sitting in the cache for (600-319) seconds - almost 5 minutes - before I saw them. Although the TTL here is only 600 seconds, some ISPs will attempt to reduce their traffic even further by forcing their DNS resolvers to cache the results for longer - in some cases, for 24 hours or more. It's traditional (in a we-don't-know-if-this-is-really-neccessary-but-let's-be-safe kind of way) to assume that any DNS change you make won't be visible everywhere on the internet for 24-48 hours.
{}
{'log_upvote_score': 8, 'links': ['https://serverfault.com/questions/355887', 'https://serverfault.com', 'https://serverfault.com/users/109136/']}
jdg_371009
stackexchange
llm_judgeable_groundtruth_similarity
27404063
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Being very new to Haskell, I'm wondering how to 1) compute something until a certain criterion is satisfied, and then 2) return the computed value. In the languages I know, you would use a while loop for that. How do you do it in Haskell? Now provide the response and nothing else.
You should use recursion : func :: <function type>func <arguments> = if condition then <recursive call> else computedValue There are also other utilities you'll discover in the future, such as until , that will help you with this. In the end it really depends on the semantic of the loop and condition. For example if the condition is simply "until we reach the end of a list" you can simply use map or one of the fold -family functions.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27404063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3271548/']}
jdg_371010
stackexchange
llm_judgeable_groundtruth_similarity
11397099
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I was looking at the following Fragments example on the android site. http://developer.android.com/guide/components/fragments.html#Example I would like to know why certain methods are performed. Why for instance, in the detailsFragment is the following method performed: public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f;} Could you not also simply instantiate the DetailsFragment and use a setter method to set index instead. Bypassing the whole setArguments . What's the point of using setArguments in the first place? Could you not just use setters and getters? Now provide the response and nothing else.
You can use getters and setters, but by passing in a bundle you don't need to write that code, since it's already there. Also, I believe that these arguments are automatically passed in again if the screen orientation changes, which also makes life easier. Essentially, setArguments and getArguments is just a design pattern that Google suggests you follow: Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments(). http://developer.android.com/reference/android/app/Fragment.html I take that to include setters which are needed for your Fragment to operate as well. Then again - there's nothing forcing you to do it this way, and as you know - it's not the only way things could be made to work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11397099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/317889/']}
jdg_371011
stackexchange
llm_judgeable_groundtruth_similarity
36074
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A massively popular tweet (50k retweets) by Ryan Holmquist quotes Fidel Castro It reads, Castro: I will not die until America is destroyed Trump: I'm gonna be the president Castro: well then There are quite a few other tweets along the same lines. You can also see this popular meme going around (over 10k shares) Did Castro ever say "I will not die until America is destroyed." Now provide the response and nothing else.
It is not an accurate quote. Fidel Castro 19 May 1977 said : Some time ago, the United States was an English colony. If an Englishman were asked if the United States would be independent, he would have said no, that it would always be an English colony. Afterward, the colonies liberated themselves, a nation was established, but it contained slavery. The slave owners would have said that slavery would never disappear, but slavery ended, salaried workers came, capitalism came, it developed extraordinarily, large multinational enterprises developed, and if a reasonable man is asked now if that will be eternal, he will have to say no. Someday the capitalist system will disappear in the United States, because no social class system has been eternal. One day, class societies will disappear. But you can be calm, I do not foresee in a short time any change toward socialism in the United States. So Castro predicted the United States eventually becoming socialist, rather than being destroyed. Also, in the same interview he said: I don't know when I'm going to die, I don't know if I'm going to die tomorrow, tonight, in an accident, from natural causes. I cannot know. So clearly he did not hold the view mentioned in the OP. The quote in the OP is somewhat similar to a famous quote by Bolivar I swear that I will not die until I have driven the last Spaniard out of America which illustrates the geographically inclusive nature of the term "America" and an additional reason that Castro would not say that "America" would be destroyed.
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/36074', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/3835/']}
jdg_371012
stackexchange
llm_judgeable_groundtruth_similarity
185645
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have three related questions about conventions for defining Clifford algebras. 1) Let $(V, q)$ be a quadratic vector space. Should the Clifford algebra $\text{Cliff}(V, q)$ have defining relations $v^2 = q(v)$ or $v^2 = -q(v)$? 2) Should $\text{Cliff}(n)$ denote the Clifford algebra generated by $n$ anticommuting square roots of $1$ or by $n$ anticommuting square roots of $-1$? That is, after you pick an answer to 1), should $\text{Cliff}(n)$ be $\text{Cliff}(\mathbb{R}^n, \| \cdot \|)$ or $\text{Cliff}(\mathbb{R}^n, - \| \cdot \|)$? More generally, after you pick an answer to 1), should $\text{Cliff}(p, q)$ be the Clifford algebra associated to the quadratic form of signature $(p, q)$ or of signature $(q, p)$? 3) Let $(X, g)$ be a Riemannian manifold with Riemannian metric $g$. After you pick an answer to 1), should the bundle of Clifford algebras $\text{Cliff}(X)$ associated to $X$ be given fiberwise by $\text{Cliff}(T_x(X), \pm g_x)$ or by $\text{Cliff}(T_x^{\ast}(X), \pm g_x^{\ast})$? For 1), on the one hand, $v^2 = q(v)$ seems very natural, especially if you think of the Clifford algebra functor as a version of the universal enveloping algebra functor , and it is used in Atiyah-Bott-Shapiro. On the other hand, Lawson-Michelson and Berline-Getzler-Vergne use $v^2 = -q(v)$, I think because they want $\text{Cliff}(\mathbb{R}^n, \| \cdot \|)$ to be the Clifford algebra generated by $n$ anticommuting square roots of $-1$. This is, for example, the correct Clifford algebra to write down if you want to write down a square root of the negative of the Laplacian (which is positive definite). For 2), this choice affects the correct statement of the relationship between $\text{Cliff}(n)$-modules and real $K$-theory, but there is something very confusing going on here, namely that with either convention, $\text{Cliff}(n)$-modules are related to both $KO^n$ and $KO^{-n}$; see Andre Henriques' MO question on this subject. For 3), whatever the answer to 1) or 2) I think everyone agrees that $\text{Cliff}(X)$ should be given fiberwise by $n$ anticommuting square roots of $-1$, where $n = \dim X$, so once you fix an answer to 1) that fixes the signs. The choice of sign affects the correct statement of the Thom isomorphism in K-theory. Lawson-Michelson use the tangent bundle but Berline-Getzler-Vergne use the cotangent bundle. The tangent bundle seems natural if you want to think of Clifford multiplication as a deformation of a covariant derivative, and the cotangent bundle seems natural if you want to think of the Clifford bundle as a deformation of exterior forms. I'm not sure how important this choice is. Anyway, I just want to know whether there are good justifications to sticking to one particular set of conventions so I can pick a consistent one for myself; reconciling the conventions of other authors is exhausting, especially because I haven't decided what conventions I want to use. Now provide the response and nothing else.
This is not really an answer, but rather a meta-answer as to why there exist many conventions in the first place. The symmetric monoidal category $\mathit{sVect}$ of super-vector spaces has a non-trivial involution $J$.The symmetric monoidal functor $J:\mathit{sVect}\to \mathit{sVect}$ is the identity at the level of objects and at the level of morphisms.But the coherence $J(V \otimes W) \xrightarrow{\cong} J(V) \otimes J(W)$ is non-trivial. It is given by $-1$ on $V_{odd} \otimes W_{odd}$ and $+1$ on the rest. The image of $\mathit{Cliff}(V,q)$ under $J$ is $\mathit{Cliff}(V,-q)$. So anything that you do with one convention can equally well be done with the other convention. Over the complex numbers, $J$ is equivalent to the identity functor.The symmetric monoidal natural transformation $J\Rightarrow Id$ that exhibits the equivalence acts as $i$ on the odd part and as $1$ on the even part of any super-vector space. Over the reals, $J$ is not equivalent to the identity functor, as can be seen from the fact that $\mathit{Cliff}(\mathbb R,|\cdot|^2)\not\simeq\mathit{Cliff}(\mathbb R,-|\cdot|^2)$. One last technical comment: Over $\mathbb C$, the action of $\mathbb Z/2$ on $\mathit{sVect}$ defined by $J$ is still non-trivial , despite the fact that $J$ is trivial. A trivialization of the action isn't just an equivalence $\alpha:J\cong Id$. For such an equivalence to trivialize the action, it would need to satisfy the further coherence $\alpha\circ \alpha = 1$, which isn't satisfied by any choice of $\alpha$. (To trivialize the action of a group $G$, one needs to trivialize the actions of each $g\in G$ in such a way that the trivializations of $g,h\in G$ compose to the trivialization of $gh$.) Now, as far as practical things are concerned, I would recommend minimizing the number of minus signs that you end up writing down.
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/185645', 'https://mathoverflow.net', 'https://mathoverflow.net/users/290/']}
jdg_371013
stackexchange
llm_judgeable_groundtruth_similarity
21074159
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider a method to write with a format parameter like string.Format 's frist parameter. As you know the Intellisense is aware of first parameter's constraints and checks for its consistency with parameters. How can I write such method. As a simple example, consider a wrap of string.Format like: public string MyStringFomratter(string formatStr, params object[] arguments){ // Do some checking and apply some logic return string.Format(formatStr, arguments);} How can I say to the compiler or IDE that formatStr is something like string.Format 's first parameter? So if I have some code like this: var x = MyStringFormatter("FristName: {0}, LastName: {1}", firstName);// This code should generate a warning in the IDE Now provide the response and nothing else.
You cannot make Visual Studio analyze parameter content for you - it simply verifies that code is compilable, and String.Format is compilable even if you haven't specified parameters for all placeholders. But you can use Visual Studio add-in (e.g. ReSharper or CodeRush ) which analyzes placeholders count for String.Format formatting string and verifies parameters count passed to this method. BTW I'm not using ReSharper but looks like it has support for marking any method as string formatting method - Defining Custom String Formatting Methods . You just should annotate your method with StringFormatMethodAttribute attribute: [StringFormatMethod("formatStr")]public string MyStringFomratter(string formatStr, params object[] arguments){ // Do some checking and apply some logic return string.Format(formatStr, arguments);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21074159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1831530/']}
jdg_371014
stackexchange
llm_judgeable_groundtruth_similarity
8684234
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On my mobile website. I've been trying to load Adsense Mobile ads, but they continue to take up the entire page after the page loads itself. I did figure out that if I disable ajax the page would load fine with the ad together. This only works on the second page I load because I click a link with the tag... data-ajax="false" Which makes the next page load perfectly. Problem : The first page loaded will be overwritten by the adsense ad because ajax is enabled (I think). Basically the first part of my page looks like this... <html><head><link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc3/jquery.mobile-1.0rc3.min.css" /><script src="http://code.jquery.com/jquery-1.6.4.min.js"></script><script src="http://code.jquery.com/mobile/1.0rc3/jquery.mobile-1.0rc3.min.js"></script><script language="text/javascript"> $(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false; });</script></head><body> <div data-role="header"> <h1>Angry Birds Cheats</h1> </div> <div data-role="content"><div> <script type="text/javascript"><!-- // XHTML should not attempt to parse these strings, declare them CDATA. /* <![CDATA[ */ window.googleAfmcRequest = { client: '', format: '', output: '', slotname: '', }; /* ]]> *///--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_afmc_ads.js"></script></div> I did try to disable ajax in the code, but I don't think it is because the ad still takes up the entire page... I was thinking that maybe I could start the visitor at a certain page and redirect them to a page that is non-ajax. Now provide the response and nothing else.
Check-out the docs for binding to the mobileinit event: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html Specifically this bit: Because the mobileinit event is triggered immediately upon execution, you'll need to bind your event handler before jQuery Mobile is loaded. Here is the proper format for binding to the mobileinit event: <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc3/jquery.mobile-1.0rc3.min.css" /><script src="http://code.jquery.com/jquery-1.6.4.min.js"></script><script type="text/javascript">$(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false;});</script><script src="http://code.jquery.com/mobile/1.0rc3/jquery.mobile-1.0rc3.min.js"></script> First the jQuery Core (so .bind() will be available), then the mobileinit event handler, then the jQuery Mobile js file (this is last so the event handler for mobileinit will be set before the event is fired). You can test that your current mobileinit event handler is not firing by putting an alert in the function.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8684234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052827/']}
jdg_371015
stackexchange
llm_judgeable_groundtruth_similarity
4592596
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to apply styles to all my divs, except one specific. I'm doing this but it doesn't work: #toolbar div[class~="olControlNavigationHistory"]{ float: left; background-repeat: no-repeat; margin: 2px 12px 2px 12px;} So I need to apply this style to all the divs in #toolbar EXCEPT the div with a class called "olControlNavigationHistory". How can I do this? Is this possible? Now provide the response and nothing else.
Just apply the rule to all divs first: #toolbar div { float: left; background-repeat: no-repeat; margin: 2px 12px 2px 12px;} Then you need to zero the values out for the specific case: #toolbar div.olControlNavigationHistor { float: none; background-repeat: repeat; margin: 0;} Of course this assumes that the property values that specific div would have had without the first rule applied are each properties defaults (such as margin: 0 and float: none .) EDIT: However in the future when CSS3 is supported everywere, you could also just rewrite your original rule as #toolbar div:not(.olControlNavigationHistory) and it would work correctly and elegantly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4592596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552669/']}
jdg_371016
stackexchange
llm_judgeable_groundtruth_similarity
593024
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 an homework question that I can't solve. Solve the following limit: $$\lim_{x \to \infty}\;(x^2+3)^\frac {1}{2}\ - (x^2 + x)^\frac {1}{2}\ $$ Now provide the response and nothing else.
For every $x\in D=(-\infty,-1]\cup[0,\infty)$ we have$$f(x):=\sqrt{x^2+3}-\sqrt{x^2+x}=\frac{(x^2+3)-(x^2+x)}{\sqrt{x^2+3}+\sqrt{x^2+x}}=\frac{3-x}{\sqrt{x^2+3}+\sqrt{x^2+x}}.$$It follows that$$\lim_{x\to\infty}f(x)=\lim_{x\to\infty}\frac{3-x}{\sqrt{x^2+3}+\sqrt{x^2+x}}=\lim_{x\to\infty}\frac{\frac{3}{x}-1}{\sqrt{1+\frac{3}{x}}+\sqrt{1+\frac{1}{x}}}=-\frac12.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/593024', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/94573/']}
jdg_371017
stackexchange
llm_judgeable_groundtruth_similarity
25515431
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to filter a list that contains a timestamp by typing a range of dates for example: JSFIDDLE html <div ng-app="tst"> <div ng-controller="MyController"> <table> <tr> <td>From: <input ng-model="query.date1" type="text" placeholder="" /> </td> <td>To: <input ng-model="query.date2" type="text" placeholder="" /> </td> </tr> <tr ng-repeat="order in orders |filter:query"> <td>{{order.date1 * 1000 | date:'dd-MM-yyyy'}}</td> <td>{{order.date2 * 1000 | date:'dd-MM-yyyy'}}</td> </tr> </table> </div></div> javascript var nameSpace = angular.module('tst',[]);nameSpace.controller('MyController', function MyController($scope) { $scope.orders = [ { "date1":"1306487800", "date2":"1406587800" }, { "date1":"1196487800", "date2":"1406597800" }]}); i want to be able to fill the "From" field with the value : 27-05-2010 and the "To" field the value of : 29-07-2015 and get only the records that are in this range. (the first record in the example). Thanks allotAvi Now provide the response and nothing else.
You can create a custom filter to achieve this aim. JSFIDDLE html <input ng-model="dateFrom" type="text"/><input ng-model="dateTo" type="text"/><tr ng-repeat="order in orders | myfilter:dateFrom:dateTo"> <td>{{order.date1 * 1000 | date:'dd-MM-yyyy'}}</td> <td>{{order.date2 * 1000 | date:'dd-MM-yyyy'}}</td></tr> javascript function parseDate(input) { var parts = input.split('-'); return new Date(parts[2], parts[1]-1, parts[0]); }nameSpace.filter("myfilter", function() { return function(items, from, to) { var df = parseDate(from); var dt = parseDate(to); var result = []; for (var i=0; i<items.length; i++){ var tf = new Date(items[i].date1 * 1000), tt = new Date(items[i].date2 * 1000); if (tf > df && tt < dt) { result.push(items[i]); } } return result; };}); also, i changed the timestamp data type from string to numbres. $scope.orders = [ { "date1": 1306487800, "date2": 1406587800 }, { "date1": 1196487800, "date2": 1406597800 }]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25515431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2924926/']}
jdg_371018
stackexchange
llm_judgeable_groundtruth_similarity
1166179
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: Suppose $A_1,A_2,A_3$ are compact sets in $\mathbb{R}^3$, use Borsuk-Ulam theorem to show that there is one plane $P$ in $\mathbb{R}^3$ that simultaneously divides each $A_i$ into two pieces of equal measures. I believe we should use the corollary of the theorem that says "whenever $S^2$ is expressed as the union of three closed sets $A_1,A_2,A_3$ then at least one of these sets must contain a pair of antipodal points," but I have no idea how to do it, any help is appreciated. Now provide the response and nothing else.
Here's a bit of a rough sketch I hope works, at least in $\mathbb{R}^3$ : Each $s\in S^2$ can be identified with a unit vector in $\mathbb{R}^3$ . For each $s\in S^2$ , you can define $P_i^s$ to be the unique (edit: the plane actually need not be unique, but can by chosen in a systematic way as pointed out in the comments below) plane with normal vector $s$ which divides $A_i$ into two pieces of equal measure. At least in $\mathbb{R}^3$ , I think it's intuitively clear such $P_i^s$ exist. Since the $A_i$ are compact, they are bounded, so by continuously sliding an affine plane along the line determined by $s$ , at some point none of $A_i$ on one side of the plane, but as we slide along, the amount of measure of $A_i$ on that side of the plane increases from none to all. So by the intermediate value theorem, at some point the plane must divide the measure of $A_i$ equally. So let $d_1\colon S^2\to\mathbb{R}$ be the continuous function for which $d_1(s)$ which measures the distance from $P_3^s$ to $P_1^s$ , where the distance is positive (nonnegative, I guess) if we travel in the $s$ direction to get from $P_3^s$ to $P_1^s$ , and negative (nonpositive, I guess) if we travel in the $-s$ direction to get from $P_3^s$ to $P_1^s$ . Likewise define $d_2\colon S^2\to\mathbb{R}$ for the distance from $P_3^s$ to $P_2^s$ . Then define $$\varphi\colon S^2\to\mathbb{R}^2\colon s\mapsto (d_1(s),d_2(s)).$$ This is a continuous map, and $\varphi(-s)=-\varphi(s)$ since changing the direction of $s$ changes the sign of the distance between the planes found above. By Borsuk-Ulam, there exists $s_0\in S^2$ such that $\varphi(s_0)=\varphi(-s_0)$ , which means $d_1(s_0)=-d_1(s_0)$ , so $d_1(s_0)=0$ , and likewise $d_2(s_0)=0$ . This means that the distances from $P_1^{s_0}$ and $P_2^{s_0}$ to $P_3^{s_0}$ are both $0$ , which means all three planes are the same. So there is a single plane which bisects $A_1$ , $A_2$ , and $A_3$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1166179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/189190/']}
jdg_371019
stackexchange
llm_judgeable_groundtruth_similarity
8667
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a data set : Amount of money (100, 50, 150, 200, 35, 60 ,50, 20, 500) . I have Googled the web looking for techniques that can be used to find a possible outlier in this data set but I ended up confused. My question is : Which algorithms, techniques or methods can be used to detect possible outlier in this data set? PS :Consider that the data does not follow a normal distribution. Thanks. Now provide the response and nothing else.
You can use BoxPlot for outlier analysis. I would show you how to do that in Python: Consider your data as an array: a = [100, 50, 150, 200, 35, 60 ,50, 20, 500] Now, use seaborn to plot the boxplot: import seaborn as snsn.boxplot(a) So, you would get a plot which looks somewhat like this: Seems like 500 is the only outlier to me. But, it all depends on the analysis and the tolerance level of the analyst or the statistician and also the problem statement. You can have a look at one of my answers on the CrossValidated SE for more tests. And there are several nice questions on outliers and the algorithms and techniques for detecting them. My personal favourite is the Mahalanobis distance technique .
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/8667', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/13132/']}
jdg_371020
stackexchange
llm_judgeable_groundtruth_similarity
80751
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 have read What is killing my MOSFETs which seems to present a similar circuit to mine (my secondary is center tapped as well and has 2 high-speed diodes rectifying into a 10R / 400uF load) The transformer is 12:1, my power supply voltage is between 10v and 25v at ~300mA. The transistors are heating due to what I believe is avalanche breakdown. I have used 50V devices and the scope shot shows ~200V devices. In each case, DS voltage rings up to breakdown (if there is sufficient energy in the circuit). I would like to push 10 and ideally 100W through this circuit. I realize the breadboard is not feasible for a 100W design, but it should do 10. The ringing is at 2.x MHz. The power supply input capacitors are not low-esr or particularly high valued. Now provide the response and nothing else.
It is because of the center tap. Look at the left part of the transformer only. You have two inductors in series. When you pull one inductor to ground a current starts to flow and the other (magnetically coupled) inductor will try to induce the same current, pushing the other transistor's drain voltage up until it breaks down.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/80751', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/26187/']}
jdg_371021
stackexchange
llm_judgeable_groundtruth_similarity
2877996
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: Background Information: I am new to linear algebra, and I recently came across this homework question that I am confused about. I appreciate any explanation that can help me improve my solution. Question: What condition on the entries of a 2x2 matrix A means Tr(A) = det(A)? Providetwo distinct examples of 2x2 matrices which satisfy this. My approach (Not Complete): Considering the following 2 x 2 matrix, the det(A) = 4, and Tr(A) = 4 \begin{bmatrix} 2 & 0\\ 0 & 2\end{bmatrix} However, considering this 2 x 2 matrix, the det(A) = 9, and Tr(A) = 6 \begin{bmatrix} 3 & 0\\ 0 & 3\end{bmatrix} I think the condition would be having 2 x 2 matrix such that the matrix is (symmetric) and (n = 2). \begin{bmatrix} n & 0\\ 0 & n\end{bmatrix} My solution makes sense, but I feel it is incomplete. Am I missing a key point or a concept that I can add to my answer? Edited: I have tried this solution with so many numbers and it seems to work. Would this be an acceptable solution? \begin{bmatrix} a & b\\ c & d\end{bmatrix} such that a = c = d and b = c - 2, so here is an example \begin{bmatrix} 5 & 3\\ 5 & 5\end{bmatrix} det(A) = 25 - 15 = 10 , and Tr(A) = 5 + 5 = 10 Now provide the response and nothing else.
consider below matrix$$M= \begin{bmatrix} a & b \\ c & d\\ \end{bmatrix}$$the trace will be: $$Tr(M)=a+d$$ and the determinant :$$det(m)=(ad-bc)$$ then according to your problem: $$a+d=ad-bc$$ so chose a and d arbitrary and then chose b and c in the way that the above equation will hold. for example: $$a=10,d=20 $$ bc=170 and you can choose:$$ b=17 ,c=10$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2877996', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/416511/']}
jdg_371022
stackexchange
llm_judgeable_groundtruth_similarity
2219924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is some jQuery for a search box that I expect is actually an antipattern, and am sure there is a much better solution for that I would love to be pointed towards: I will describe it in comments then just give the code, since the comments may be more clear and simple than the code: // set up a function call on keypress. // function call has a delay before the main event occurs. // When keypress function is called, wipe any previously queued events and make a new one at the standard delay rate. // Use a global to store the setTimeout pointer. // clearTimeout any pre-existing pointers. // Start a new delay. The Code: // set up a filter function call on keypress. $('#supplier-select-filter').keypress(function (){ // Currently, resets a delay on an eventual filtering action every keypress. filterSuppliers(.3, this); }); // Delayed filter that kills all previous filter request. function filterSuppliers(delay, inputbox){ if(undefined != typeof(document.global_filter_trigger)){ clearTimeout(document.global_filter_trigger); // clearTimeout any pre-existing pointers. } // Use a global to store the setTimeout pointer. document.global_filter_trigger = setTimeout(function (){ var mask = $(inputbox).val(); $('#user_id').load("supplier.php?action=ajax_getsuppliers_html&mask="+escape(mask)); }, 1000*delay); // Finally, after delay is reached, display the filter results. } The problems: On an input box where a search term may consist of 10 characters on average, that's 10 calls to setTimeout in a half a second, which seems to be processor heavy, and in my testing is causing some noticeable performance issues, so hopefully there's a cleaner alternative? .load() is simpler than taking in JSON and then generating html from the json, but maybe there is a better tool? .keypress() doesn't seem to always trigger on things like backspace deletion and other essentials, so perhaps using keypress() on this input box isn't the ideal? Now provide the response and nothing else.
I frequently use the following approach, a simple function to execute a callback, after the user has stopped typing for a specified amount of time:: $(selector).keyup(function () { typewatch(function () { // executed only 500 ms after the last keyup event. }, 500);}); Implementation: var typewatch = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); };})(); I think this approach is very simple, and it doesn't imply any global variables. For more sophisticated usages, give a look to the jQuery TypeWatch Plugin .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2219924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69993/']}
jdg_371023
stackexchange
llm_judgeable_groundtruth_similarity
18053914
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 Java - what is the faster way to find if the given integer number is starting with the digit 2 without having to convert the number into a string? String.valueOf(number).charAt(0) == '2' Now provide the response and nothing else.
If you wanted to avoid converting it to a string, you could just keep dividing by 10 to find the most significant digit: int getMostSignificantDigit(int x){ // Need to handle Integer.MIN_VALUE "specially" as the absolute value can't // represented. We can hard-code the fact that it starts with 2 :) x = x == Integer.MIN_VALUE ? 2 : Math.abs(x); while (x >= 10) { x = x / 10; } return x;} I don't know whether this would be faster than Husman's log/pow approach.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18053914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2652406/']}
jdg_371024
stackexchange
llm_judgeable_groundtruth_similarity
31931
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Usual decision trees are directed acyclic graphs. Are there generalizations of decision trees that contain cycles analogously to recurrent neural networks? If such trees exist, can they be applied to sequences of variable length? I could not find information about such trees. Or their existence is impossible of infeasible? Now provide the response and nothing else.
Premise :The confusion matrix that you mention above is only correct if there is as much Positive and Negative cases in the data we use a random classifier that assigns Positive and Negative class both with probability 0.5 So you derive the confusion matrix for a very particular random classifier for a very particular dataset. This very particular random classifier is indeed, as you point out, only a point in the ROC plot. To obtain the whole ROC curve, we have to vary the probability with which we assign the positive class, from 0 to 1. So in effects, the ROC curve is a graphical evaluation of the performance of infinitely many classifiers! Each one of these random classifiers with a different probability will have a different expected confusion matrix. Derivation : Here I derive the AUC of a random classifier on a dataset with an arbitrary class imbalance. Assuming that there is a fraction $x$ of positive cases and a fraction $1-x$ of negative cases, and that our classifier consists of randomly assigning the positive class with probability $\rho$ and the negative class with probability $1-\rho$ . The confusion matrix of a random classifier will have the following expected proportions $$TP = \rho x \\ FP = \rho (1-x) \\ FN = (1-\rho)x \\ TN = (1-\rho)(1-x)$$ Then we calculate the True Positive Rate (sensitivity) and False Positive Rate (1-specificity) of our random classifier $$TPR=\frac{TP}{TP+FN}=\frac{\rho x}{\rho x + (1-\rho)x}=\rho\\ FPR=\frac{FP}{TN+FP}=\frac{\rho(1-x)}{\rho(1-x)+(1-\rho)(1-x)}=\rho$$ So as you can see TPR and TFR do not depend on the class proportion $x$ , which means that the ROC-AUC will also be independent of $x$ . Moreover TPR=FPR, meaning that the ROC-curve will look like a straight line from (0,0) to (1,1). Now we calculate the AUC as the integral between 0 and 1 of the area under TPR as a function of FPR as we vary the threshold $\rho$ . $$AUC=\int_0^1 \rho d\rho' = \frac{\rho'^2}{2}|_0^1 = 1/2$$ So the area under the ROC curve for a random classifier is 0.5 regardless of the class proportion.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/31931', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/51836/']}
jdg_371025
stackexchange
llm_judgeable_groundtruth_similarity
36895396
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to find the best solution to convert an entire Spark dataframe to a scala Map collection. It is best illustrated as follows: To go from this (in the Spark examples): val df = sqlContext.read.json("examples/src/main/resources/people.json")df.show+----+-------+| age| name|+----+-------+|null|Michael|| 30| Andy|| 19| Justin|+----+-------+ To a Scala collection (Map of Maps) represented like this: val people = Map(Map("age" -> null, "name" -> "Michael"),Map("age" -> 30, "name" -> "Andy"),Map("age" -> 19, "name" -> "Justin")) Now provide the response and nothing else.
I don't think your question makes sense -- your outermost Map , I only see you are trying to stuff values into it -- you need to have key / value pairs in your outermost Map . That being said: val peopleArray = df.collect.map(r => Map(df.columns.zip(r.toSeq):_*)) Will give you: Array( Map("age" -> null, "name" -> "Michael"), Map("age" -> 30, "name" -> "Andy"), Map("age" -> 19, "name" -> "Justin")) At that point you could do: val people = Map(peopleArray.map(p => (p.getOrElse("name", null), p)):_*) Which would give you: Map( ("Michael" -> Map("age" -> null, "name" -> "Michael")), ("Andy" -> Map("age" -> 30, "name" -> "Andy")), ("Justin" -> Map("age" -> 19, "name" -> "Justin"))) I'm guessing this is really more what you want. If you wanted to key them on an arbitrary Long index, you can do: val indexedPeople = Map(peopleArray.zipWithIndex.map(r => (r._2, r._1)):_*) Which gives you: Map( (0 -> Map("age" -> null, "name" -> "Michael")), (1 -> Map("age" -> 30, "name" -> "Andy")), (2 -> Map("age" -> 19, "name" -> "Justin")))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36895396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5986461/']}
jdg_371026
stackexchange
llm_judgeable_groundtruth_similarity
274757
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was trying to do some clean up by: Deleting some of my useless * posts. Voting to delete oldest questions which I voted to close, and is closed as not useful for future readers ( Like the ones i targeted in this feature request ). As per my current reputation, I have 6 delete votes per day. To my surprise, when I tried voting to delete old typo questions after deleting 5 of my own useless * posts, I realized that I have only 1 delete vote left for the day. For me, this doesn't make sense because: The privilege description says: At 10,000 reputation, you can cast 5 delete votes per day. An additional vote is granted per 1000 reputation, to a maximum of 30 delete votes per day. All users whether they have deletion privilege or not are allowed to delete 5 of their own posts per day, as far as I know. The description also says: When should I delete questions? Closed questions that are of no lasting value whatsoever should be flagged and deleted Why does deleting my own posts ( useless *) consume the 5 delete votes granted to me..? Aren't those meant to vote for deleting useless closed questions, as the privilege description says? * Useless in the sense, very old answers to too localized questions which isn't accepted, has no upvotes where there is an already accepted or upvoted answer better than mine* Now provide the response and nothing else.
Short answer: because the accounting of delete votes is a buggy mess. Although this is not obvious, each 10K users has two kinds of delete votes: all-purpose delete votes (their number depends on reputation) self-delete votes (five; these are available under 10K too) The current behavior is that the software uses all-purpose delete votes as long as you have them, even if you are deleting your own post. You can avoid wasting the delete votes on self-deletion if you postpone self-deletions until you have no all-purpose votes left. This behavior is also buggy. Today I used all my all-purpose delete votes (18) on posts by other users (on Math.SE), and then deleted two posts of my own. So I cast 20 in total. Now if I try to delete a post, the pop-up message tells me: (This might be a separate bug report, but the issue is obviously tied to the behavior you describe.)
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/274757', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/2333214/']}
jdg_371027
stackexchange
llm_judgeable_groundtruth_similarity
22805243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to open different files by having a for loop increment a counter, then appending that counter to the filename to be opened, but I'm stuck on how to use strcat to do this. If I understand right, strcat takes 2 strings, but my counter is an int. How can I make it so that it becomes a string? for(a = 1; a < 58; a++) { FILE* inFile; int i; char filename[81]; strcpy(filename, "./speeches/speech"); strcat(filename, a); strcat(filename, ".txt"); Definitely doesn't work since a is an int. When I try casting it to char, because a starts at 1 and goes to 57, I get all the wrong values since a char at 1 is not actually the number 1.. I'm stuck. Now provide the response and nothing else.
You can't cast an integer into a string, that's just not possible in C. You need to use an explicit formatting function to construct the string from the integer. My favorite is snprintf() . Once you realize that, you can just as well format the entire filename in a single call, and do away with the need to use strcat() (which is rather bad, performance-wise) at all: snprintf(filename, sizeof filename, "./speeches/speech%d", a); will create a string in filename constructed from appending the decimal representation of the integer a to the string. Just as with printf() , the %d in the formatting string tells snprintf() where the number is to be inserted. You can use e.g. %03d to get zero-padded three-digits formatting, and so on. It's very powerful.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22805243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2797058/']}
jdg_371028
stackexchange
llm_judgeable_groundtruth_similarity
2339679
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: .dylib is the dynamic library extension on macOS, but it's never been clear to me when I can't / shouldn't use a traditional unix .so shared object. Some of the questions I have: At a conceptual level, what are the main differences between .so and .dylib? When can/should I use one over the other? Compilation tricks & tips (For example, the replacement for gcc -shared -fPIC, since that doesn't work on osx) Now provide the response and nothing else.
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules . Use otool -hv some_file to see the filetype of some_file . Mach-O shared libraries have the file type MH_DYLIB and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo for libfoo.dylib. They can be created by passing the -dynamiclib flag to the compiler. ( -fPIC is the default and needn't be specified.) Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE . They can carry any extension; the extension .bundle is recommended by Apple, but most ported software uses .so for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle flag to the compiler. Both dylibs and bundles can be dynamically loaded using the dl APIs (e.g. dlopen , dlclose ). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded. Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile , NSLinkModule ) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose with dylibs and deprecated the dyld APIs. On ELF systems like Linux, both use the same file format ; any piece of shared code can be used as a library and for dynamic loading. Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above. Additional references: Fink Porting Guide , the basis for this answer (though pretty out of date, as it was written for Mac OS X 10.3). ld(1) and dlopen(3) Dynamic Library Programming Topics Mach-O Programming Topics
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2339679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77846/']}
jdg_371029
stackexchange
llm_judgeable_groundtruth_similarity
15055304
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 enable USB debugging in an Android phone and connect it to Ubuntu, I get a popup like: Unable to mount SAMSUNG_Android Error initializing camera: -60: Could not lock the device How can I disable or ignore the popup? In Windows it works fine; the problem is just in Ubuntu. Now provide the response and nothing else.
The problem is that Ubuntu is yet to support MTP natively. I hope with the next version, Ubuntu 13.04 (Raring Ringtail), they will fix this annoying problem. In the meantime, you can manually add MTP support to your Ubuntu installation's PPA and have seamless access to your Android device. In Terminal , issue: sudo add-apt-repository ppa:langdalepl/gvfs-mtpsudo apt-get update then sudo apt-get install gvfs Restart your computer. You might have to turn on USB Debugging on your Android devices. Next time when you plug it in, there shouldn't be any annoying error popups. It should appear in Nautilus as a single device with the SD card and internal memory as sub folders, not as two mounted devices. Data transfer should work, but you might have a problem accessing the device from some applications, in which case you might want to give Go-mtpfs a try. It requires manual mounting/unmounting the device, (which is done in two clicks) but then everything should be as fast and easy as accessing a normal folder. It works for me. Ubuntu 12.04 (Precise Pangolin), Samsung Galaxy S III and Nexus 7 .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15055304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267679/']}
jdg_371030
stackexchange
llm_judgeable_groundtruth_similarity
2161172
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 regular $n$-gon is constructible by ruler and compass precisely when the odd prime factors of $n$ are distinct Fermat primes. Prove that in this case, $φ(n)$ is a power of $2$. Where $φ(n)$ is Euler's totient function. I am having difficulty with this, I used the hints from here but still can't seem to get it. It would be useful if someone could provide me their version of the proof or tell me what I have done wrong. My attempt:I think $n$ has divisors $1,2^i,2^{2^i}+1,n$ So since $φ(n)$ is multiplicative we can write $φ(2^{2^i}+1)φ(2^i)$ Then using the fact $φ(p^k)=p^{k-1}(p-1)$ I get: $2^{2^i}(2^{2^i}+1)2^{i-1}(2^i-1)$ Then I try to exapand but can't arrive at showing it is a power of two so feel I must be wrong somewhere. Now provide the response and nothing else.
Stirling numbers of the first kind might be useful here, Consider $$m! \sum_{k=m}^\infty (-1)^{k-m} \left[k\atop m\right] \frac{x^k}{k!} = \log^m(1+x)$$ $$\int\limits_0^1 \dfrac{\log^m (1+x)\log^n x}{x}\; dx = m! \sum_{k=m}^\infty (-1)^{k-m} \left[k\atop m\right] \frac{1}{k!} \int^1_0 x^{k-1} \log^n(x)\,dx$$ Now it is easy to see that $$\int^1_0 x^{k-1} \,dx = \frac{1}{k}$$ By differentiation $n$ times with respect to $k$ $$\int^1_0 x^{k-1} \log^n(x)\,dx = (-1)^n\frac{n!}{k^{n+1}}$$ Substituting back we have $$\int\limits_0^1 \dfrac{\log^m (1+x)\log^n x}{x}\; dx =(m!)(n!) \sum_{k=m}^\infty (-1)^{k-m+n} \left[k\atop m\right] \frac{1}{k!\, k^{n+1}}$$ Now the Striling numbers could related to Euler sums through equations like $$\frac{\left[k\atop 3\right]}{k!} =\frac{ (H_{k-1})^2-H^{(2)}_{k-1}}{2k}$$ and $$\frac{\left[k\atop 4\right]}{k!} =\frac{ (H_{k-1})^3-3H^{(2)}_{k-1}H_{k-1}+2H^{(3)}_{k-1}}{6k}$$ I don't think there exist a simple formula but this procedure should work. Case $m=2 , n=2$ $$\int\limits_0^1 \dfrac{\log^2 (1+x)\log^2 x}{x}\; dx =4 \sum_{k=2}^\infty (-1)^{k} \left[k\atop 2\right] \frac{1}{k!\, k^{3}}$$ Note that $$\frac{\left[k\atop 2\right]}{k!} = \frac{H_{k-1}}{k}$$ Hence we deduce that $$\int\limits_0^1 \dfrac{\log^2 (1+x)\log^2 x}{x}\; dx =4 \sum_{k=2}^\infty (-1)^{k} \frac{H_{k-1}}{\, k^{4}}$$ Note that $$\begin{align} \sum_{k=2}^\infty (-1)^{k} \frac{H_{k-1}}{\, k^{4}} &=\sum_{k=2}^\infty (-1)^{k} \frac{H_{k}}{ k^{4}} -\sum_{k=2}^\infty (-1)^{k} \frac{1}{ k^{5}} \\&=\sum_{k=1}^\infty (-1)^{k} \frac{H_{k}}{ k^{4}} -\sum_{k=1}^\infty (-1)^{k} \frac{1}{ k^{5}}\\&= \frac{\zeta(2) \zeta(3)}{2} - \frac{ 29\zeta(5)}{32}\end{align}$$ We deduce that $$\boxed{\int\limits_0^1 \dfrac{\log^2 (1+x)\log^2 x}{x}\; dx = 2\zeta(2) \zeta(3)- \frac{ 29}{8}\zeta(5)}$$ This implies we can represent the special case $m=2$ $$\int\limits_0^1 \dfrac{\log^2 (1+x)\log^n x}{x}\; dx =2 (-1)^n(n!) \left[ \sum_{k=1}^\infty (-1)^{k} \frac{H_k}{ k^{n+2}} + \left(1-2^{-n-2} \right) \zeta(n+3) \right]$$ General formula in terms of nonlinear Euler sums Define $\{ m\}$ as the $l$ partitions of $m$ where $m = i_1r_1+\cdots i_l r_l$ $$ \frac{1}{(m+1)!} \log^{m+1}(1+x) =\sum_{\{m\}} \sum_{k=1}^\infty \prod^l_{j=1}\frac{(-1)^{i_j+1}}{(i_j)!} \left( \frac{H_{k-1}^{(r_j)}}{r_j}\right)^{i_j} \frac{(-x)^k}{k} $$ Substitute back in the integral $$\int\limits_0^1 \dfrac{\log^{m} (1+x)\log^n x}{x}\; dx = (-1)^{n+1}(n!) (m)! \sum_{\{m-1\}} \sum_{k=1}^\infty \frac{(-1)^k}{k^{n+2}} \prod^{l'}_{j=1}\frac{(-1)^{i_j}}{(i_j)!} \left( \frac{H_{k-1}^{(r_j)}}{r_j}\right)^{i_j}$$ Reference: https://arxiv.org/pdf/math/0607514.pdf
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2161172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/386945/']}
jdg_371031
stackexchange
llm_judgeable_groundtruth_similarity
1646324
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f:\mathbb R\to\mathbb R$ be continuous such that $f(\frac{x+y}{2})=\frac{f(x)+f(y)}{2}~\forall~x,y\in\mathbb R.$ How to show that $f$ is a straight line? Now provide the response and nothing else.
The two points $(x,f(x))$ and $(y,f(y))$ are on the graph of $f$. The point on the straight line half-way between them is $\left(\frac{x+y} 2, \frac{f(x)+f(y)} 2 \right)$. The actual point on the graph with abscissa $\frac{x+y}2$ is $\left(\frac{x+y} 2, f\left(\frac{x+y} 2 \right) \right)$. And we are told those two points are the same. Now iterate this: We've shown the conclusion that's it's a straight line is right for $x$ and $y$ and the point $z$ half-way between them: those three points on the graph are on a straight line. Now deal in the same way with the points half-way between $x$ and $z$ (call it $a$), and half-way between $z$ and $y$ (call it $b$). So far we have$$x < a < z < b< y.$$Then half-way between $x$ and $a$; then half-way between $a$ and $z$; then half-way between $z$ and $b$; then half-way between $b$ and $y$. Then further split the resulting intervals in half. Then split the next set of resulting intervals in half. And so on. No matter how long we continue the process, the points we getting by splitting smaller and smaller intervals in half will thus be shown always to lie on a straight line. However, some points between $x$ and $y$ will never be reached by successively splitting in half: the point two-thirds of the way from $x$ to $y$ is one such point. Here we use continuity of the function $f$: that point can be approached as closely as you wish by points that do result from successively splitting intervals in half. Thus the part of the graph between $(x,f(x))$ and $(y,f(y))$ is a straight line. But that is true no matter which two points are chosen to be called $x$ and $y$. Hence the whole graph is a straight line.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1646324', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/311774/']}
jdg_371032
stackexchange
llm_judgeable_groundtruth_similarity
104961
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 multiple files with an example of how they look like shown below. -rw-r--r-- 1 my_user users 12 Dec 13 09:56 Example_30_001_20130913175000.DAT -rw-r--r-- 1 my_user users 12 Dec 13 09:57 Example_30_002_20130913180854.DAT -rw-r--r-- 1 my_user users 12 Dec 13 09:58 Example_30_003_20130913180857.DAT -rw-r--r-- 1 my_user users 12 Dec 13 09:58 Example_30_004_20130913180901.DAT -rw-r--r-- 1 my_user users 12 Dec 13 09:59 Example_30_005_20130913180904.DAT -rw-r--r-- 1 my_user users 12 Dec 13 10:02 Example_30_006_20130913180907.DAT -rw-r--r-- 1 my_user users 12 Dec 13 09:59 Example_30_007_20130913180911.DAT My question is how do I copy them in the same directory and rename the copied files using a sh script such that they start with something like the filenames shown below? Ex_Example_001.DAT Ex_Example_002.DAT Ex_Example_003.DAT Ex_Example_004.DAT Ex_Example_005.DAT Ex_Example_006.DAT Ex_Example_007.DAT Now provide the response and nothing else.
Let's just ask the source code. If you're not interested in the details, just skip to the end to see the result: There is a KCM for setting the default applications. Let's look up its name: $ kcmshell4 --list | ack -i defaultcomponentchooser - Choose the default components for various services NOTE: The following 5 steps are Gentoo specific, but could be applied to any other distribution or could be replaced by browsing through KDE's source repositories manually! Let's search the filesystem for files belonging to the componentchooser : $ find /usr -name "*componentchooser*"/usr/lib64/kde4/kcm_componentchooser.so/usr/share/doc/HTML/en/kcontrol/componentchooser/usr/share/doc/HTML/de/kcontrol/componentchooser/usr/share/kde4/services/componentchooser.desktop/usr/share/apps/kcm_componentchooser/usr/share/locale/de/LC_MESSAGES/kcmcomponentchooser.mo Now we'll query the package manager (in our case Gentoo's Portage) and ask for the package which contains any of these files: $ find /usr -name "*componentchooser*" | xargs qfilekde-base/kdelibs (/usr/share/apps/kcm_componentchooser)kde-base/kcontrol (/usr/share/apps/kcm_componentchooser)kde-base/kcontrol (/usr/share/kde4/services/componentchooser.desktop)kde-base/kcontrol (/usr/share/doc/HTML/en/kcontrol/componentchooser)kde-base/kcontrol (/usr/lib64/kde4/kcm_componentchooser.so)kde-base/kde-l10n (/usr/share/locale/de/LC_MESSAGES/kcmcomponentchooser.mo)kde-base/kde-l10n (/usr/share/doc/HTML/de/kcontrol/componentchooser) As we're looking for the source code which actually writes the value for the default-browser, we should look into the .so file which contains actual code, while the other files just provide documentation ( /usr/share/doc/[…] ), meta-information ( […].desktop ) and translation strings ( /usr/share/locale/[…] ). This means, we'll have to take a look at the package providing the shared-object ( .so ) file, which is kde-base/kcontrol on Gentoo. First, we make sure, the source tarball is present on our filesystem, by asking Portage to download it for this package ( --nodeps ensures, only the sources for this package are downloaded, but not for any dependencies): $ emerge --fetchonly --nodeps kde-base/kcontrol>>> Fetching (1 of 1) kde-base/kcontrol-4.11.4 * kde-runtime-4.11.4.tar.xz SHA256 SHA512 WHIRLPOOL size ;-) ... [ ok ] In this case, the file was already present and just its checksums were verified. Now we're going to unpack this file into a temporary location for examining it further: $ cd /tmp$ tar xf /usr/portage/distfiles/kde-runtime-4.11.4.tar.xz The result is the directory kde-runtime-4.11.4 which we're going to change into now: $ cd kde-runtime-4.11.4 This directory contains now a lot of components belonging to the kde-runtime package of KDE SC. We're interested in the kcontrol component: $ cd kcontrol Now we need to identify the file which contains the source code to write the default browser to kdeglobalsrc . There are different ways to do this: Browse through the directory structure and try to find the file by its name. Look for a file whose name contains something like componentchooser and examine its source code Scan the source code and find directly the file which writes the value BrowserApplication . The shortest path to our goal is option '3', so that's what we're going to do: $ ack BrowserApplicationcomponentchooser/componentchooserbrowser.cpp50: QString exec = config.readPathEntry( QLatin1String("BrowserApplication"), QString("") );92: config.writePathEntry( QLatin1String("BrowserApplication"), exec); // KConfig::Normal|KConfig::Global So obviously in line '92' of the file componentchooser/componentchooserbrowser.cpp , that's were this value is being written, so let's have a closer look at it: 80 void CfgBrowser::save(KConfig *) 81 { 82 KConfigGroup config(KSharedConfig::openConfig("kdeglobals"), QLatin1String("General") ); 83 QString exec; 84 if (radioExec->isChecked()) 85 { 86 exec = lineExec->text(); 87 if (m_browserService && (exec == m_browserExec)) 88 exec = m_browserService->storageId(); // Use service 89 else if (!exec.isEmpty()) 90 exec = '!' + exec; // Literal command 91 } 92 config.writePathEntry( QLatin1String("BrowserApplication"), exec); // KConfig::Normal|KConfig::Global 93 config.sync(); 94 95 KGlobalSettings::self()->emitChange(KGlobalSettings::SettingsChanged); 96 97 emit changed(false); 98 } In line '92', the key BrowserApplication is written and it's value is in the variable exec . The exclamation mark is added to the command string in line '90', but there is no elaborate comment in the code at this line which would explain, why this is done, so let's have a look instead at the code logic which leads to adding an ! in front of the BrowserApplication value: Line '86' sets exec to the string which is provided by the input field Line '87' checks, whether the member variable m_browserService is true and whether the content of the variable exec is the same as the member variable m_browserExec . m_browserService is set ( 0 or 1 ) by the method CfgBrowser::selectBrowser when the default browser is selected by browsing the application tree instead of entering the executable name directly as string. In case the browser is selected by browsing the application tree, the content of the input field is the name of the applications *.desktop file. m_browserExec is the name of the *.desktop file when selecting the browser via the application tree. In case both statements evaluate to TRUE , exec is set to the result of storageId (the name of the *.desktop entry). Otherwise, the name of the executable file is set, but it is prepended by an ! . To make it short: The exclamation mark for the BrowserApplication entry in kdeglobalsrc is used to distinguish between an actual binary name to be executed for launching the browser or the name of a browser's *.desktop file.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/104961', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/54476/']}
jdg_371033
stackexchange
llm_judgeable_groundtruth_similarity
1724
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We touched on introns and exons in my bio class, but unfortunately we didn't really talk about why Eukaryotes have introns. It would seem they would have to have some purpose since prokaryotes do not have them and they evolved first chronologically, but I could easily be wrong. Did the junk sections of DNA just evolve there by some sort of randomness or necessity as opposed to an actual evolutionary advantage? Why hasn't evolution stopped us from having introns since they seem to be a 'waste' of time and DNA? Why do prokaryotes not have introns? Now provide the response and nothing else.
There is still a lot to be learned about the roles introns play in biological processes, but there are a couple of things that have been pretty well established. Introns enable alternative splicing , which enables a single gene to encode multiple proteins that perform different functions under different conditions. For example, a signal the cell receives could cause an exon that is normally included to be skipped, or an intron that is normally spliced out to be left in for translation (the Wikipedia article on the subject has a basic overview of the possibilities). This would not be possible, or at least would be much more difficult, without the presence of introns. In recent years, we have discovered that RNA molecules (especially small RNAs such as siRNAs and miRNAs) are much more involved in regulating gene expression than previously thought. Often the small regulatory RNAs are derived from spliced introns. There is probably more, but essentially introns enable a finer level of regulatory control. Biological complexity is often not the result of having a larger complement of genes, but of having additional layers of regulation to turn genes on and off at the right times. Prokaryotic genes are often organized into operons, and a single polycistronic mRNA will often encode multiple proteins from multiple adjacent genes. Since the biological processes required to sustain microbial life are much less complicated than those required to sustain eukaryotic life, they can get away with much less regulatory control.
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/1724', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/62/']}
jdg_371034
stackexchange
llm_judgeable_groundtruth_similarity
16453644
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 Pandas DataFrame with a date column (eg: 2013-04-01 ) of dtype datetime.date . When I include that column in X_train and try to fit the regression model, I get the error float() argument must be a string or a number . Removing the date column avoided this error. What is the proper way to take the date into account in the regression model? Code data = sql.read_frame(...)X_train = data.drop('y', axis=1)y_train = data.yrf = RandomForestRegressor().fit(X_train, y_train) Error TypeError Traceback (most recent call last)<ipython-input-35-8bf6fc450402> in <module>()----> 2 rf = RandomForestRegressor().fit(X_train, y_train)C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight) 292 X.ndim != 2 or 293 not X.flags.fortran):--> 294 X = array2d(X, dtype=DTYPE, order="F") 295 296 n_samples, self.n_features_ = X.shapeC:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy) 78 raise TypeError('A sparse matrix was passed, but dense data ' 79 'is required. Use X.toarray() to convert to dense.')---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order) 81 _assert_all_finite(X_2d) 82 if X is X_2d and copy:C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order) 318 319 """--> 320 return array(a, dtype, copy=False, order=order) 321 322 def asanyarray(a, dtype=None, order=None):TypeError: float() argument must be a string or a number Now provide the response and nothing else.
The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by DictVectorizer ). Here are some features that can be extracted from a date: hour of the day (24 boolean features) day of the week (7 boolean features) day of the month (up to 31 boolean features) month of the year (12 boolean features) year (as many boolean features as they are different years in your dataset)... That should make it possible to identify linear dependencies on periodic events on typical human life cycles. Additionally you can also extract the date a single float: convert each date as the number of days since the min date of your training set and divide by the difference of the number of days between the max date and the number of days of the min date. That numerical feature should make it possible to identify long term trends between the output of the event date: e.g. a linear slope in a regression problem to better predict evolution on forth-coming years that cannot be encoded with the boolean categorical variable for the year feature.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16453644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/741099/']}
jdg_371035
stackexchange
llm_judgeable_groundtruth_similarity
2251364
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 $X$ and $Y$ be two independent identically distributed random variables with finite expectation $\Bbb{E}(X) = \Bbb{E}(Y) < \infty$. Prove that $$\Bbb{E}(|X-Y|) \le \Bbb{E}(|X+Y|)$$ I think that this inequality may follow somehow from Jensen's inequality , but I failed to use it here. Or maybe it is worth considering an expression $|x+y|-|x-y|$ and making use of some of its properties? I am interested to see a proof of this fact or some favorable ideas that may help here. Any suggestions would be greatly appreciated. Now provide the response and nothing else.
Taking integration by parts to the Dirichlet integral , it is easy to check that $$ \int_{-\infty}^{\infty} \frac{1-\cos(at)}{t^2} \, dt = \pi|a|. \tag{1}$$ Taking advantage of the fact that the integrand of $\text{(1)}$ is non-negative, by the Tonelli's theorem , for any real-valued random variable $Z$ we have $$ \pi \Bbb{E}[|Z|] = \Bbb{E}\left[ \int_{-\infty}^{\infty} \frac{1-\cos(Zt)}{t^2} \, dt \right] = \int_{-\infty}^{\infty} \frac{1-\Bbb{E}[\cos(Zt)]}{t^2} \, dt. $$ Therefore \begin{align*}\pi \Bbb{E}[|X+Y| - |X-Y|]&= \int_{-\infty}^{\infty} \frac{\Bbb{E}[\cos((X-Y)t)-\cos((X+Y)t)]}{t^2} \, dt \\&= \int_{-\infty}^{\infty} \frac{\Bbb{E}[2\sin(Xt)\sin(Yt)]}{t^2} \, dt \\&= \int_{-\infty}^{\infty} \frac{2\Bbb{E}[\sin(Xt)]^2}{t^2} \, dt \\&\geq 0.\end{align*} Moreover, notice that the equality holds if and only if $\Bbb{E}[\sin(Xt)] = 0$ for all $t$. This means that the c.f. $\varphi_X(t) = \Bbb{E}[e^{itX}]$ is real-valued, which is equivalent to the symmetry condition: $X \stackrel{d}{=} -X$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2251364', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/434944/']}
jdg_371036
stackexchange
llm_judgeable_groundtruth_similarity
8443820
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to add more than one x-axis to a plot in R? And to put an annotation next to each scale? Edit > here's the result of Nick Sabbe idea. For the annotation (a little text at the left of each axis), is it possible ? Now provide the response and nothing else.
You can use the line argument of axis() to place an axis higher or lower, this way you can make multiple axes. With mtext() you can then add a label to the side. Do note that the plot itself is only on one scale so you need to rescale the points and labels of the other scale accordingly: # Plot and first axis:plot(1:10,1:10,bty="n",col="red",pch=16,axes=FALSE,xlab="",ylab="")axis(2,0:11,las=1)axis(1,0:11,line=1,col="red",col.ticks="red",col.axis="red")mtext("Label 1",1,line=1,at=0.2,col="red")# Secondary points and axis:points(rnorm(10,50,20)/10, rnorm(10,5,2),pch=16, col="blue" )axis(1,0:11,labels=0:11*10,line=3,col="blue",col.ticks="blue",col.axis="blue")mtext("Label 2",1,line=3,at=0.2,col="blue")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8443820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025741/']}
jdg_371037
stackexchange
llm_judgeable_groundtruth_similarity
8619883
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 a singleTop Activity to receive intents from a search-dialog via onNewIntent() . What I noticed is that onPause() is called before onNewIntent() , and then afterwards it calls onResume() . Visually: search dialog initiated search intent fired to activity onPause() onNewIntent() onResume() The problem is that I have listeners registered in onResume() that get removed in onPause() , but they are needed inside of the onNewIntent() call. Is there a standard way to make those listeners available? Now provide the response and nothing else.
onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate() . From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent() . I suggest you to rewrite your activity to not use these listeners inside of onNewIntent() . For example most of the time my onNewIntent() methods simply looks like this: @Overrideprotected void onNewIntent(Intent intent) { super.onNewIntent(intent); // getIntent() should always return the most recent setIntent(intent);} With all setup logic happening in onResume() by utilizing getIntent() .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8619883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155949/']}
jdg_371038
stackexchange
llm_judgeable_groundtruth_similarity
3790650
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to do an "empty list to visibility converter" for WPF.This is an IValueConverter that takes an object ( that should be a list ) and if the list is empty (or if the passed object is null ) it should return Visibility.Collapsed; if the list is not empty it should return Visibility.Visibile; I plan to use this for a datagrid. The plan is to make the datagrid invisible (collapsed) whenever the list given to the ItemsSource is an empty list or a null. <my:DataGrid Name="dataGridAuxiliaryTools" Style="{StaticResource DataGridStyle}" CellStyle="{StaticResource DataGridCellStyle}" ColumnHeaderStyle="{StaticResource DataGridColumnHeaderStyle}" ItemsSource="{Binding Path=Items}" IsReadOnly="False" Visibility="{Binding Path=Items, Converter={StaticResource emptyListToVisibilityConverter}}" </my:DataGrid> I wrote the EmptyListToVisibilityConverter as follows: public class EmptyListToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return Visibility.Collapsed; } else if (value is IList<Object>) { if ((value as IList<Object>).Count == 0) { return Visibility.Collapsed; } else { return Visibility.Visible; } } else { return Visibility.Visible; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } This works well when Items is given as null but when Items is given as a List it does not work ... I think that the code bellow is not correct and cannot detect if "value" is a list or not ... Any hints ? if (value is IList<Object>) { if ((value as IList<Object>).Count == 0) { return Visibility.Collapsed; } else { return Visibility.Visible; } Any hints on how to do this ? Now provide the response and nothing else.
You can't cast your list to IList <Object>, but you can cast it to ICollection, and then use ICollection.Count : see http://devw.wordpress.com/2011/07/18/empty-list-visibility-converter/ public class EmptyListVisibilityConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return Visibility.Collapsed; else { ICollection list = value as ICollection; if (list != null) { if (list.Count == 0) return Visibility.Collapsed; else return Visibility.Visible; } else return Visibility.Visible; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); }}<ListBox x:Name=”NameChoiceListBox” ItemsSource=”{Binding NamesList}” SelectedItem=”{Binding SelectedName, Mode=TwoWay}” ItemTemplate=”{StaticResource DataTemplateNameChoice}” Visibility=”{Binding NamesList, Converter={StaticResource EmptyListVisibilityConverter}}”>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3790650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275289/']}
jdg_371039
stackexchange
llm_judgeable_groundtruth_similarity
12667926
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 per the default behavior, alt attribute is rendered first time just before the image rendering. I am displaying 25 images in a grid so it looks bit awkward as all alt attributes are displayed first. Is it possible to hide alt attributes in Firefox? Note: alt attributes contain dynamic names in my case. Now provide the response and nothing else.
The way to prevent alt attribute values from being displayed is to remove the attribute. The meaning of an alt attribute (not tag) is that it specifies an alternative, a substitute for the image, in situations where the image is not displayed. So if you want to hide it when the image has not yet been loaded, you are asking for behavior that contradicts the very meaning of the attribute. You can however make the alt text invisible (with the usual CSS Caveats) on Firefox by setting e.g. img { background: white; color: white; } in CSS. This implies that the alt texts are invisible also in case the browser never gets the image, or the browser has been configured not to display images.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12667926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592298/']}
jdg_371040