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
239523
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am surprised that R’s glm will “break” (not converge with default setting) for the following “toy” example (binary classification with ~50k data, ~10 features), but glmnet returns results in seconds. Am I using glm incorrectly (for example, should I set max iteration, etc.), or is R’s glm not good for big data setting? Does adding regularization make a problem easy to solve? d=ggplot2::diamondsd$price_c=d$price>2500d=d[,!names(d) %in% c("price")]lg_glm_fit=glm(price_c~.,data=d,family = binomial())library(glmnet)x=model.matrix(price_c~.,d)y=d$price_clg_glmnet_fit=glmnet(x = x,y=y,family="binomial", alpha=0)Warning messages:1: glm.fit: algorithm did not converge 2: glm.fit: fitted probabilities numerically 0 or 1 occurred EDIT:Thanks for Matthew Drury and Jake Westfall's answer. I understand the perfect separation issue which is which is already addressed. How to deal with perfect separation in logistic regression? And in my original code, I do have the third line which drops the column that derives the label. The reason I mention about "big data" is because in many "big data" / "machine learning" settings, people may not carefully test assumptions or know if data can be perfectly separated. But glm seems to be easily broken with "unfriendly" messages, and there is not a easy way to add the regularization to fix it. Now provide the response and nothing else.
The unregularized model is suffering from complete separation because you are trying to predict the dichotomized variable price_c from the continuous variable price from which it is derived. The regularized model avoids the problem of complete separation by imposing a penalty that keeps the coefficient for the price predictor from going off to $\infty$ or $-\infty$. So it manages to converge fine and work well. You should remove the continuous price predictor from the design matrix in this toy example. Edit: As @Erik points out, the continuous price predictor is already removed from the design matrix, which I somehow missed. So the complete separation arises from some other predictor or combination of predictors. It's also worth adding that, of course, none of these issues have anything to do with the particular implementation of logistic regression in R's glm() function. It is simply about regularized vs. unregularized logistic regression.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/239523', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/113777/']}
jdg_381441
stackexchange
llm_judgeable_groundtruth_similarity
526742
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Simple question, but for some reason I couldn't find the exact answer on Google: I have a fresh Ubuntu install on Slicehost, and would like to make a public directory in my home dir for a simple website containing a bunch of static HTML files. How do I do this? Is it just a matter of typing mkdir public_html and setting the permissions, or is there a cleaner way? (I remember in the past I've had issues where every time I copied a file into my public_html directory, I would have to manually set its permissions, which was quite frustrating.) Now provide the response and nothing else.
Assuming you've already installed apache, do the following: sudo a2enmod userdirsudo service apache2 reload The first command enables the userdir apache mod, which does exactly what you want. The second reloads apache configurations so that it starts using the new configuration. To install apache2: sudo apt-get install apache2 Of course, you'll also need to make sure that the permissions on your public_html folder allow the www-data user to see the files in there -- 755 usually works well. To do this: mkdir ~/public_htmlchmod -R 755 ~/public_html This will recursively (-R) go through your public_html and set the permissions to 755 (owner rwx, and both group and other r-x, r-x).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/526742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38146/']}
jdg_381442
stackexchange
llm_judgeable_groundtruth_similarity
10584580
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a project with a bunch of C++ header files that follow the standard C++ header naming convention; that is, a class called Foo would be declared in a file called Foo , not Foo.h or Foo.hh . Is there a good way to configure vim to do syntax highlighting for these files only? A slightly-less-pleasing fallback would be to enable C++-style highlighting for all files that don't have an extension. I'm not sure if there's any more sophisticated way to detect the type of file instead of relying solely on its extension. Now provide the response and nothing else.
You can use the modeline feature for this. Modelines allow you to set certain options from within a comment in the first/last few lines of your file. This makes it a great place to set parameters for coding guidelines, folding. Some options cannot be set for security reasons. See the documentation for more information. Put this at the top or bottom of the file: /* vim: set ft=cpp: */ EDIT: More details, prompted by the comments :) : It will only work if modeline is enabled. In normal circumstances it should be by default. To make sure it is enabled, or to change the size of the area it is detected in, set the modeline option in your .vimrc : set modelines=5 will make sure the line like the one quoted above will be detected in the first five or the last five lines of each file. Inside the modeline, setlocal means to set options for the buffer the file is loaded in. The ft option, also known as filetype , is what determines the syntax highlighting language. The value cpp is the one that is used by C++ files. EDIT 2: Without the modeline, with a bit more work, if you can identify a magic pattern: au BufRead * if search('MagicPattern', 'nw') | setlocal ft=cpp | endif Meaning: Every time you open a file, check if "MagicPattern" is in there. If it is, treat it as C++. The pattern argument is in vim dialect of regular expressions; check help pattern for details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10584580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/919747/']}
jdg_381443
stackexchange
llm_judgeable_groundtruth_similarity
19562
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: The divisor function $d(n)$, is the number of $(a,b)\in\mathbb {N^+}^2$ such that $a\times b =n$.For example, $d(2)=2$ because $2=1\times 2=2\times 1$ and d(6)=4 because $6=1\times 6=2\times 3=3\times 2=6\times 1$. The divisor summatory function is defined by :$$D(n)=\sum_{i=1}^n d(i)$$ This is sequence A006218 in OEIS. Does anyone know the best time complexity algorithm to compute this function ? Are they any results published on the computational complexity of this function ? Now provide the response and nothing else.
Based on a "folkore intuition" for a related problem, one might expect this to be at least as hard as factoring: The folkore intuition suggests that computing the number of prime factors, or even computing essentially any useful information about the prime factorization, is as hard as factoring itself (see Tao's answer to this related question ). $d(n)$ gives you exactly such information, and is essentially equivalent (from the computational perspective) to computing $D(n)$, since $d(n) = D(n) - D(n-1)$. For example, if $n$ is squarefree, then $d(n)$ is equal to $2^{f}$ where $f$ is the number of prime factors. For general $n$, $d(n)$ is $\prod_{p} (m_p + 1)$ where $m_p$ is the number of times the prime $p$ divides $n$ (that is, $n = \prod_{p} p^{m_p}$ is the prime factorization of $n$).
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/19562', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/10151/']}
jdg_381444
stackexchange
llm_judgeable_groundtruth_similarity
226812
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Our old 2003 mail server has died, and we are hastily setting up a new one based on Exchange 2010. We looking for a way to recover the 2003 data into 2010, any idea if possible? Thanks. Now provide the response and nothing else.
Edit: Woah there! You say you've lost your Active Directory. That changes things considerably. I would still look long and hard at restoring a System State Backup (if you've got one) because you'll get back your AD in the process (and won't have to rejoin all your client computers to the domain, deal with user profiles, etc). If you can't get AD back then I'd proceed with a "dialtone" strategy-- building a new environment and importing the old mail later. I'd try like heck to get AD back, though, first. Doing the "same domain name, same server name" won't work to get Exchange 2003 to mount the databases. It needs to be the same AD in order to perform a disaster recovery Exchange installation. Why not just do an orderly disaster recovery of your Exchange 2003 environment and then an orderly upgrade to Exchange 2010? It seems like you're buying yourself years of future nightmares (with mismatched legacyExchangeDN values) by not just approaching this in an orderly, stable manner. You can bring up another Exchange 2003 machine with the same computer name as the failed server (running Exchange 2003 "setup /DisasterRecovery" and "update /DisasterRecovery" on your applicable Exchange service pack) and then restore the database backups you have (or copy EDB and STM files over from the failed machine into the same drive-letter / path on the recovery server) and have Exchange 2003 back up and running ASAP and ready to migrate to E2K10. Here's a link from Microsoft to help: http://technet.microsoft.com/en-us/library/aa998965(EXCHG.65).aspx If you've got the Active Directory that hosted the failed Exchange organization then really it's just a matter of: Spin up a Windows Server 2003 machine (w/ service packs, etc) with the same computer name as the failed server computer Partition the disks to allow the same drive letter / path that the current STM / EDB files are stored in to be accessible (not required but makes life easier) Install Exchange 2003 in "/DisasterRecovery" mode Apply the same Exchange service packs and hot fixes (in "/DisasterRecovery" mode for service packs, as well) to the new Exchange 2003 machine Copy in the EDB / STM files from the failed Exchange installation (the entire "mdbdata" folder, if you were storing everything together) or restore your last backup to the new server Whine: It puzzles me why people act rashly during a crisis and make a bigger mess than they already have.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/226812', 'https://serverfault.com', 'https://serverfault.com/users/13323/']}
jdg_381445
stackexchange
llm_judgeable_groundtruth_similarity
33264017
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 seen the following code: template <class T>class Type { public: Type() {} T& operator=(const T& rhs) {value() = rhs; return value();} T& value() {return m_value;} T value() const {return m_value;} private: T m_value;}; Why does the compiler not complain about T& value() {return m_value;} T value() const {return m_value;} and how to know which one is invoked? Now provide the response and nothing else.
The two functions are actually not the same. Only the second function is declared as a const member function. If the object that the member is called from is const , the latter option is used. If the object is non- const , the first option is used. Example: void any_func(const Type *t){ something = t->value(); //second `const` version used}void any_func2(Type *t){ something = t->value(); //first non-`const` version used} If both functions were declared non- const or both were declared const , the compiler would (should, anyway) complain.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33264017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5354436/']}
jdg_381446
stackexchange
llm_judgeable_groundtruth_similarity
1074589
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a reason I am missing that a block within a case statement isn't considered a block level declaration space? I keep getting an error (variable has already been declared) when I try case x: var someVariable = 42;break;case y: var someVariable = 40;break; but I can do case x: try{var someVariable = 42;}catch{} break;case y: try{var someVariable = 40;}catch{}break; If C# allowed fall through statements, that would make sense, but it doesn't, and I can't think of a scenario where you can declare a variable in a case statement and use it outside of that block. Now provide the response and nothing else.
UPDATE: This question was used as the inspiration for this blog post; see it for further details. http://ericlippert.com/2009/08/13/four-switch-oddities/ Thanks for the interesting question. There are a number of confusions and mis-statements in the various other answers, none of which actually explain why this is illegal. I shall attempt to be definitive. First off, to be strictly correct, "scope" is the wrong word to use to describe the problem. Coincidentally, I wrote a blog post last week about this exact mis-use of "scope"; that will be published after my series on iterator blocks, which will run throughout July. The correct term to use is " declaration space ". A declaration space is a region of code in which no two different things may be declared to have the same name . The scenario described here is symptomatic of the fact that a switch section does not define a declaration space, though a switch block does. Since the OP's two declarations are in the same declaration space and have the same name, they are illegal. (Yes, the switch block also defines a scope but that fact is not relevant to the question because the question is about the legality of a declaration , not the semantics of an identifier lookup .) A reasonable question is "why is this not legal?" A reasonable answer is "well, why should it be"? You can have it one of two ways. Either this is legal: switch(y){case 1: int x = 123; ... break;case 2: int x = 456; ... break;} or this is legal: switch(y){case 1: int x = 123; ... break;case 2: x = 456; ... break;} but you can't have it both ways. The designers of C# chose the second way as seeming to be the more natural way to do it. This decision was made on July 7th, 1999, just shy of ten years ago. The comments in the notes from that day are extremely brief, simply stating " A switch-case does not create its own declaration space " and then giving some sample code that shows what works and what does not. To find out more about what was in the designers minds on this particular day, I'd have to bug a lot of people about what they were thinking ten years ago -- and bug them about what is ultimately a trivial issue; I'm not going to do that. In short, there is no particularly compelling reason to choose one way or the other; both have merits. The language design team chose one way because they had to pick one; the one they picked seems reasonable to me.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1074589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1942/']}
jdg_381447
stackexchange
llm_judgeable_groundtruth_similarity
35322
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: Apolgies if this has been asked and answered, but I'm not even sure what to search for. I have two functions defined as follows: F[n_]:=Max[Select[Divisors[n],#<=Sqrt[n]&]];P[n_] := Select[Range[1, 1000], F[#] == n &]; I have two questions: I have read the Mathematica help page on the # symbol, and I think I understand most of that. I do not, however, understand what # and & do in this specific context. How can I write P[n_ ] using a single line of code? It doesn't work if I simply copy and paste the definition for F into the definition of P: P[n_] := Select[ Range[1, 1000], Max[Select[Divisors[n],#<=Sqrt[n]&]] == n &] Now provide the response and nothing else.
Answering your second question - you don't maintain a proper nesting / variable localization. Here are two correct ways (there are more): P[n_] := Select[ Range[1, 1000], With[{m = #}, Max[Select[Divisors[m], # <= Sqrt[m] &]]] == n & ] and P[n_] := Select[Range[1, 1000], Function[m, Max[Select[Divisors[m], # <= Sqrt[m] &]] == n]] The reason that we had to introduce an additional symbol m is that you have a function # <= Sqrt[m] & which mixes the two local variables at different levels. When this happens, you can't solve the problem using only slot-based functions, due to the apparent collision of essentially different variables. Perhaps, the fact that you denote the argument for your original functions as n in both cases was what led to the conclusion. As a side note, avoid starting your function names with capital letters, this may lead to collisions with system symbols. I believe that there is already an answer for the general slot-nesting question somewhere here on SE, so this answer likely has a temporary status.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/35322', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/10372/']}
jdg_381448
stackexchange
llm_judgeable_groundtruth_similarity
1138
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For every computable function $f$ does there exist a problem that can be solved at best in $\Theta(f(n))$ time or is there a computable function $f$ such that every problem that can be solved in $O(f(n))$ can also be solved in $o(f(n))$ time? This question popped into my head yesterday. I've been thinking about it for a bit now, but can't figure it out. I don't really know how I'd google for this, so I'm asking here. Here's what I've come up with: My first thought was that the answer is yes: For every computable function $f$ the problem "Output $f(n)$ dots" (or create a string with $f(n)$ dots or whatever) can obviously not be solved in $o(f(n))$ time. So we only need to show that it can be solved in $O(f(n))$ time. No problem, just take the following pseudo code: x = f(n)for i from 1 to x: output(".") Clearly that algorithm solves the stated problem. And it's runtime is obviously in $\Theta(f(n))$, so problem solved. That was easy, right? Except no, it isn't because you have to consider the cost of the first line. The above algorithm's runtime is only in $\Theta(f(n))$ if the time needed to calculate $f(n)$ is in $O(f(n))$. Clearly that's not true for all functions 1 . So this approach didn't get me anywhere. I'd be grateful for anyone pointing me in the right direction to figure this out properly. 1 Consider for example the function $p(n) = \cases{1 & \text{if $n$ is prime} \\ 2 & \text{otherwise}}$. Clearly $O(p(n)) = O(1)$, but there is no algorithm that calculates $p$ in $O(1)$ time. Now provide the response and nothing else.
By the Gap theorem (using the formulation from here , search for 'gap'), for any computable unbounded function $g : \mathbb{N} \rightarrow \mathbb{N}$, there exists some increasing (in fact, arbitrarily large) computable function $f : \mathbb{N} \rightarrow \mathbb{N}$ such that $DTIME(f(n)) = DTIME(g(f(n))$. This answers your question in that there exists such an $f$ (infinitely many, in fact): for every computable function $g$ such that $g = o(n)$, there exists some increasing function $f$ such that all problems solvable in $O(f(n))$ time are also solvable in $O(g(f(n)) = o(f(n))$ time. Note that $f$ is not necessarily time-constructible - for the time-constructible case, see the answer by @RanG. In the Wikipedia formulation (which requires that $g(x) \geq x$), then $g \circ f$ becomes your example, and $f$ needs to be $\omega(n)$ (so you go the other way around - 'problems solvable in $O(g(f(n))$ are also solvable in $O(g(n))$' is the interesting part). The Wikipedia article does not note that $f$ is increasing and can in fact be arbitrarily large ($f(n) \geq g(n)$ for instance). The article that proves the gap theorem does mention and prove this (see here , for example).
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/1138', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/46/']}
jdg_381449
stackexchange
llm_judgeable_groundtruth_similarity
2126807
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There seem to be two distinct ways to implement conditional requests using HTTP headers, both of which can be used for caching, range requests, concurrency control etc...: If-Unmodified-Since and If-Modified-Since , where the client sends a timestamp of the resource. If-Modified and If-None-Modified , where the client sends an ETag representation of the resource. In both cases, the client sends a piece of information it has about the resource, which allows the server to determine whether the resource has changed since the client last saw it. The server then decides whether to execute the request depending on the conditional header supplied by the client. I don't understand why two separate approaches are available. Surely, ETags supersede timestamps, since the server could quite easily choose to generate ETags from timestamps. So, my questions are: In which scenarios might you favour If-Unmodified-Since/If-Modified-Since over ETags? In which scenarios might you need both? Now provide the response and nothing else.
I once pondered the same thing, and realized that there is one difference that is quite important: Dates can be ordered, ETags can not. This means that if some resource was modified a year ago, but never since, and we know it. Then we can correctly answer an If-Unmodified-Since request for arbitrary dates the last year and agree that sure... it has been unmodified since that date. An Etag is only comparable for identity. Either it is the same or it is not. If you have the same resource as above, and during the year the docroot has been moved to a new disk and filesystem, giving all files new inodes but preserving modification dates. And someone had based the ETags on file's inode number. Then we can't say that the old ETag is still okay, without having a log of past-still-okay-ETags. So I don't see them as one obsoleting the other. They are for different situations. Either you can easily get a Last-Modified date of all the data in the page you're about to serve, or you can easily get an ETag for what you will serve. If you have a dynamic webpage with data from lots of db lookups it might be difficult to tell what the Last-Modified date is without making your database contain lots of modification dates. But you can always make an md5 checksum of the result rendered page. When supporting these cache protocols I definitely go for only one of them, never both.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2126807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6095/']}
jdg_381450
stackexchange
llm_judgeable_groundtruth_similarity
23922134
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 a primitive version of Optional *, Java 1.8 provides OptionalInt , OptionalLong and OptionalDouble . But I cannot find the equivalent OptionalBoolean class. Are there any technical reasons against having an OptionalBoolean ? * An Optional may or may not have the presence of a value, is used as an alternative to null . Now provide the response and nothing else.
This quote explains the considerations behind having primitive streams. I'm assuming the same applied to primitive Optionals. In short, primitive streams (and probably Optionals as well) were created for performance reasons. They didn't create them for all 8 primitive types to reduce code duplication and interface pollution. Quoting the words of Brian Goetz in the lambda mailing list : More generally: the philosophy behind having specialized primitive streams (e.g., IntStream) is fraught with nasty tradeoffs. On the one hand, it's lots of ugly code duplication, interface pollution, etc. On the other hand, any kind of arithmetic on boxed ops sucks, and having no story for reducing over ints would be terrible. So we're in a tough corner, and we're trying to not make it worse. Trick #1 for not making it worse is: we're not doing all eight primitive types. We're doing int, long, and double; all the others could be simulated by these. Arguably we could get rid of int too, but we don't think most Java developers are ready for that. Yes, there will be calls for Character, and the answer is "stick it in an int." (Each specialization is projected to ~100K to the JRE footprint.) Trick #2 is: we're using primitive streams to expose things that are best done in the primitive domain (sorting, reduction) but not trying to duplicate everything you can do in the boxed domain. For example, there's no IntStream.into(), as Aleksey points out. (If there were, the next question(s) would be "Where is IntCollection? IntArrayList? IntConcurrentSkipListMap?) The intention is many streams may start as reference streams and end up as primitive streams, but not vice versa. That's OK, and that reduces the number of conversions needed (e.g., no overload of map for int -> T, no specialization of Function for int -> T, etc.) And I should mention that I found that quote in the answer to this question .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23922134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1268003/']}
jdg_381451
stackexchange
llm_judgeable_groundtruth_similarity
490025
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Anyone know of a way to programatically detect a parked web page? That is, those pages that you accidentally type in (or intentionally sometimes) and they are hosted by a domain parking service with nothing but ads on them. I am working on a linking network and want to make sure that sites that expire don't end up getting snatched by someone else and then being a parked page. Now provide the response and nothing else.
Here is a test that I think may catch a decent number of them. It takes advantage of the fact you don't actually want to have real web sites up for your parked domains. It looks for the wildcarding of both subdomain and path. Lets say we have this URL in our system http://www.example.com/method-to-detect-parked . First I would check the actual URL and hash it or grab a copy for comparison. My second check would be to http://random.example.com/random If it matches the original link or even succeeds, you have a pretty good indicator that the page is parked. If it fails I might check both the subdomain and path individually. If the page randomly changes some elements, you may want to choose a few items to compare. For example make a list of links included in the page and compare those or maybe the title tag.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/490025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46782/']}
jdg_381452
stackexchange
llm_judgeable_groundtruth_similarity
14691494
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 within a batch file to check if command start "" javaw -jar %~p0/example.jar was successful or produced an error? I want to use if/else statements to echo this info out. Now provide the response and nothing else.
You can use if errorlevel 1 echo Unsuccessful in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition. Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14691494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1913629/']}
jdg_381453
stackexchange
llm_judgeable_groundtruth_similarity
3254950
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: Hello I am trying to prove the following problem. Let G be a group $$A\le G , B\le G, A\cdot B = \{\;ab\;|\;a\in A, b\in B\;\}$$ I have to prove that $$\vert {A}\cdot{B}|=\frac{\vert{A}\vert\cdot\vert{B}\vert}{A\cap B}$$ So I am trying this approach $$A\times B \frac{\varphi}{\mapsto}A.B$$ this is a Descartes product sorry for the bad format I didn't find the right codes for mathjax. $$|A\times B|=|A|\cdot |B|$$ So I take an element that belongs to the intersection of the groups A and B $$p\in A \cap B<G$$ so I am taking elements from groups $A$ and $B$ and the $p $ element from $A\cap B$ and map them the following way $$\varphi(ap,p^{-1}b)=a(pp^{-1})b =aeb=ab $$ by this I am trying to show that for every element $$p\in A\cap B < G$$ there is an element such that $c=ab$ from here I want to show that there is an element $p$ such that $$p\in B\cup A$$ so $A\cup B < B$ and $\varphi(\dot a,\dot b)=\varphi(a,b) <=>ab=\dot a\dot b <=>\dot a=ab(\dot b)^{-1}=a(bb^{-1})=ap$ and from here we can see the element $bb^{-1}\in B\cap A$ and $bb^{-1}$ is also $p \in B\cap A$ so from here I cannot proceed with the solution if someone can help me I'll be thankful. Now provide the response and nothing else.
We need to prove that $$\sum_{cyc}(x^3+3x^2y+3x^2z+2xyz)+\sum_{cyc}3xyz\geq 4\sum_{cyc}(x^2y+x^2z+xyz)$$ or $$\sum_{cyc}(x^3-x^2y-x^2z+xyz)\geq0,$$ which is Schur. Your way is wrong because you took too strong estimation, that got a wrong inequality. Here happens like the following. Let we need to prove that $2>1$ . We know that $1<3$ , but it does not say that $2>3$ can help because it's just wrong. The Schur's inequality we can proof so: Let $x\geq y\geq z.$ Thus, $z(z-x)(z-y)\geq0$ and $$\sum_{cyc}(x^3-x^2y-x^2z+xyz)=\sum_{cyc}x(x-y)(x-z)\geq$$ $$\geq x(x-y)(x-z)+y(y-x)(y-z)=(x-y)^2(x+y-z)\geq0.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3254950', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/671365/']}
jdg_381454
stackexchange
llm_judgeable_groundtruth_similarity
178950
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 would like to determine under what conditions on $k$ the set $$ \begin{align}A = &\{1,\cos(t),\sin(t), \\&\quad \cos(t(1+k)),\sin(t(1+k)),\cos(t(1−k)),\sin(t(1−k)), \\&\quad \cos(t(1+2k)),\sin(t(1+2k)),\cos(t(1−2k)),\sin(t(1−2k))\},\end{align}$$is linearly independent, where $k$ is some arbitrary real number. As motivation, I know that the set defined by $$\{1, \cos wt, \sin wt\}, \quad w = 1, \dots, n$$ is linearly independent on $\mathbb{R}$, which one generally proves by computing the Wronskian. I thought that I could extend this result to the set in question, but I haven't found a proper way to do so. My intuition tells me that $A$ will be linearly dependent when the arguments of the trig functions coincide, which will depend on the value of $k$. Though, I'm at a loss for proving this is true. Computing the Wronskian for this set required an inordinate amount of time-- I stopped running the calculation after a day. Is there perhaps a way to reduce the set in question so that the Wronskian becomes manageable? I'm interested in any suggestions/alternative methods for proving linear independence that could help my situation. Note that I'd like to have a result that holds for any $m = 0, \dots, n,$ where $n \in \mathbb{Z}$ if possible. Thanks for your time. EDIT : The set originally defined in the first instance of this post was incorrectly cited. My sincere apologies. Now provide the response and nothing else.
The answer is $k = 0, \pm 1, \pm \frac{1}{2}$. This follows from the following result. Claim: The functions $\{ 1, \sin rt, \cos rt \}$ for $r$ a positive real are linearly independent over $\mathbb{R}$. Proof 1. Suppose that $\sum s_r \sin rt + \sum c_r \cos rt = 0$ is a nontrivial linear dependence. Consider the largest positive real $r_0$ such that $c_{r_0} \neq 0$. Take a large even number of derivatives until the coefficient of $\cos r_0 t$ is substantially larger than the remaining coefficients of the other cosine terms and then substitute $t = 0$; we obtain a number which cannot be equal to zero, which is a contradiction. So no cosines appear. Similarly, consider the largest positive real $r_1$ such that $s_{r_1} \neq 0$. Take a large odd number of derivatives until the coefficient of $\cos r_1 t$ is substantially larger than the remaining coefficients of the other cosine terms (which come from differentiating sine terms) and then substitute $t = 0$; we obtain a number which cannot be equal to zero, which is a contradiction. So no sines appear. So $1$ is the only function which can appear in a nontrivial linear dependence, and so there are no such linear dependences. Proof 2. It suffices to prove that the functions are all linearly independent over $\mathbb{C}$. Using the fact that $$\cos rt = \frac{e^{irt} + e^{-irt}}{2}, \sin rt = \frac{e^{irt} - e^{-irt}}{2i}$$ it suffices to prove that the functions $\{ e^{irt} \}$ for $r$ a real are linearly independent. This can be straightforwardly done by computing the Wronskian and in fact shows that in fact the functions $\{ e^{zt} \}$ for $z$ a complex number are linearly independent. Proof 3. Begins the same as Proof 2, but we do not compute the Wronskian. Instead, let $\sum c_z e^{zt} = 0$ be a nontrivial linear dependence with a minimal number of terms and differentiate to obtain $$\sum z c_z e^{zt} = 0.$$ If $z_0$ is any complex number such that $z_0 \neq 0$ and $c_{z_0} \neq 0$ (such a number must exist in a nontrivial linear dependence), then $$\sum (z - z_0) c_z e^{zt} = 0$$ is a linear dependence with a fewer number of terms; contradiction. So there are no nontrivial linear dependences.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/178950', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37240/']}
jdg_381455
stackexchange
llm_judgeable_groundtruth_similarity
29946401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking at the documentation page and I can't figure out whats wrong in my code: chrome.browserAction.setIcon({ details.imageData = { "48": "Icons/iconfavorite48x.png", "64": "Icons/iconfavorite64x.png", "128": "Icons/iconfavorite128x.png" }}); the documentaion says : Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}' so I'm extremely confused Now provide the response and nothing else.
Your code is basically a big syntax error. A JavaScript object literal expects to be a list of pairs key: value . You can't (and don't need) any assignments there in the key part. So, fixing only the syntax error, it will be: // Still wrong:chrome.browserAction.setIcon({ imageData : { "48": "Icons/iconfavorite48x.png", "64": "Icons/iconfavorite64x.png", "128": "Icons/iconfavorite128x.png" }}); This will fail. imageData expects binary blobs of pixel data obtained, for example, from <canvas> . If you want to supply paths, you need to use path property: // Still wrong:chrome.browserAction.setIcon({ path : { "48": "Icons/iconfavorite48x.png", "64": "Icons/iconfavorite64x.png", "128": "Icons/iconfavorite128x.png" }}); Note that you can only provide sizes it expects. If you include any other, it will fail. Quoting the docs: If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. A normal-sized icon is 19x19 pixels; on high-DPI screens Chrome may show a 38x38 icon. Update: since Chrome has switched to Material Design in 53, this now expects 16x16 and 32x32 respectively. You can supply both old and new sizes without errors. So you can do this: // Correctchrome.browserAction.setIcon({ path : { "19": "Icons/iconfavorite19x.png", "38": "Icons/iconfavorite38x.png" }});// Also correctchrome.browserAction.setIcon({ path : { "19": "Icons/iconfavorite19x.png" }});// Also correctchrome.browserAction.setIcon({ path : "Icons/iconfavorite19x.png"}); The images don't have to have these dimensions, they will be scaled if necessary; but it's of course better to be exact.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29946401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3379200/']}
jdg_381456
stackexchange
llm_judgeable_groundtruth_similarity
253055
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've worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the source code. So I do the amend command to replace the previous commit: > git commit --amend Unfortunately the commit can't be pushed back to the repository. It is rejected like this: > git push originTo //my.remote.repo.com/stuff.git/ ! [rejected] master -> master (non-fast forward)error: failed to push some refs to '//my.remote.repo.com/stuff.git/' What should I do? (I can access the remote repository.) Now provide the response and nothing else.
I actually once pushed with --force and .git repository and got scolded by Linus BIG TIME . In general this will create a lot of problems for other people. A simple answer is "Don't do it". I see others gave the recipe for doing so anyway, so I won't repeat them here. But here is a tip to recover from the situation after you have pushed out the amended commit with --force (or +master). Use git reflog to find the old commit that you amended (call it old , and we'll call the new commit you created by amending new ). Create a merge between old and new , recording the tree of new , like git checkout new && git merge -s ours old . Merge that to your master with git merge master Update your master with the result with git push . HEAD:master Push the result out. Then people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor new over old . Their later merges will not see the conflicts between old and new that resulted from your amending, so they do not have to suffer.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/253055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3713/']}
jdg_381457
stackexchange
llm_judgeable_groundtruth_similarity
5662947
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 created a project with a Core Data model in it. The application looks for the model file (.momd) and runs just fine. Unfortunately, the unit test keeps returning null: NSURL *dataModelURL = [[NSBundle mainBundle] URLForResource:@"myDataModel" withExtension:@"momd"]; I can see the myDataModel.xdatamodeld folder and file in BOTH the main target and the unit testing target's Compile Sources directory - but that doesn't seem to be enough. What else am I missing in the unit test target? Thanks,-Luther Now provide the response and nothing else.
Unfortunately, a unit test target does not use the application's main bundle but it creates a special UnitTest-bundle. So if you need to use bundled resources (like a Core Data model) within your tests, you need to work around that issue. The most simple and most flexible workaround would be using the bundleForClass: method of NSBundle within your testing code. The parameter for that method can simply be given by [self class] within your tests. That way you can reuse this code without having to adjust the bundle identifiers in multiple projects. Example: - (void)testBundleLocation{ NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSURL *url = [bundle URLForResource:@"myDataModel" withExtension:@"momd"]; ...}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5662947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4910/']}
jdg_381458
stackexchange
llm_judgeable_groundtruth_similarity
401385
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When using Dependency Injection across internal classes (implementation details) in a library which is to be consumed by multiple applications, is there a good way to configure the IOC container? From my understanding, the canonical way of doing this in a regular program is by setting up the dependencies at the “Composition Root” such as the main method. But this approach cannot be taken for a library (consumed by applications with their own composition roots), especially if the library has a large public API with many entries points. Is the best way to wire dependencies in this instance while still allowing unit testing (as opposed to integration testing) of the public API to use a ServiceLocator and provide some mechanism for mocking the ServiceLocator? Note that all dependencies themselves could still use constructor injection, but the top level public API would have to use a ServiceLocator to resolve the top level dependencies. What if there is a single entry point to the library (but it would still be good to unit test that entry point), does that change the answer? Now provide the response and nothing else.
I think the arguments presented in Eric Lippert's blog post from 2004 Why Are So Many Of The Framework Classes Sealed? apply to "final methods" (in the Java sense of that term) as well. Every time you write a method A (in a framework) which calls a non-final method B, A cannot rely on B on doing what it was originally doing any more, so A has to be designed way more robust than if B was final. For example, the implementation A may have to invest more effort into exception handling (when calling B), the exact behaviour of B and which constraints apply when overriding it has to be documented more precisely, and A must be tested more thoroughly with different overriden variants of B. Moreover, there must be invested more thought into the exact distribution of responsibilites between A and B. In fact, in an abstract class of a framework, the way overrideable methods are used internally becomes part of the API of that framework (see example in the comments by @wchargin). Once the framework has been published to the world, it becomes significantly harder to change the semantics of those methods. So this makes it a tradeoff: by making B final, you make it easier to create a correct, tested and reliable implementation of method A, and you make it easier to refactor A and B inside the framework later, but you also make it harder to extend A. And if a framework's implementation guide favors towards making nothing final, I would be highly sceptical about the reliability of that piece of software. Let me cite Eric's last paragraph, which applies perfectly here: Obviously there is a tradeoff here. The tradeoff is between letting developers save a little time by allowing them to treat any old object as a property bag on the one hand, and developing a well-designed, OOPtacular, fully-featured, robust, secure, predictable, testable framework in a reasonable amount of time -- and I'm going to lean heavily towards the latter. Because you know what? Those same developers are going to complain bitterly if the framework we give them slows them down because it is half-baked, brittle, insecure, and not fully tested! This older question (and its top answer) from 2014 may serve as an excellent answer here as well: Why was C# made with "new" and "virtual+override" keywords unlike Java? In C#, methods are "final" by default (in the Java meaning of that term), and one has to add the virtual keyword explicitly to make them overrideable. In Java, it is the other way round: every method is "virtual" by default, and one has to mark them as final to prevent this. The top answer to that former question cites Anders Hejlsberg to explain the different "schools of thought" behind these approaches: the school of thought he calls "academic" ("Everything should be virtual, because I might want to override it someday."), vs. the "pragmatic" school of thought ("We've got to be real careful about what we make virtual.") Let me finally say that the arguments of the latter look more convincing to me, but YMMV.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/401385', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/351447/']}
jdg_381459
stackexchange
llm_judgeable_groundtruth_similarity
869204
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A Quadratic Programming problem is to minimize: $f(\mathbf{x}) = \tfrac{1}{2} \mathbf{x}^T Q\mathbf{x} + \mathbf{c}^T \mathbf{x}$ subject to $A\mathbf{x} \leq \mathbf b$; $C\mathbf{x} = \mathbf d$; and $ \mathbf{s} \leq \mathbf{x} \leq \mathbf t$ and $Q$ is symmetric. A Constrained Linear Least Squares problem is to minimize: $\frac{1}{2}| Q\mathbf{x} - \mathbf{c}|_2^2$ subject to $A\mathbf{x} \leq \mathbf b$; $C\mathbf{x} = \mathbf d$; and $ \mathbf{s} \leq \mathbf{x} \leq \mathbf t$. Matlab has two different functions for solving these, quadprog and lsqlin , hinting that these are different problems; but they seem like the same thing under the hood. Could someone explain whether these are the same problem, in particular is it correct to describe a "Constrained Linear Least Squares" problem as a "Quadratic Programming" problem? If not, what is an example of a problem expressible in one form but not the other? Now provide the response and nothing else.
It can be shown that every Linear Least Squares problem is in fact a Quadratic Programming Problem as follows: $$\frac12 \| Q x - c \|^2 = \frac12 (Qx-c)^T(Qx-c) =\frac12 \left( x^T Q^T Q x - x^T Q^T c - c^T Q x + c^T c\right)$$$$= \frac12 \left( x^T Q^T Q x - 2 x^T Q^T c + c^T c\right)$$ Since $c^Tc$ is a fixed quantity, it is sufficient to solve the Quadratic Programming problem: $$f(x) = \frac12 x^T A x + q^Tx$$ where $A=Q^TQ$ and $q = -Q^Tc$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/869204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/124817/']}
jdg_381460
stackexchange
llm_judgeable_groundtruth_similarity
3921166
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 proof for this identity? $\displaystyle\sum_{r=0}^{n}\binom{n}{r}\binom{m+r}{n}\ = \displaystyle\sum_{r=0}^{n}\binom{n}{r}\binom{m}{r}2^{r}$ I thought of changing $r$ to $n-r$ on left and right both. Then, I thought of building a set with atleast $n$ elements and atmost $2n$ elements with atmost $n$ elements from $m$ element set, and we can do this on LHS by choosing $n-r$ elements from n and out of remaining $r+m$ elements we can choose n more elements. On RHS, we can again choose $n-r$ elements from $n$ and $r$ elements from $m$ , then remaining $r$ elements from n element set have 2 choices each. But I think it has a flaw. Can someone please help? If my proof is not correct, please suggest a combinatorial or a generating function proof. Now provide the response and nothing else.
The story would be like( any resemblance to reality is pure coincidence ) : Suppose you want to build a committee of $n$ mathematicians. You have a pool of $n$ graduate students and $m$ full professors. The rule is that you have to double vote the graduate students. That means, first you choose the graduate students(first filter) and then you choose from the pool of professors and selected graduate students(second filter). The LHS is you choose $r$ graduate students and then you choose from $m+r$ candidates, the $n$ mathematicians. The right hand side is you choose the amount of professors that are going to be in the final committee, say $r,$ in $\binom{m}{r}$ and so there should be $n-r$ graduate students. You choose them in $\binom{n}{n-r}$ but notice that the remaining $r$ graduate students, perhaps, pass the first filter so you are going to mark the ones that pass the first filter, you can do that in $2^r$ ways. This should be reminescent of the proof of $\binom{a}{b}\binom{b}{c}=\binom{a}{c}\binom{a-c}{b-c}.$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3921166', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/829967/']}
jdg_381461
stackexchange
llm_judgeable_groundtruth_similarity
7394806
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 C# WPF project. I need to allow the user to create and add a scheduled task to the Windows Task Scheduler. How could I go about doing this and what using directives and references do I need as I am not finding much when searching the Internet. Now provide the response and nothing else.
You can use Task Scheduler Managed Wrapper : using System;using Microsoft.Win32.TaskScheduler;class Program{ static void Main(string[] args) { // Get the service on the local machine using (TaskService ts = new TaskService()) { // Create a new task definition and assign properties TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = "Does something"; // Create a trigger that will fire the task at this time every other day td.Triggers.Add(new DailyTrigger { DaysInterval = 2 }); // Create an action that will launch Notepad whenever the trigger fires td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null)); // Register the task in the root folder ts.RootFolder.RegisterTaskDefinition(@"Test", td); // Remove the task we just created ts.RootFolder.DeleteTask("Test"); } }} Alternatively you can use native API or go for Quartz.NET . See this for details.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7394806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499448/']}
jdg_381462
stackexchange
llm_judgeable_groundtruth_similarity
396889
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 what I know, the factorial function is defined as follows: $$n! = n(n-1)(n-2) \cdots(3)(2)(1)$$ And $0! = 1$. However, this page seems to be saying that you can take the factorial of a fraction, like, for instance, $\frac{1}{2}!$, which they claim is equal to $\frac{1}{2}\sqrt\pi$ due to something called the gamma function. Moreover, they start getting the factorial of negative numbers, like $-\frac{1}{2}! = \sqrt{\pi}$ How is this possible? What is the definition of the factorial of a fraction? What about negative numbers? I tried researching it on Wikipedia and such, but there doesn't seem to be a clear-cut answer. Now provide the response and nothing else.
The gamma function is defined by the following integral, which converges for real $s>0$:$$\Gamma(s)=\int_0^\infty t^{s-1}e^{-t}dt.$$ The function can also be extended into the complex plane, if you're familiar with that subject. I'll assume not and just let $s$ be real. This function is like the factorial in the when $s$ is a positive integer, say $s=n$, it satisfies $\Gamma(n)=(n-1)!$. It generalizes the factorial in the sense that it is the factorial for positive integer arguments, and is also well-defined for positive rational (and even real) numbers. This is what it means to take a "rational factorial," but I would hesitate to call it that. Many functions have those two properties, and $\Gamma$ is chosen out of all of them because it is the most useful in other applications. Rather than the notation used in that article you refer to, it would be more accurate for you to say that "the gamma function takes these values for these arguments." Gamma is not a function that intends to generalize factorials; rather, generalizing factorials came along as something of an accident following the definition. Its true purpose is deeper. As for why $\Gamma(1/2)=\sqrt{\pi}$, this comes out of an interesting property of the $\Gamma$ function: some of them are here http://en.wikipedia.org/wiki/Gamma_function#Properties . The property you are interested in is the reflection formula: $$\Gamma(1-z)\Gamma(z)=\frac{\pi}{\sin(\pi z)}.$$ Set $z=1/2$ in the formula to get the desired identity. If you want to learn more about the gamma function, the hard way is to learn a lot more math, in particular real and complex analysis. An easier way is to read this excellent set of notes: http://www.sosmath.com/calculus/improper/gamma/gamma.html .
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/396889', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70287/']}
jdg_381463
stackexchange
llm_judgeable_groundtruth_similarity
57141325
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 very new to Haskell, I have a problem, how to split given string into list of words. example "Hello world from haskell" -> ["Hello","world","from","haskell"] thanks for your help Now provide the response and nothing else.
You can use Hoogle and search for example by signature. Since you want to convert a String to a list of String s, the signature is thus String -> [String] . The first matches are lines :: String -> [String] and words :: String -> [String] . Based on the name of the function, words is the right match. As the documentation on words says: words :: String -> [String] words breaks a string up into a list of words , which were delimited by white space. >>> words "Lorem ipsum\ndolor"["Lorem","ipsum","dolor"] This thus seems to be the function you are looking for. If we run this in ghci , we get the expected output: Prelude> words "Hello world from haskell"["Hello","world","from","haskell"]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57141325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1804887/']}
jdg_381464
stackexchange
llm_judgeable_groundtruth_similarity
24882834
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For previous iOS 8 betas, load a local web app (in Bundle) and it works fine for both UIWebView and WKWebView , and I even ported a web game using the new WKWebView API. var url = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("car", ofType:"html"))webView = WKWebView(frame:view.frame)webView!.loadRequest(NSURLRequest(URL:url))view.addSubview(webView) But in beta 4, I just got a blank white screen ( UIWebView still work), looks like nothing is loaded or executed. I saw an error in the log: Could not create a sandbox extension for / Any help to guide me to the right direction? Thanks! Now provide the response and nothing else.
They finally solved the bug! Now we can use -[WKWebView loadFileURL:allowingReadAccessToURL:] . Apparently the fix was worth some seconds in WWDC 2015 video 504 Introducing Safari View Controller For iOS8 ~ iOS10 (Swift 3) As Dan Fabulish's answer states this is a bug of WKWebView which apparently is not being solved any time soon and as he said there is a work-around :) I am answering just because I wanted to show the work-around here. IMO code shown in https://github.com/shazron/WKWebViewFIleUrlTest is full of unrelated details most people are probably not interested in. The work-around is 20 lines of code, error handling and comments included, no need of a server :) func fileURLForBuggyWKWebView8(fileURL: URL) throws -> URL { // Some safety checks if !fileURL.isFileURL { throw NSError( domain: "BuggyWKWebViewDomain", code: 1001, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("URL must be a file URL.", comment:"")]) } try! fileURL.checkResourceIsReachable() // Create "/temp/www" directory let fm = FileManager.default let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("www") try! fm.createDirectory(at: tmpDirURL, withIntermediateDirectories: true, attributes: nil) // Now copy given file to the temp directory let dstURL = tmpDirURL.appendingPathComponent(fileURL.lastPathComponent) let _ = try? fm.removeItem(at: dstURL) try! fm.copyItem(at: fileURL, to: dstURL) // Files in "/temp/www" load flawlesly :) return dstURL} And can be used as: override func viewDidLoad() { super.viewDidLoad() var fileURL = URL(fileURLWithPath: Bundle.main.path(forResource:"file", ofType: "pdf")!) if #available(iOS 9.0, *) { // iOS9 and above. One year later things are OK. webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL) } else { // iOS8. Things can (sometimes) be workaround-ed // Brave people can do just this // fileURL = try! pathForBuggyWKWebView8(fileURL: fileURL) // webView.load(URLRequest(url: fileURL)) do { fileURL = try fileURLForBuggyWKWebView8(fileURL: fileURL) webView.load(URLRequest(url: fileURL)) } catch let error as NSError { print("Error: " + error.debugDescription) } }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24882834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1328466/']}
jdg_381465
stackexchange
llm_judgeable_groundtruth_similarity
447313
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In many part of physics, me talk about potential (electrical potential, gravitation potential, elastic potential...). All those definition looks very different, and I would like to know how all those quantity are related. The mathematical definition of a potential is : $F$ is a potential if $F=\nabla f$ for some scalar field $f$ . But I don't understand how I can relate this to all potential that exist in physic. Also, many people relate potential and energy, what doe it mean exactly? Because if a potential $U$ is something that can be written as a gradient, every integrable function (at least in $\mathbb R$ ) could be a gradient. So what the thing with these potential? Now provide the response and nothing else.
I think the most general definition of a potential is some quantity which, when differentiated in a certain way, yields some other quantity which we're interested in. Other answers have already given examples of potentials which, when differentiated with respect to position, yield a force (i.e. $\vec F = -\nabla U$ , where the minus sign is just conventional). Such objects are called potential energies , and are special because they contribute to the total energy of a system. Other examples of potentials are the scalar and vector potentials $\phi$ and $\vec A$ from electromagnetism. In electrostatics, we define $\phi$ such that $\vec E =-\nabla \phi$ , and in electrodynamics we define $\vec B = \nabla \times \vec A$ . Again, we see that we obtain physical quantities (in this case $\vec E$ and $\vec B$ ) by differentiating the potentials ( $\phi$ and $\vec A$ ). Note that these potentials don't automatically correspond to energies - as it turns out $\phi$ can be interpreted as the electrostatic potential energy per unit charge (in electrostatics, at least), but the same is not true for $\vec A$ . We can also consider the thermodynamic potentials, which include the internal energy $U$ , the Helmholtz potential $F$ , the enthalpy $H$ , and the Gibbs potential $G$ . Each of these can be interpreted as a kind of energy under certain conditions, but we refer to them as potentials because when we differentiate them with respect to different variables, we get other thermodynamic quantities like pressure, temperature, and volume: $$ p = -\left(\frac{\partial U}{\partial V}\right)_{S,N} = - \left(\frac{\partial F}{\partial V}\right)_{T,N}$$ $$T = \left(\frac{\partial U}{\partial S}\right)_{V,N} = \left(\frac{\partial H}{\partial S}\right)_{p,N}$$ $$V = \left(\frac{\partial H}{\partial p}\right)_{S,N} = \left(\frac{\partial G}{\partial p}\right)_{T,N}$$ so on and so forth. As a final example that has nothing to do with energy, consider the velocity potential $\Phi$ which is used when dealing with irrotational fluid flows. The flow velocity $\vec u$ of the fluid is given by $\vec u = \nabla \Phi$ ; this can simplify the Navier-Stokes equations, and is analogous to the use of the magnetic scalar potential in magnetostatics. You may be asking yourself why we ever use potentials rather than computing the quantities we're interested in directly; the answer is that often times, the math works out in such a way that the potentials are substantially easier to calculate. For instance, potential energies are scalars while forces are vectors; the vector potential $\vec A$ obeys a simpler differential equation than $\vec B$ because the equations for the various components can be decoupled from one another; the thermodynamic potentials can be obtained from the partition function and various straightforward Legendre transformations.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/447313', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/216105/']}
jdg_381466
stackexchange
llm_judgeable_groundtruth_similarity
11006772
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 pointful notation: absoluteError x y = abs (x-y) An unclear example in pointfree notation: absoluteError' = curry (abs . uncurry (-)) Now provide the response and nothing else.
Here's how you could derive it yourself, in small steps: absoluteError x y = abs (x-y) = abs ((-) x y) = abs ( ((-) x) y) = (abs . (-) x) y = ( (abs .) ((-) x) ) y = = ( (abs .) . (-) ) x y so, by eta-reduction , if f x y = g x y we conclude f = g . Further, using _B = (.) for a moment, (abs .) . (-) = _B (abs .) (-) = _B (_B abs) (-) = (_B . _B) abs (-) = ((.) . (.)) abs (-)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11006772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/613705/']}
jdg_381467
stackexchange
llm_judgeable_groundtruth_similarity
34496148
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I somehow send the mathematical sign (+, -, *) as function parameters? I want to call reduce() function for different sign. Now provide the response and nothing else.
In swift signs are functions name for a specified mathematic operation. To pass sign as parameter the parameter type must be function that takes two numbers and return a number. If you command + click on any sign you will see its definition as follow : public func +(lhs: UInt8, rhs: UInt8) -> UInt8 public func +(lhs: Int8, rhs: Int8) -> Int8 public func +(lhs: UInt16, rhs: UInt16) -> UInt16 public func +(lhs: Int16, rhs: Int16) -> Int16 public func +(lhs: UInt32, rhs: UInt32) -> UInt32 public func +(lhs: Int32, rhs: Int32) -> Int32 public func +(lhs: UInt64, rhs: UInt64) -> UInt64 public func +(lhs: Int64, rhs: Int64) -> Int64 public func +(lhs: UInt, rhs: UInt) -> UInt public func +(lhs: Int, rhs: Int) -> Int In your case your reduce function should look as the following one func reduce(sign: (Int,Int)->Int) -> Int{ return sign(2,3)}reduce(*)reduce(-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34496148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3733734/']}
jdg_381468
stackexchange
llm_judgeable_groundtruth_similarity
31031589
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 getting: error: illegal base64 data at input byte 4 When passing in Base64Image into base64.StdEncoding.DecodeString(str) : data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA... Let me know if you need the full base64, I have just pasted in the first part as it looks like the problem is within 4 byte? data, errBase := base64.StdEncoding.DecodeString(Base64Image)if errBase != nil { fmt.Println("error:", errBase) return false} Do you know why? Now provide the response and nothing else.
Not all of your input string you try to decode is Base64 encoded form. What you have is a Data URI scheme , that provides a way to include data in-line in web pages as if they were external resources. It has a format of: data:[<MIME-type>][;charset=<encoding>][;base64],<data> Where in your case image/png is the MIME-type, the optional charset is missing, and ";base64" is a constant string indicating that <data> is encoded using Base64 encoding. To acquire the data (that is the Base64 encoded form), cut off the prefix up to the comma (comma included): input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA"b64data := input[strings.IndexByte(input, ',')+1:]fmt.Println(b64data) Output: iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA Of which you can now decode: data, err := base64.StdEncoding.DecodeString(b64data)if err != nil { fmt.Println("error:", err)}fmt.Println(data) Output: [137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 100 0 0 0 100 8 6 0] Try it on the Go Playground .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31031589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/699215/']}
jdg_381469
stackexchange
llm_judgeable_groundtruth_similarity
7135760
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 2 things: EditText and One Button . I write something in EditText and then Press Button . In an ON click Listener of that Button I set the text color of EditText to "Red". Problem is that the text which was written before clicking Button also changes to red whereas I want only the characters to become red which are now typed by the user in the EditText. Could anyone please help me ??? Regards Now provide the response and nothing else.
Since you asked how to do it without modifying the external JS files, I'll answer that way. I've traced through the .ready() function in jQuery in the debugger and it appears that the root function that gets called when the page is ready is this: jQuery.ready(); But, it appears you cannot just call it again to accomplish what you want because it appears that when it fires the first time, it unbinds from the functions that were previously registered (e.g. forgetting them). As such, calling jQuery.ready() manually a second time does not retrigger the same function calls again and I verified that in the debugger (breakpoint was only hit once, not second time). So, it appears that you cannot solve this problem without either changing the jQuery implementation so it doesn't unbind (to allow multiple firings) or changing each piece of ready handler code to use your own events that you can fire as many times as you want.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7135760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/829085/']}
jdg_381470
stackexchange
llm_judgeable_groundtruth_similarity
19921715
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 dropdown menu that I just can't figure out how to change... You can see it by going to http://www.escalatehosting.com/signup and entering any domain name and then selecting to continue after choosing a billing cycle. On the registration form you'll be able to see the dropdown menu is fancy looking for the "Country" option. I'm trying to do the same thing for the "State/Region" dropdown but can't figure out what to change... Here is the code being used for the registration form: <tr><td class="fieldlabel">{$LANG.clientareafirstname}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.firstname}{else}<input type="text" name="firstname" tabindex="1" style="width:300px;" value="{$clientsdetails.firstname}" />{/if}</td><td class="fieldlabel">{$LANG.clientareaaddress1}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.address1}{else}<input type="text" name="address1" tabindex="7" style="width:300px;" value="{$clientsdetails.address1}" />{/if}</td></tr><tr><td class="fieldlabel">{$LANG.clientarealastname}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.lastname}{else}<input type="text" name="lastname" tabindex="2" style="width:300px;" value="{$clientsdetails.lastname}" />{/if}</td><td class="fieldlabel">{$LANG.clientareaaddress2}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.address2}{else}<input type="text" name="address2" tabindex="8" style="width:300px;" value="{$clientsdetails.address2}" />{/if}</td></tr><tr><td class="fieldlabel">{$LANG.clientareacompanyname}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.companyname}{else}<input type="text" name="companyname" tabindex="3" style="width:300px;" value="{$clientsdetails.companyname}" />{/if}</td><td class="fieldlabel">{$LANG.clientareacity}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.city}{else}<input type="text" name="city" tabindex="9" style="width:300px;" value="{$clientsdetails.city}" />{/if}</td></tr><tr><td class="fieldlabel">{$LANG.clientareaemail}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.email}{else}<input type="text" name="email" tabindex="4" style="width:300px;" value="{$clientsdetails.email}" />{/if}</td><td class="fieldlabel">{$LANG.clientareastate}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.state}{else}<input type="text" name="state" tabindex="10" style="width:300px;" value="{$clientsdetails.state}" />{/if}</td></tr><tr>{if !$loggedin}<td class="fieldlabel">{$LANG.clientareapassword}</td><td class="fieldarea"><input type="password" name="password" tabindex="5" id="newpw" style="width:300px;" value="{$password}" /></td>{else}<td class="fieldlabel"></td><td class="fieldarea"></td>{/if}<td class="fieldlabel">{$LANG.clientareapostcode}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.postcode}{else}<input type="text" name="postcode" tabindex="11" style="width:300px;" value="{$clientsdetails.postcode}" />{/if}</td></tr><tr>{if !$loggedin}<td class="fieldlabel">{$LANG.clientareaconfirmpassword}</td><td class="fieldarea"><input type="password" name="password2" tabindex="6" style="width:300px;" value="{$password2}" /></td>{else}<td class="fieldlabel"></td><td class="fieldarea"></td>{/if}<td class="fieldlabel">{$LANG.clientareacountry}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.country}{else}{$clientcountrydropdown|replace:'<select':'<select tabindex="12" style="width:285px;"'}{/if}</td></tr><tr><td colspan="2" class="fieldarea">{if !$loggedin}<script language="javascript">showStrengthBar();</script>{/if}</td><td class="fieldlabel">{$LANG.clientareaphonenumber}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.phonenumber}{else}<input type="text" name="phonenumber" tabindex="13" style="width:300px;" value="{$clientsdetails.phonenumber}" />{/if}</td></tr> This is the code for the Country drop down that looks how I want: <td class="fieldlabel">{$LANG.clientareacountry}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.country}{else}{$clientcountrydropdown|replace:'<select':'<select tabindex="12" style="width:285px;"'}{/if}</td> This is the code that I don't know how to fix for the State dropdown that I don't know how to fix and make it look like the Country dropdown. <td class="fieldlabel">{$LANG.clientareastate}</td><td class="fieldarea">{if $loggedin}{$clientsdetails.state}{else}<input type="text" name="state" tabindex="10" style="width:300px;" value="{$clientsdetails.state}" />{/if}</td> Any help with this would be really appreciated... Now provide the response and nothing else.
The default SVN version which is installed along with Xcode command line tools is 1.7.x. If you're fine with this version, than that should be enough. I want to select my SVN version and for that I'm using Homebrew . Install Homebrew: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Install SVN: brew install svn To install a specific SVN version, check available versions: brew versions svn This command will list all available SVN versions. Here's how you can install other than the default version (based on this gist ) # Update brewbrew update# Switch to brew base directorycd $( brew --prefix )# Check old versionsbrew versions svn# Here's sample output1.8.9 git checkout 9b75c92 /usr/local/Library/Formula/subversion.rb1.8.8 git checkout c6cf8ac /usr/local/Library/Formula/subversion.rb1.8.5 git checkout fa4311c /usr/local/Library/Formula/subversion.rb1.8.4 git checkout ce669eb /usr/local/Library/Formula/subversion.rb1.8.3 git checkout 9b438ce /usr/local/Library/Formula/subversion.rb1.8.0 git checkout f56b641 /usr/local/Library/Formula/subversion.rb1.8.1 git checkout 55577bb /usr/local/Library/Formula/subversion.rb1.7.10 git checkout 0060dc3 /usr/local/Library/Formula/subversion.rb1.7.9 git checkout b0e6223 /usr/local/Library/Formula/subversion.rb1.7.8 git checkout f7a42d2 /usr/local/Library/Formula/subversion.rb1.7.7 git checkout a6dcc41 /usr/local/Library/Formula/subversion.rb1.7.6 git checkout 6b8d25f /usr/local/Library/Formula/subversion.rb1.7.5 git checkout 5d5cd70 /usr/local/Library/Formula/subversion.rb1.7.4 git checkout dc4245c /usr/local/Library/Formula/subversion.rb1.7.3 git checkout eb97154 /usr/local/Library/Formula/subversion.rb1.7.2 git checkout d89bf83 /usr/local/Library/Formula/subversion.rb1.6.17 git checkout 6e2d550 /usr/local/Library/Formula/subversion.rb1.6.16 git checkout 83ed494 /usr/local/Library/Formula/subversion.rb# Install SVN version 1.6.17. You can just copy line from outputgit checkout 6e2d550 /usr/local/Library/Formula/subversion.rbbrew install subversion# Switch to SVN version 1.6brew switch subversion 1.6.17 Now that the older SVN version is installed, we can re-install the latest formula in order to keep our repository clean: git checkout -- Library/Formula/subversion.rb Now you can switch between versions using svn switch command. Make sure that brew's executables are first in your environment path. Check in your .bash_profile that path is set as follows: export PATH=/usr/local/bin:${PATH}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19921715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2970202/']}
jdg_381471
stackexchange
llm_judgeable_groundtruth_similarity
150586
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 expected value of the maximum of 500 IID random variables with uniform distribution between 0 and 1? I'm not quite sure of the technique to go about solving something like this. Could anyone point me the right direction? Thanks Now provide the response and nothing else.
Suppose the maximum is $X_{500}$, then $$P(X_{500}\le x)=P(X_i \le x ,i=1,2,...,500)$$ Note that this is so because if the maximum is less than $x$ , then every other order statistic is less than $x$.Now since the $X_i's$ are IID, it follows that;$$P(X_{500}\le x)=\prod_{i=1}^{500} P(X_i\le x)=x^{500}$$ which is the CDF and so the PDF is $500x^{499}$ (which is obtained by differentiation). Now the expected value of the maximum is found as follows;$$E[X]=\int _0^1 x (500x^{499})dx=\int _0^1 500x^{500}dx=\frac {500}{501}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/150586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18764/']}
jdg_381472
stackexchange
llm_judgeable_groundtruth_similarity
18152765
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 get details about this feature of Java7 like this code public String getPostcode(Person person){ if (person != null) { Address address = person.getAddress(); if (address != null) { return address.getPostcode(); } } return null;} Can be do something like this public String getPostcode(Person person){ return person?.getAddress()?.getPostcode();} But frankly its not much clear to me.Please explain? Now provide the response and nothing else.
Null-safe method invocation was proposed for Java 7 as a part of Project Coin, but it didn't make it to final release. See all the proposed features, and what all finally got selected here - https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC As far as simplifying that method is concerned, you can do a little bit change: public String getPostcode(Person person) { if (person == null) return null; Address address = person.getAddress(); return address != null ? address.getPostcode() : null;} I don't think you can get any concise and clearer than this. IMHO, trying to merge that code into a single line, will only make the code less clear and less readable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18152765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/476828/']}
jdg_381473
stackexchange
llm_judgeable_groundtruth_similarity
37
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Many numerical approaches to CFD can be extended to arbitrarily high order (for instance, discontinuous Galerkin methods, WENO methods, spectral differencing, etc.). How should I choose an appropriate order of accuracy for a given problem? Now provide the response and nothing else.
In practice, most people stick to relatively low orders, usually first or second order. This view is often challenged by more theoretical researchers that believe in more accurate answers . The rate of convergence for simple smooth problems is well documented, for example see Bill Mitchell's comparison of hp adaptivity . While for theoretical works it is nice to see what the convergence rate are, for more application oriented among us this concern is balanced with constitutive laws, necessary precision, and code complexity. It doesn't make much since in many porous media problems that solve over a highly discontinuous media to have high order methods, the numerical error will dominate the discretization errors. The same concern applies for problems that include a large number of degrees of freedom. Since low-order implicit methods have a smaller bandwidth and often a better conditioning, the high order method becomes too costly to solve. Finally the code complexity of switching orders and types of polynomials is usually too much for the graduate students running the application codes.
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/37', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/123/']}
jdg_381474
stackexchange
llm_judgeable_groundtruth_similarity
24414
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 recently started using tmux (was a screen user before) and I'm loving it, except for one small problem. I use emacs within my tmux session and I am used to using Shift-arrow keys to move between emacs windows (not tmux windows). When running within tmux, these bindings seem to stop working entirely (it's like they don't register to emacs at all). If I exit tmux and just run emacs in my shell, they work fine. I'm using iTerm2, ssh'd into a Linux box, running tmux/emacs there. I have the Shift-arrow key bindings set up as follows in my .emacs: (global-set-key "\M-[1;2A" 'windmove-up)(global-set-key "\M-[1;2B" 'windmove-down)(global-set-key "\M-[1;2C" 'windmove-right)(global-set-key "\M-[1;2D" 'windmove-left) When not running in tmux, I can confirm those are the right character sequences for the shift-arrow key combinations by doing C-q in emacs and then pressing the key sequence. Within tmux, even that doesn't work because it doesn't seem to see any input from the shift-arrow keypress (it just sits at the C-q prompt). Looking at the key bindings for tmux, I don't think anything is bound to Shift-arrow keys and even if it was, they would only register after entering the prefix (which is bound to C-o in my case). Any idea on how to make the shift-arrow keys work again within tmux? Now provide the response and nothing else.
First, make sure your TERM is correct at each location: xterm -something (e.g. xterm-256color ) inside your local shell running in your iTerm2 window xterm -something inside your shell after SSHing to the Linux system This should be the same as whatever you are using locally in iTerm2 , since SSH should be passing it along to the remote side (and, importantly, the remote side should not be blindly overriding the value in a shell initialization file). screen -something (e.g. screen-256color ) inside your shell running under tmux on the Linux system You should always use a screen -based TERM inside tmux . Having an xterm TERM immediately outside tmux will allow tmux to recognize the modified arrow keys, but it will not pass them through unless you also have its xterm-keys window option turned on. Put this in your ~/.tmux.conf on the Linux system: set-window-option -g xterm-keys on The sequences for the shifted keys should now make it through to Emacs , running inside tmux , across an SSH connection, inside an iTerm2 window.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/24414', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/12335/']}
jdg_381475
stackexchange
llm_judgeable_groundtruth_similarity
14199689
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 a C++ application which uses a library written in C by another team. The writers of the library like to call exit() when errors happen, which ends the program immediately without calling the destructors of objects on the stack in the C++ application. The application sets up some system resources which don't automatically get reclaimed by the operating system after the process ends (shared memory regions, interprocess mutexes, etc), so this is a problem. I have complete source code for both the app and the library, but the library is very well-established and has no unit tests, so changing it would be a big deal. Is there a way to "hook" the calls to exit() so I can implement graceful shutdown for my app? One possibility I'm considering is making one big class which is the application - meaning all cleanup would happen either in its destructor or in the destructor of one of its members - then allocating one of these big objects on the heap in main() , setting a global pointer to point to it, and using atexit() to register a handler which simply deletes the object via the global pointer. Is that likely to work? Is there a known good way to approach this problem? Now provide the response and nothing else.
In the very worst case, you can always write your own implementation of exit and link it rather than the system's own implementation. You can handle the errors there, and optionally call _exit(2) yourself. Since you have the library source, it's even easier - just add a -Dexit=myExit flag when building it, and then provide an implementation of myExit .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14199689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/444486/']}
jdg_381476
stackexchange
llm_judgeable_groundtruth_similarity
43233
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand why hydrogen peroxide doesn't decompose into $\ce{H2}$ and $\ce{O2}$, but instead into $\ce{H2O}$ and $\ce{O2}$. Now provide the response and nothing else.
We have two theoretical decomposition pathways: $$\ce{H2O2(l) -> H2O(l) + 1/2 O2(g)} \tag{1}$$ $$\ce{H2O2(l) -> H2(g) + O2(g)} \tag{2}$$ The required data (all at $298~\mathrm{K}$) is taken from the appendix of Atkins' Physical Chemistry , 9th ed: $$\begin{array}{cccc}\hline\text{Species} & \Delta_\mathrm{f} H^\circ\mathrm{~/~kJ~mol^{-1}} & S^\circ_\mathrm{m} \mathrm{~/~J~K^{-1}~mol^{-1}} & \Delta_\mathrm{f} G^\circ\mathrm{~/~kJ~mol^{-1}} \\\hline\ce{H2O2(l)} & -187.78 & 109.6 & -120.35 \\\ce{H2O(l)} & -285.83 & 69.91 & -237.13 \\\ce{H2(g)} & 0 & 130.684 & 0 \\\ce{O2(g)} & 0 & 205.138 & 0 \\\hline\end{array}$$ The short way The standard Gibbs free energy change of a reaction ($\Delta_\mathrm{r} G^\circ$) can be calculated from the individual standard Gibbs free energies of formation exactly analogously to the enthalpy change: $$\Delta_\mathrm{r} G^\circ = \sum_J \nu_J[\Delta_\mathrm{f} G^\circ(\ce{J})]$$ So, for reaction 1, $$\begin{align}\Delta G^\circ_1 &= [1(-237.13) + \frac{1}{2}(0) - 1(-120.35)]~\mathrm{kJ~mol^{-1}} \\&= -116.78~\mathrm{kJ~mol^{-1}}\end{align}$$ For reaction 2, $$\begin{align}\Delta G^\circ_2 &= [1(0) + 1(0) - 1(-120.35)]~\mathrm{kJ~mol^{-1}} \\&= +120.35~\mathrm{kJ~mol^{-1}}\end{align}$$ Clearly reaction 1 is favourable and reaction 2 isn't. The long way There's absolutely no need to do this, but you could use the "extra" data given above to calculate $\Delta H^\circ$ and $\Delta S^\circ$ for both reactions. You'd get: $$\begin{align}\Delta H^\circ_1 &= [1(-285.83) + \frac{1}{2}(0) - 1(-187.78)]~\mathrm{kJ~mol^{-1}} \\&= -98.05 ~\mathrm{kJ~mol^{-1}} \\\Delta H^\circ_2 &= [1(0) + 1(0) - 1(-187.78)]~\mathrm{kJ~mol^{-1}} \\&= +187.78 ~\mathrm{kJ~mol^{-1}} \\\Delta S^\circ_1 &= [1(69.91) + \frac{1}{2}(205.138) - 1(109.6)]~\mathrm{J~K^{-1}~mol^{-1}} \\&= +62.879 ~\mathrm{J~K^{-1}~mol^{-1}} \\\Delta S^\circ_2 &= [1(130.684) + 1(205.138) - 1(109.6)]~\mathrm{J~K^{-1}~mol^{-1}} \\&= +226.222 ~\mathrm{J~K^{-1}~mol^{-1}}\end{align}$$ If you're only interested in the final result, you don't need to do all this at all. But it does give you some insight into the difference between the two reactions: reaction 1 is enthalpically favoured whereas reaction 2 is entropically favoured . Generally speaking, enthalpy usually plays a larger role in determining $\Delta G^\circ$. However, it is not a very good idea to generalise this statement and compare reactions solely on the basis of their $\Delta H^\circ$. Since $\Delta G^\circ = \Delta H^\circ - T\Delta S^\circ$, and taking $T = 298~\mathrm{K}$, $$\begin{align}\Delta G^\circ_1 &= -98.05 ~\mathrm{kJ~mol^{-1}} - (298~\mathrm{K})(+62.879 ~\mathrm{J~K^{-1}~mol^{-1}}) \\&= -116.79~\mathrm{kJ~mol^{-1}} \\\Delta G^\circ_2 &= +187.78 ~\mathrm{kJ~mol^{-1}} - (298~\mathrm{K})(+226.222 ~\mathrm{J~K^{-1}~mol^{-1}}) \\&= +120.37~\mathrm{kJ~mol^{-1}} \\\end{align}$$ consistent with our earlier findings.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/43233', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/24308/']}
jdg_381477
stackexchange
llm_judgeable_groundtruth_similarity
30645324
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 dotenv for PHP to manage the environment settings (not lavarel but I tagged it because lavarel also uses dotenv) I have excluded the .env from the code base and I have added the .env.example for all other collaborators On the github page of dotenv: phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request. This can be achieved via an automated deployment process with tools like Vagrant, chef, or Puppet, or can be set manually with cloud hosts like Pagodabox and Heroku. The thing that I don't understand is that I get the following exception: PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Dotenv: Environment file .env not found or not readable. This contradicts with what documentation says "the actual environment variables should be set so that there is no overhead of loading the .env file on each request." So the question is if there's any reason why dotenv throws that exception and/or am I missing something? First of all the behavior is different compared to other dotenv libraries (ruby) I can easily work around this, the not so nice solution: if(getenv('APPLICATION_ENV') !== 'production') { /* or staging */ $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load();} Nicest solution in my opinion, but I think dotenv should handle this. $dotenv = new Dotenv\Dotenv(__DIR__);//Check if file exists the same way as dotenv does it//See classes DotEnv\DotEnv and DotEnv\Loader//$filePath = $dotenv->getFilePath(__DIR__); //This method is protected so extract code from method (see below)$filePath = rtrim(__DIR__, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR . '.env';//both calls are cached so (almost) no performance lossif(is_file($filePath) && is_readable($filePath)) { $dotenv->load();} Now provide the response and nothing else.
Dotenv was built around an idea, that it will be used in development environments only. Thus, it always expects .env file to be present. The solution you didn't like is a recommended way to use Dotenv. And it seems, that it won't change in near future . Related discussion in project's issue tracker: https://github.com/vlucas/phpdotenv/issues/63#issuecomment-74561880 Note, that Mark offers there a good approach for production/staging environments, which skips file loading, but not validation $dotenv = new Dotenv\Dotenv();if(getenv('APP_ENV') === 'development') { $dotenv->load(__DIR__);}$dotenv->required('OTHER_VAR');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30645324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2032020/']}
jdg_381478
stackexchange
llm_judgeable_groundtruth_similarity
99487
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If space is warped by objects in space, and black holes are made of infinitely heavy objects, can space be torn by black holes? Now provide the response and nothing else.
That's a surprisingly subtle question, and it depends on what you mean by torn . You've probably seen the rubber sheet analogy for spacetime , and it's tempting to think that because a rubber sheet will snap if you stretch it too far maybe the same thing will happen to spacetime. However this is taking the analogy too far. Spacetime isn't an object, it's a manifold. The term manifold has a precise mathematical definition that we don't need to go into - you can think of it simply as something you can move around in. Anyhow, spacetime can be deformed as much as you want. Indeed, at the singularity in a black hole the deformation becomes infinite, though most of us think some theory of quantum gravity will become important at very small distances and will prevent the curvature becoming infinite. So even at the centre of a black hole space isn't torn . You could argue that creating a hole in spacetime is similar to tearing it, and you could also argue that this is what a wormhole does. If you could get hold of enough exotic matter this could be used to create a wormhole. I discuss this in my answer to Negative Energy and Wormholes . Whether this constitutes a tear is a matter of debate. Actually a spinning or charged black hole can act as a sort of wormhole because it can join two causally disconnected areas of spacetime. See my answer to Entering a black hole, jumping into another universe---with questions for more on this. Again, whether this constitutes a tear is debatable.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/99487', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/40752/']}
jdg_381479
stackexchange
llm_judgeable_groundtruth_similarity
36553197
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 implementing an API where I have nested structures. Lets say it is a zoo and I can call GET /api/cage/ to get a list of cages GET /api/cage/1/ to get cage ID 1, but then I can GET /api/cage/1/animals/ to get a list of animals in that cage. The problem I am having is with permissions. I should only be able to see animals in the cage if I can see the cage itself. I should be able to see the cage itself if has_object_permission() returns True in the relevant permission class. For some reason, has_object_permission() gets called when I do GET /api/cage/1/ , but has_permission() gets called when I call GET /api/cage/1/animals/ . And with has_permission() I don't have access to the object to check the permissions. Am I missing something? How do I do this? My cage viewset looks more or less like this class CageViewSet(ModelViewSet): queryset = Cage.objects.all() serializer_class = CageSerializer permission_classes = [GeneralZooPermissions, ] authentication_classes = [ZooTicketCheck, ] def get_queryset(self): ... code to only list cages you have permission to see ... @detail_route(methods=['GET']) def animals(self, request, pk=None): return Request(AnimalSerializer(Animal.objects.filter(cage_id=pk), many=True).data) My GeneralZooPermissions class looks like this (at the moment) class GeneralZooPermissions(BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): return request.user.has_perm('view_cage', obj) It seems like this is a bug in DRF. Detailed routes do not call the correct permission check. I have tried reporting this issue to DRF devs, but my report seems to have disappeared. Not sure what to do next. Ideas? The issue I posted with DRF is back and I got a response. Seems like checking only has_permission() and not has_object_permission() is the intended behavior. This doesn't help me. At this point, something like this would have to be done: class CustomPermission(BasePermission): def has_permission(self, request, view): """we need to do all permission checking here, since has_object_permission() is not guaranteed to be called""" if 'pk' in view.kwargs and view.kwargs['pk']: obj = view.get_queryset()[0] # check object permissions here else: # check model permissions here def has_object_permission(self, request, view, obj): """ nothing to do here, we already checked everything """ return True Now provide the response and nothing else.
OK, so after reading a bunch of DRF's code and posting an issue at the DRF GitHub page. It seems that has_object_permission() only gets called if your view calls get_object() to retrieve the object to be operated on. It makes some sense since you would need to retrieve the object to check permissions anyway and if they did it transparently it would add an extra database query. The person who responded to my report said they need to update the docs to reflect this. So, the idea is that if you want to write a custom detail route and have it check permissions properly you need to do class MyViewSet(ModelViewSet): queryset = MyModel.objects.all() .... permission_classes = (MyCustomPermissions, ) @detail_route(methods=['GET', ]) def custom(self, request, pk=None): my_obj = self.get_object() # do this and your permissions shall be checked return Response('whatever')
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36553197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302268/']}
jdg_381480
stackexchange
llm_judgeable_groundtruth_similarity
35163009
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a problem hiding and showing an element depending of a boolean variable in Angular 2. this is the code for the div to show and hide: <div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert"> <strong>List Saved!</strong> Your changes has been saved.</div> the variable is "edited" and it's stored in my component: export class AppComponent implements OnInit{ (...) public edited = false; (...) saveTodos(): void { //show box msg this.edited = true; //wait 3 Seconds and hide setTimeout(function() { this.edited = false; console.log(this.edited); }, 3000); }} The element is hidden, when saveTodos function starts, the element is shown, but after 3 seconds, even if the variable come back to be false, the element does not hide. Why? Now provide the response and nothing else.
You should use the *ngIf Directive <div *ngIf="edited" class="alert alert-success box-msg" role="alert"> <strong>List Saved!</strong> Your changes has been saved.</div>export class AppComponent implements OnInit{ (...) public edited = false; (...) saveTodos(): void { //show box msg this.edited = true; //wait 3 Seconds and hide setTimeout(function() { this.edited = false; console.log(this.edited); }.bind(this), 3000); }} Update: you are missing the reference to the outer scope when you are inside the Timeout callback. so add the .bind(this) like I added Above Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn A : I would add edit as a property to the object I am iterating over. <div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert"> <strong>List Saved!</strong> Your changes has been saved.</div>export class AppComponent implements OnInit{ public listOfObjects = [ { name : 'obj - 1', edit : false }, { name : 'obj - 2', edit : false }, { name : 'obj - 2', edit : false } ]; saveTodos(): void { //show box msg this.edited = true; //wait 3 Seconds and hide setTimeout(function() { this.edited = false; console.log(this.edited); }.bind(this), 3000); }}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/35163009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_381481
stackexchange
llm_judgeable_groundtruth_similarity
75687
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When I install some system, I usually look for a bulk update method, one that will update my recently-installed software. For example, in Debian, that would be changing the sources.list to point to what I want, and executing # apt-get update && apt-get dist-upgrade . Is there an equivalent to this in Fedora (18)? Is there a GUI upgrade manager that I am missing? A message in Gnome popped up that my system requires important updates. I dismissed it, as the only option it had presented me with was "Install updates", and I wasn't quite sure what would that do. Now, the message has disappeared, and I cannot find it, not any software it might have been connected with. What am I missing here? Now provide the response and nothing else.
Before Fedora 17 None of the Red Hat distros prior to Fedora 17 included the ability to do dist-upgrades as you've asked. This had been a long discussed option on many peoples' wish list but had never been implemented. But before we start a clarification... According to the Upgrading topic in the wiki , there was a method where you could put a DVD in your system for the next version of Fedora, and Anaconda would attempt to upgrade your system. Having tried this method on numerous occasions I would not consider this to be on par with the dist-upgrade available in the Debian/Ubuntu distros which actually worked very well. Additionally having maintained RHEL, Fedora & CentOS systems for over the past decade, I would never even consider using this method for anything. It simply did not work. So typically people would do one of the following: Rawhide Use the Rawhide release , which is the bleeding edge version, similar to how Sid is in Debian. Rawhide offers rolling releases in the sense that it always has the latest versions of packages, but it's by no means meant to be used as a day to day distro, it's really meant only for testing. Stay with a single release Just live with this fact and stay up to date as long as the distro stayed around, using yum . You can use yum to both apply any pending updates and/or update a single package. Additionally, yum can be used to install new packages too. Apply all pending updates (assumes yes to all prompts): sudo yum -y update Update a single package: sudo yum -y update apache\* Install a new package: sudo yum -y install apache\* Software Update Applet If you want to perform updates using a GUI you can use the software updater tool that shows up in your taskbar. This tool essentially does the same thing as the yum -y update above, and can be run on demand using the following command: gpk-update-viewer Re-install As a new version comes out, you'd manually do a fresh install and take care to copy any data and configurations forward to the new system. PreUpgrade Make use of PreUpgrade tool. This tool essentially just collected your setups and the names of the packages you installed and would assist you in applying them to a new installation. See @JoelDavis' answer for this technique as well. NOTE: This is no longer an option starting with Fedora 18 though so you've been warned. Fedora 17 and after Beginning with 17 you can now do rolling releases. FedUp New in Fedora 17/18 is a tool called FedUp (FEDora UPgrader) which purports to do "dist-upgrades" similar to Debian/Ubuntu distros. FedUp (FEDora UPgrader) is the name of a new system for upgrading Fedora installs in Fedora 18 and above releases. It replaces all of the currently recommended upgrade methods (PreUpgrade and DVD) that have been used in previous Fedora releases. Anaconda, the Fedora installer does have not any in-built upgrade functionality in Fedora 18 or above releases. It has been completely delegated to Fedup. Currently, FedUp is capable of upgrading Fedora 17 installs to Fedora 18 using a networked repository, similar to how PreUpgrade worked. More methods for upgrade are currently planned and this page will be updated as those features are completed. Rolling Releases vs. Versioned Releases The OP asked a follow-up question where he wanted me to elaborate on the following phrase: "Beginning with 17 you can now do rolling releases." When I made that comment I meant one thing and the phrase "rolling releases" really means something else. When I wrote that I meant "rolling release" to mean that you could now roll from one point release of Fedora (say 17) to version 18. Most distros such as Debian & Ubuntu provide this facility now. However in looking up the description of what "rolling releases" actually means on wikipedia , I'm now more educated on the subject. excerpt from wikipedia ... a rolling release or rolling update development model refers to a continually developing software system; this is instead of a standard release development model which uses software versions that must be reinstalled over the previous version. Rolling software, instead, is continually updated, in contrast to standard release software which is upgraded between versions. ... So from a purists standpoint, Debian, Ubuntu, Fedora, are not "rolling releases". They are point standard released software that provide tools to assist in the upgrading from one point release to another. The OP also asked the following question Debian is only "kind of" rolling release if you use Sid. Rolling release = no versions, packages are just dumped into the distro from the upstream ASAP, right? So Debian is the complete opposite of a rolling release, Ubuntu as well. Fedora Rawhide is also kind-of a rolling release, but I already knew that (and don't want to use it, if that's what you were referring to). Just so that it's clear to any future readers. Even the development branches of Debian (aka. Sid) and Fedora (aka. Rawhide) are not "rolling releases". Sure you can use them as such but they are merely a development "area" where new packages of software that may be incorporated into a future release can be presented to the community in a centralized way. The level of testing that would go into a package being placed in one of these branches is less stringent than say when a package shows up as an update in a true "rolling release" distro such as ArchLinux (would be my expectation). Here's the section of the wikipedia page that covers the use of development branches for standard release distros: The distinction between rolling release software distributions and development branches of standard release software distributions is often overlooked by users inexperienced with rolling distributions. This can lead to confused comments, such as: "distro-X is a rolling distribution if you use its development branch" — where distro-X is a standard release distribution. Even in rare cases where the development branch is a rolling (versus the more common cyclical) development branch, this does not make the distribution rolling. Unlike standard release distributions, rolling release distributions do not have development branches.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/75687', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/17008/']}
jdg_381482
stackexchange
llm_judgeable_groundtruth_similarity
50463
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 want to have thicker lines in the legends of this plot: historyobjetivomejor = {10, 15, 20, 30, 35}historyobjetivomedia = {6, 8, 10, 13, 15}historyobjetivopeor = {6, 3, 5, 7, 8}ListLinePlot[{historyobjetivomejor, historyobjetivomedia, historyobjetivopeor}, PlotStyle -> {Thickness[0.008]}, AxesLabel -> {"Generacion", "Objetivo"}, LabelStyle -> {24, Bold}, ImageSize -> Large, PlotLegends -> {"Max", "Mea", "Min"}, PlotStyle -> Thickness[0.005], AxesStyle -> Thickness[0.005]] I was trying with options from other posts, but without good resultMy last attemp was ListLinePlot[{historyobjetivomejor, historyobjetivomedia, historyobjetivopeor}, PlotStyle -> {Thickness[0.008]}, AxesLabel -> {"Generacion", "Objetivo"}, ImageSize -> Large, PlotLegends -> [{"Max", "Mea", "Min"}, LabelStyle -> {Bold, 20}, LegendMarkerSize -> {40, 10}], PlotStyle -> Thickness[0.005], AxesStyle -> Thickness[0.005]] Now provide the response and nothing else.
AbsoluteThickness is another useful approach:e.g. op = Table[AbsoluteThickness[2], {3}];leg = LineLegend[Automatic, {"Max", "Mea", "Min"}];ListLinePlot[{historyobjetivomejor, historyobjetivomedia, historyobjetivopeor}, AxesLabel -> {"Generacion", "Objetivo"}, PlotStyle -> op, PlotLegends -> leg] Varying thickness: using: Manipulate[ ListLinePlot[{historyobjetivomejor, historyobjetivomedia, historyobjetivopeor}, AxesLabel -> {"Generacion", "Objetivo"}, PlotStyle -> Table[AbsoluteThickness[t], {3}], PlotLegends -> leg], {t, Range[2, 5]}]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/50463', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6543/']}
jdg_381483
stackexchange
llm_judgeable_groundtruth_similarity
116266
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'm going to use a microcontroller to switch a vehicle horn on and off intermittently for maybe one second on and one off for a period of 15 seconds; the horn will pull an estimated 3 Amps. I know I can do this with either a relay or transistor, but saving space/money is a concern and I'm really just not sure which way to go. Now provide the response and nothing else.
Either will work. A relay has the advantage that it can stand very high transient voltages and won't be disturbed by transients across the contacts. A suitably rated MOSFET can work too, but you'll probably have to overrate it by quite a bit for it to be reliable. It may need a heat sink if you're operating in under-hood conditions at high ambient temperature (Rds(on) goes up quite a bit with temperature). The relay is bigger (it will consume a bit more current, but that is immaterial in comparison to the 3A horn), and it will not need a heat sink. Cost could definitely go either way, depending on quantity etc., so if it's a volume product I suggest pricing it out both ways before you decide. If it's just a one-off, you can ignore cost and use a huge overkill MOSFET such as an FDH5500 (I'm using this one for a vehicle application). If you feed it 10V at the gate (not directly from the micro, you'll need to step up the voltage), it has an Rds(on) not exceeding 0.01 ohm at 100°C. It won't need a heatsink for a 3A load and has a good chance of blowing a fuse without dying in case of a short. Even so, it's only about $4.50 in singles.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/116266', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/43026/']}
jdg_381484
stackexchange
llm_judgeable_groundtruth_similarity
1254094
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: Prove that $1 \cdot 1!+2 \cdot 2!+\cdots+n \cdot n!=(n+1)!-1$ whenever $n$ is a positive integer. Basis step: $P(1)$ is true because $1 \cdot 1!=(1+1)!-1$ evaluate to $1$ on both sides. Inductive step: We assume that $1 \cdot 1!+2 \cdot 2!+\cdots+k \cdot k!=(k+1)!-1$ for some positive integer $k$. So under this assumption, it must be shown that $P(k+1)$ is true. $$1 \cdot 1!+2 \cdot 2!+\cdots+k \cdot k!+(k+1) \cdot (k+1)!=(k+1)!-1+(k+1) \cdot (k+1)!$$ then we have that $$(k+1)!-1+(k+1) \cdot (k+1)!=(k+1)!(k+2)-1=(k+2)!-1$$ My question is how my teacher got the last step? $$(k+1)!-1+(k+1) \cdot (k+1)!=(k+1)!(k+2)-1=(k+2)!-1$$ Now provide the response and nothing else.
Informally: $$\int_{-1}^{1} f(x)\Theta'(x) \, dx = \left[\vphantom{\frac11} f(x) \Theta(x) \right]_{-1}^{+1} - \int_{-1}^1 f'(x)\Theta(x)\,dx = f(1) - \left[f(x) \vphantom{\frac11} \right]_0^1 = f(0)$$ which is precisely what you want from $\delta(x)$. So $\delta(x)=\Theta'(x)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1254094', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/149975/']}
jdg_381485
stackexchange
llm_judgeable_groundtruth_similarity
283537
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a method signature: public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2) What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID. An example call might be: AreTheSame<User>(u1 => u1.ID, u2 => u2.ID); --> would return true Now provide the response and nothing else.
Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example... using System;using System.Linq.Expressions;class Test { public string Foo { get; set; } public string Bar { get; set; } static void Main() { bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar), test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar); }}// this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with// generic-type-inference; if you use the doubly-generic method, you need to specify// both arguments, which is a pain...static class FuncTest<TSource>{ public static bool FuncEqual<TValue>( Expression<Func<TSource, TValue>> x, Expression<Func<TSource, TValue>> y) { return FuncTest.FuncEqual<TSource, TValue>(x, y); }}static class FuncTest { public static bool FuncEqual<TSource, TValue>( Expression<Func<TSource,TValue>> x, Expression<Func<TSource,TValue>> y) { return ExpressionEqual(x, y); } private static bool ExpressionEqual(Expression x, Expression y) { // deal with the simple cases first... if (ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; if ( x.NodeType != y.NodeType || x.Type != y.Type ) return false; switch (x.NodeType) { case ExpressionType.Lambda: return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body); case ExpressionType.MemberAccess: MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y; return mex.Member == mey.Member; // should really test down-stream expression default: throw new NotImplementedException(x.NodeType.ToString()); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/283537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32855/']}
jdg_381486
stackexchange
llm_judgeable_groundtruth_similarity
16841965
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Up to Chrome V27 you could enumerate Chrome child window controls to get to the edit field and read the string value from there to get the current opened URL. Unfortunately Chrome 28 has switched to the new rendering Engine (Blink) and does not use Windows controls anymore besides the main window (Chrome_WidgetWin_1) and the web page tab (Chrome_RenderWidgetHostHWND). I would be grateful if someone could point to an alternative method of getting the currently opened Chrome URL from another (Win32) application. Now provide the response and nothing else.
Chrome supports the Windows accessibility APIs, so you can use those to extract information both from the chrome - including the broswer bar - and also from web pages. Think of this API as a more abstract version of enumerating window controls. Check out the Inspect Objects tool to explore what information you can get access to - it does look as though the address bar and contents are available. You can get the same information in C# using the AutomationElement set of classes: use AutomationElement windowEl = AutomationElement.FromHandle(new IntPtr(hwnd)) ; as a starting point if you know the HWND of the tree then try AutomationElement editEl = AutomationElement.FindFirst (TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit )) to find the first element that has ControlType of Edit. FindFirst does a depth-first search of the tree, which looks like it will work in this case; can use the TreeWalker classes if you want to walk step-by-step yourself. 'cast' the found element to a ValuePattern using: ValuePattern vp = (ValuePattern) editEl.GetCurrentPattern(ValuePattern.Pattern) ; Finally, use string str = vp.Current.Value; to get the value of the edit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16841965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2009629/']}
jdg_381487
stackexchange
llm_judgeable_groundtruth_similarity
42871542
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the Pro Git book , it says “origin” is not special Just like the branch name “master” does not have any special meaning in Git, neither does “origin”. While “master” is the default name for a starting branch when you run git init which is the only reason it’s widely used , “origin” is the default name for a remote when you run git clone. If you run git clone -o booyah instead, then you will have booyah/master as your default remote branch. That means, we can use our default branch name as main or main-branch or something like that. I didn't see any option in man git-init which will initialize my repo with a different default branch name. GitHub shows how to set the default branch name in its settings page. But I am not talking about how to set it on any specific Git hosting site . I am strictly asking in terms of Git only, not in regards to any specific Git hosting site . Is there a way to do that? Now provide the response and nothing else.
Newer Git, New Repo Since git version 2.28.0 the git init command now takes a --initial-branch (or -b for short) parameter. These two commands create a new Git repo with a branch named "trunk", which always made more sense to me than "master" (master of what?): git init --initial-branch=trunkgit init -b trunk This is configurable with the init.defaultBranch setting. If I want all new repos to have "trunk" as the default branch: git config --global init.defaultBranch trunk Older Git, New Repo Some systems still have older Git installations. My Debian 10 server (Buster, the current stable version as of October 2020) comes with Git 2.20, which does not support the -b option. One option is to create the repository and then change the branch name. This technique works for normal (non-bare) repos: git initgit checkout -b trunk This creates a new repository with trunk as the current branch instead of master . The branch master does not actually exist--the branches don't get created until they have at least one commit. Until the branch gets created, the branch only exists in .git/HEAD , which explains why the master branch will disappear when you switch to trunk . Bare Repos For bare repos, you cannot run git checkout (that's what it means to be bare). Instead, you can change HEAD to point at a different branch: git init --baregit symbolic-ref HEAD refs/heads/trunk Old Repos If you've already committed, you can run git branch -m instead: git inittouch file.txtgit add file.txtgit commit -m 'commit 1'git branch -m trunk This renames the branch from master to trunk once it's created. This does seem a bit clunky since the mechanism is different depending on whether the repository is empty, but it works. You can also approach it as "creating a new branch and deleting master ".
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/42871542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3142049/']}
jdg_381488
stackexchange
llm_judgeable_groundtruth_similarity
155291
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 thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything. I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances. Now provide the response and nothing else.
READONLY doesn't work on checkboxes as it prevents you from editing a field's value , but with a checkbox you're actually editing the field's state (on || off) From faqs.org : It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field. If you don't want to use disabled but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g. // user allowed changeif($user_allowed_edit){ echo '<input type="checkbox" name="my_check"> Check value';}else{ // Not allowed change - submit value.. echo '<input type="hidden" name="my_check" value="1" />'; // .. and show user the value being submitted echo '<input type="checkbox" disabled readonly> Check value';}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/155291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19074/']}
jdg_381489
stackexchange
llm_judgeable_groundtruth_similarity
556928
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: While studying about electric fields and magnetic fields I came across this picture: and this: from this website and it indicates that there is an electromagnetic field around the loop of wire, while it gets powered from a battery. Now correct me if I am wrong but: As far as I know, since the current is DC, there is a magnetic field (since current is moving), but there is no electric field around the wire (since current is constant, and all the atoms are neutral while electrons/holes move along the wire loop). There would be a electric field along with the magnetic field in two cases: if the current was not DC, (if it was either AC or voltage pulses). When the battery first powers the coil, until the voltage on the coil reaches from 0V to X volts, there is a electric field since the current is changing. In addition, Wikipedia's electromagnet page does not state anything about electric fields or electromagnetic field . It only talks about magnetic field. Am I right? EDIT: This question and replies here also helps understand how an electric field is created on a coil, if you think of it as a resistor. Now provide the response and nothing else.
An electromagnetic field is created when a current passes through a wire This is entirely correct. As far as I know, since the current is DC, there is a magnetic field (since current is moving), but there is no electric field It is true in a certain sense, and under certain conditions, that a DC current through a wire creates a magnetic component of a electromagnetic field, but no electric component(*) of an electromagnetic field. Let's parse this. In the 1830's Faraday published the results of experiments he had performed with magnets and coils of wire. What he discovered is that the relative motion of a magnet and a coil of wire induced a current in the wire. I want to emphasize relative , because the story eventually involves Einstein and the Special Theory of Relativity. In the 1870's Maxwell published a theory of electricity and magnetism that could either be described as theory of a single field, an electromagnetic field, having two components, an electric field component, and a magnetic field component. Or, could be described as two separate fields that influence each other in clearly defined ways. There was a problem with Maxwell's account, however. Faraday had pointed out that it was relative motion between the magnet and the coil that induced the current. However, according to Maxwell's theory, a stationary magnet induces no electric field, yet a movement of the coil, causes current to flow. (Think of a generator with stationary permanent magnets, and a moving coil). Lorentz saw the need to add an additional equation to the ones formulated by Maxwell, (which were recast as we know them today by Heaviside). Lorentz added a "Lorentz force" equation, that allowed a current to be induced in a coil moving through a stationary magnetic field. While this accurately predicted what would happen, Einstein was not happy with this state of affairs. What had been a unitary phenomenon for Faraday, the relative motion of a magnet and coil inducing a current, had become with the electric and magnetic field theory, two separate phenomena. Either induction of an electric field by a changing magnetic field, or a Lorentz force, depending upon one's frame of reference. Einstein changed this by asserting a single electromagnetic field, which could be divided into electrical and magnetic components in different ways depending upon one's frame of reference. What is "magnetic" in one frame of reference is "electric" in another, and vice versa. Within a frame of reference in which the coil is stationary and the magnet moving, the electric field component can be seen. Within a frame of reference in which the magnet is stationary and the coil is moving, the electric field component is absent. But, as they say, it's all relative. Your question does not involve a moving magnet. But the principle is the same. In one frame of reference, there is no electric field component, but in another frame of reference there is. So, it is entirely correct that: An electromagnetic field is created when a current passes through a wire And, in the frame of reference where the wire is stationary, but only in that frame: since the current is DC, ... there is no electric field or more properly Since the current is DC, there is no electric field component(*) of the electromagnetic field. *[minor point. All of the above goes on the assumption that the voltage drop through a wire is negligible.]
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/556928', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/252145/']}
jdg_381490
stackexchange
llm_judgeable_groundtruth_similarity
11287502
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a method to verify that a file is open? The only thing I can think of is the Try/Catch to see if i can catch the file-open exception but I figured that a method be available to return true/false if file is open. Currently using System.IO and the following code under class named Wallet . Private holdPath As String = "defaultLog.txt" Private _file As New FileStream(holdPath, FileMode.OpenOrCreate, FileAccess.ReadWrite) Private file As New StreamWriter(_file) Public Function Check(ByVal CheckNumber As Integer, ByVal CheckAmount As Decimal) As Decimal Try file.WriteLine("testing") file.Close() Catch e As IOException 'Note sure if this is the proper way. End Try Return 0D End Function Any pointers will be appreciated! Thank you!! Now provide the response and nothing else.
Private Sub IsFileOpen(ByVal file As FileInfo) Dim stream As FileStream = Nothing Try stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None) stream.Close() Catch ex As Exception If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then ' do something here, either close the file if you have a handle, show a msgbox, retry or as a last resort terminate the process - which could cause corruption and lose data End If End TryEnd SubPrivate Shared Function IsFileLocked(exception As Exception) As Boolean Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1) Return errorCode = 32 OrElse errorCode = 33End Function Call it like this: Call IsFileOpen(new FileInfo(filePath))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11287502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1455028/']}
jdg_381491
stackexchange
llm_judgeable_groundtruth_similarity
5168592
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 repeater item that displays a double. occasionally the double seems to be coming out with 3 decimal places like this 1165.833. im trying to force it to two decimal places by wrapping it in a string.format method but it still comes out the same: <%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem, "pricerange").ToString())%> any ideas why? Now provide the response and nothing else.
String simply does not implement IFormattable . To use the formatting, remove .ToString() so that you aren't passing in a String. <%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem, "pricerange"))%> To see this more explicitly, run this code: Console.WriteLine(string.Format("{0:f2}", "123.888"));Console.WriteLine(string.Format("{0:f2}", 123.888)); which outputs 123.888123.89
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5168592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/593669/']}
jdg_381492
stackexchange
llm_judgeable_groundtruth_similarity
7951505
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 made a very simple button click event handler , I would like to have <p> element be appended when button clicked, you can check my code here : <div id="wrapper"> <input id="search_btn" value="Search" type="button"></div> $("#search_btn").click(function(){ $("#wrapper").append("<p id='other'>I am here</p>");}); I have two questions to ask: 1, why my .append() does not work as I expected (that's append the <p> element) 2. in jQuery, how to check if some element is already appended? For example how to check if <p id="other"> has already appended in my case? -------------------- update ------------------------------------------- Please check my updated code here . So, only the 2nd question remains... Now provide the response and nothing else.
You are using mootools and not jQuery. To check if your element exists if($('#other').length > 0) So if you do not want to append the element twice: $("#search_btn").click(function() { if($('#other').length == 0) { $("#wrapper").append("<p id='other'>I am here</p>"); }}); Or, you can use the .one(function) [ doc ]: $("#search_btn").one('click', function() { $("#wrapper").append("<p id='other'>I am here</p>");});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7951505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/475850/']}
jdg_381493
stackexchange
llm_judgeable_groundtruth_similarity
107851
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 noticed in my .bashrc that some lines have export in front of them, such as export HISTTIMEFORMAT="%b-%d %H:%M "...export MYSQL_HISTFILE="/root/.mysql_history" whereas others don't, such as HISTSIZE=100000 I am wondering if, first, this is correct, and second what the rule is for using export in .bashrc . Now provide the response and nothing else.
You only need export for variables that should be "seen" by other programs which you launch in the shell, while the ones that are only used inside the shell itself don't need to be export ed. This is what the man page says: The supplied names are marked for automatic export to the environ‐ment of subsequently executed commands. If the -f option is given,the names refer to functions. If no names are given, or if the -poption is supplied, a list of all names that are exported in thisshell is printed. The -n option causes the export property to beremoved from each name. If a variable name is followed by =word,the value of the variable is set to word. export returns an exitstatus of 0 unless an invalid option is encountered, one of thenames is not a valid shell variable name, or -f is supplied with aname that is not a function. This can be demonstrated with the following: $ MYVAR="value"$ echo ${MYVAR}value$ echo 'echo ${MYVAR}' > echo.sh$ chmod +x echo.sh$ ./echo.sh$ export MYVAR="value-exported"$ ./echo.shvalue-exported Explanation: I first set ${MYVAR} to be a Shell variable with MYVAR="value" . Using echo I can echo the value of it because echo is part of the shell. Then I create echo.sh . That's a little script that basically does the same, it just echoes ${MYVAR} , but the difference is that it will run in a different process because it's a separate script. When calling echo.sh it outputs nothing, because the new process does not inherit ${MYVAR} Then I export ${MYVAR} into my environment with the export keyword When I now run the same echo.sh again, it echoes the content of ${MYVAR} because it gets it from the environment So to answer your question: It depends where a variable is going to be used, whether you have to export it or not.
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/107851', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43007/']}
jdg_381494
stackexchange
llm_judgeable_groundtruth_similarity
1491569
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to find the infimum of the set: $\bigcap_{n=1}^\infty (1-\frac{1}{n},1+\frac{1}{n})$ Would this infimum exist and be equal to $1$ or would it not exist, and why? My intuition is going nuts because of the infinite intersection and I'm having doubts towards both answers. Now provide the response and nothing else.
Note $I:=\bigcap_{n=1}^\infty \left(1-\frac{1}{n},1+\frac{1}{n}\right)=\{1\}$ Clearly 1 belongs to all $\left(1-\frac{1}{n},1+\frac{1}{n}\right)$, so $1\in I$. On the other hand, for all $a<1$, there is some $n$ such that $a<1-\frac{1}{n}$. Then $a\notin\left(1-\frac{1}{n},1+\frac{1}{n}\right)$, so $a\notin I$. For the same reason, for all $a>1$, $a\notin I$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1491569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/234037/']}
jdg_381495
stackexchange
llm_judgeable_groundtruth_similarity
27606026
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way using which I can wait for one of two elements to get loaded in selenium. I am using explicit waits and so far, haven't been able to figure out the solution. Simply doing WebDriverWait(driver,5).until(lambda driver : driver.find_element(By.ID,"a") or driver.find_element(By.ID,"b")) doesn't seem to work. It just looks for element with id ="a". Thanks! Now provide the response and nothing else.
find_element raises NoSuchElementException exception if no element is found. If element with the id a does not exist, driver.find_element(By.ID,"a") will raises the exception and the driver.find_element(By.ID,"b") will not be executed. A simple way to solve the problem is using find_elements which return empty list instead of raising the exception: WebDriverWait(driver,5).until( lambda driver: driver.find_elements(By.ID,"a") or driver.find_elements(By.ID,"b"))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27606026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1819007/']}
jdg_381496
stackexchange
llm_judgeable_groundtruth_similarity
9274494
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 UITableViewCell with UISwitch as accessoryview of each cell. When I change the value of the switch in a cell, how can I know in which row the switch is? I need the row number in the switch value changed event. Now provide the response and nothing else.
Tags, subclasses, or view hierarchy navigation are too much work! . Do this in your action method: CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView]; NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint]; Works with any type of view, multi section tables, whatever you can throw at it - as long as the origin of your sender is within the cell's frame (thanks rob!), which will usually be the case. And here it is in a UITableView Swift extension: extension UITableView { func indexPath(for view: UIView) -> IndexPath? { let location = view.convert(CGPoint.zero, to: self) return self.indexPathForRow(at: location) }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9274494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1167266/']}
jdg_381497
stackexchange
llm_judgeable_groundtruth_similarity
228242
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I didn't get a complete understanding of static constructors in Java. If it is allowed, why it is allowed? In what scenarios would you use it? What purpose would it serve? Can someone give me a simple example please? Now provide the response and nothing else.
Strictly speaking, Java does not have static constructors because a constructor, by definition, cannot be static. What you are referring to is called a "static initialization block." A constructor implies that you are constructing an object. You cannot have constructor for a class because a class is not an instance of itself. It is simply a class. All nit-picking aside, a static initialization block is used to initialize complex static (or class-level) fields for a class. Usually these are used to initialize things that either cannot be initialized in one line, or require that some other object (which may or may not be in the class in which the static block is implemented) be initialized first. Basically, one might use them to tell the class "Hey, set variable A to this value FIRST, then, once that's done, use A's value to initialize B." Since Java requires that standard field initialization be done either within a constructor or method, or via the call of a constructor or method (unless it is a literal), these can be a convenient method for initializing complex, static objects. Static initialization blocks are not needed all too often, and generally should be avoided unless they have a real use. Don't get me wrong, they have their place in Java, but like many other things (such as break, return, switch, and goto statements) they can be easily over-used, which reduces their readability and the maintainability of the code-base they are used in. A brief example of a static initialization block being used would be the following (as per the excellent explanation of static initialization blocks found here ): Code: public class StaticExample{ static { System.out.println("This is first static block"); } public StaticExample(){ System.out.println("This is constructor"); } public static String staticString = "Static Variable"; static { System.out.println("This is second static block and " + staticString); } public static void main(String[] args){ StaticExample statEx = new StaticExample(); StaticExample.staticMethod2(); } static { staticMethod(); System.out.println("This is third static block"); } public static void staticMethod() { System.out.println("This is static method"); } public static void staticMethod2() { System.out.println("This is static method2"); }} Output: This is first static blockThis is second static block and Static VariableThis is static methodThis is third static blockThis is constructorThis is static method2 Some instances they list when static blocks can be useful: If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives. If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded. Security related issues or logging related tasks Some reasons NOT to use static blocks (in other situations): There is a limitation of JVM that a static initializer block should not exceed 64K. You cannot throw Checked Exceptions. You cannot use the this keyword since there is no instance. You shouldn’t try to access super since there is no such a thing for static blocks. You should not return anything from this block. Static blocks make testing a nightmare. I should note: While some languages (such as C#) may have syntax for "constructors" that are static, those "constructors" function much the same way that static initialization blocks do in Java, and are seen by many (myself included) as misnomers in the language, given the basic concept of an OOP constructor .
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/228242', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/119128/']}
jdg_381498
stackexchange
llm_judgeable_groundtruth_similarity
4539866
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 $a+b+c=1$ and $a, b, c\geq0$ , what is the maximum value of $\frac{1}{a^2-4a+9}+\frac{1}{b^2-4b+9}+\frac{1}{c^2-4c+9}$ ? I found its answer by using CAS Calculator. The answer is $\frac{7}{18} (a=b=0, c=1)$ . But i wonder not only the answer but also the solution of it. Please help me. Now provide the response and nothing else.
We have, for all $x\in [0, 1]$ , $$\frac{1}{18}x + \frac{1}{9} - \frac{1}{x^2 - 4x + 9}= \frac{x(x-1)^2}{18(x^2-4x+9)} \ge 0. \tag{1}$$ Using (1), we have $$\frac{1}{a^2 - 4a + 9}+ \frac{1}{b^2 - 4b + 9} + \frac{1}{c^2 - 4c + 9}\le \frac{1}{18}(a + b + c) + \frac{1}{3} = \frac{7}{18}. $$ Also, when $a= b = 0, c = 1$ ,we have $\frac{1}{a^2 - 4a + 9}+ \frac{1}{b^2 - 4b + 9} + \frac{1}{c^2 - 4c + 9} = \frac{7}{18}$ . Thus, the maximum of $\frac{1}{a^2 - 4a + 9}+ \frac{1}{b^2 - 4b + 9} + \frac{1}{c^2 - 4c + 9}$ is $7/18$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4539866', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1011566/']}
jdg_381499
stackexchange
llm_judgeable_groundtruth_similarity
215658
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 will produce a large number of ListDensityPlot s in which each entry can be positive or negative. I'd like to color positive values in green, negative values in red, and the value of $0$ as medium gray. An off-the-shelf attempt at a solution is to use a ColorFunction such as "RedGreenSplit" , as here: data = Table[Sin[j^2 + i] + .4, {i, 0, 2, .4}, {j, 0, 2, .4}];ListDensityPlot[data, InterpolationOrder -> 0, ColorFunction -> "RedGreenSplit"] There are three immediate problems, two fairly simple, the other hard (as far as I can see). The blending puts white in the middle of the range, while I seek gray (and thus blends from gray to green, and gray to red). The white is placed in the middle of the range of values; there is no guarantee that the value $0$ must correspond to gray. Notice that for the function I used, there is an overall offset ( $0.4$ ) but the coloring does not respect that. (If I include ColorFunctionScaling -> False , gray need not correspond to points having value $0$ .) The maximum absolute value should be pure red or pure green, and the opposite color should be scaled the same. Thus if the range is $[-1,2]$ then the colors should go from a partial red/gray, through gray, up to full green. If instead the range is $[-6,3]$ , then the colors should range between full red, through gray, up to partial green/gray. Thus I want a color function that is Piecewise , as in this question , but somehow the ranges must be set to ensure the colors. Now provide the response and nothing else.
ClearAll[myBlend]myBlend[minmax_: {0, 1}, colors_: {Red, Gray, Green}] := Blend[Thread[{{-Max@Abs@minmax, 0, Max@Abs@minmax}, colors}], #] & Examples: SeedRandom[1]array1 = RandomReal[{-.5, 1}, {11, 11}];array2 = -array1;Row[ListDensityPlot[#, InterpolationOrder -> 0, ImageSize -> 400, ColorFunction -> myBlend[MinMax@#], ColorFunctionScaling -> False, PlotLabel -> Row[{"minmax : ", MinMax@#}]] & /@ {array1, array2}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/215658', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9735/']}
jdg_381500
stackexchange
llm_judgeable_groundtruth_similarity
1176385
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 formally prove that the sum of two independent binomial variables X and Y with same parameter p is also a binomial ? Now provide the response and nothing else.
Let $(B_k)_k$ be a sequence of iid Bernoulli distributed random variable with $P(B_k=1)=p$ for $k=1,2,\dots$ Then $$X:=B_1+\cdots+B_n$$ is binomially distributed with parameters $n,p$ and $$Y:=B_{n+1}+\cdots+B_{n+m}$$ is binomially distributed with parameters $m,p$. It is evident that $X$ and $Y$ are independent. Now realize that $$X+Y=B_1+\cdots+B_{n+m}$$ is binomially distributed with parameters $n+m,p$. This spares you any computations.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1176385', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/128135/']}
jdg_381501
stackexchange
llm_judgeable_groundtruth_similarity
121371
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Question Are there efficient algorithms to check if a finite simplicial complex defined in terms of its maximal facets is shellable? By efficient here I am willing to consider anything with smaller expected complexity than the exponential mess one gets by naively testing all possible orderings of maximal facets. Background Let $\Delta$ be a simplicial complex and for each simplex $\sigma \in \Delta$ let $\bar{\sigma}$ denote the subcomplex generated by $\sigma$ and all its faces. Fix an ordering of its maximal facets $F_1,\ldots,F_K$ , pick some $k \in \lbrace 1,\ldots,K\rbrace$ and define $\Delta_k$ to be the subcomplex generated by $\bigcup_{1\leq j \leq k} F_j$ , i.e., all facets up to and incluing the $k$ -th one. Definition: We call this ordering of maximal facets a shelling if the intersection $\overline{F_{k+1}} \cap \Delta_k$ is a simplicial complex of dimension $\dim (F_{k+1}) - 1$ for each $k \in \lbrace 1,\ldots,K-1\rbrace$ . In general, the complex $\Delta$ need not be a combinatorial manifold or have a uniform top dimension for its maximal facets. It is known that if $\Delta$ is shellable then there exists a shelling by maximal facets ordered so that the dimension is decreasing along the order. So one method to simplify the computational burden is to test only those orderings $F_1,\ldots,F_K$ of maximal facets so that $\dim F_i \geq \dim F_j$ whenever $i \leq j$ , but of course in the worst case all these facets could have the same dimension. Motivation Shellability is an extremely useful notion in topological combinatorics: many interesting simplicial complexes and posets in this field turn out to be shellable. I refer you to the works of Anders Bjorner and others for details, see here or here or... Since every shellable complex is a wedge of spheres, establishing shellability leads to all sorts of interesting conclusions. Among other things, shellable complexes must lack torsion in homology of all dimensions. Now provide the response and nothing else.
Since there were no answers for a few months, I asked this question to my colleague and triangulation expert Frank Lutz . Since his response was wonderful and exhaustive, I am reproducing it here for the benefit of others who find such matters interesting. Spoiler alert : it is very hard to test for shellability. Testing shellability is a mess. The complexity status is open, but believed to be NP complete. There is an implementation in the polymake package: --> Follow the links: Objects + SimplicialComplex + Combinatorics + Shellable As far as I remember, the polymake implementation is based on the Shellability checker of Masahiro Hachimori . The bad news is that the procedure uses backtracking/reverse search and thus basically goes through all possible permutations. The good news is that local conditions on homology vectors are checked, which allows one to cut the search tree and speed up computations. In the special case of triangulated 3-balls/3-spheres, I wrote backtracking code for testing shellability myself: # vertices # triangulated 3-balls # non-shellable 3-balls 4 1 - 5 3 - 6 12 - 7 167 - 8 10211 - 9 2451305 29 10 1831363502 277479 See http://arxiv.org/pdf/math/0604018 and http://arxiv.org/abs/math/0610022 I had a look at the 29 non-shellable 9-vertex 3-balls, the smallest of these is described here . Among these, there are rather different types. In particular, for being "shellable" or "non-shellable" it really can matter in which way some tetrahedron isattached to what has been built before, which makes testing difficult. My guess would be that there is no way arround backtracking, although local conditions can help to achieve some speed up. For testing explicit examples (of dimension at least 3), the following will happen: - If some example is shellable, there is a good chance to find a shelling sequence with backtracking.- If some example is non-shellable (and has, say, 20 or more vertices), it will be hopeless to complete the backtrack search.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/121371', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18263/']}
jdg_381502
stackexchange
llm_judgeable_groundtruth_similarity
66084
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 don't know how to evaluate it. I know there is one method using the gamma function. BUT I want to know the solution using a calculus method like polar coordinates. $$\int_{-\infty}^\infty x^2 e^{-x^2}\mathrm dx$$ I will wait for a solution. Thank you. Now provide the response and nothing else.
In order to solve the integral by polar coordinates first consider $I_s = \int_{-\infty}^\infty \mathrm{e}^{-s x^2} \mathrm{d} x$. The integral you seek will be obtained by differentiation as $-\left. \frac{\mathrm{d}}{\mathrm{d} s} I_s \right|_{s=1}$. Now, to evaluate $I_s$: $$ I_s^2 = \int_{-\infty}^\infty \mathrm{e}^{-s x^2} \mathrm{d} x \cdot \int_{-\infty}^\infty \mathrm{e}^{-s y^2} \mathrm{d} y = \int_{-\infty}^\infty \int_{-\infty}^\infty \mathrm{e}^{-s (x^2 + y^2)} \, \mathrm{d} x \mathrm{d} y$$Now change variables into polar coordinates $x = r \sin \theta$ and $y = r \cos \theta$. $$ I_s^2 = \int_{0}^{2 \pi} \mathrm{d} \theta \int_0^\infty \mathrm{e}^{-s r^2} \cdot r \, \mathrm{d} r = \pi \int_0^\infty \mathrm{e}^{-s t} \mathrm{d} t = \frac{\pi}{s}$$where $t = r^2$ change of variable has been made. Now, since $I_s > 0$ for $s >0$, we obtain $I_s = \sqrt{\frac{\pi}{s}}$. The integral in question now follows:$$ \int_{-\infty}^\infty x^2 \mathrm{e}^{-x^2} \mathrm{d} x = \left. -\frac{\mathrm{d}}{\mathrm{d} s} \sqrt{\frac{\pi}{s}} \right|_{s=1} = \left. \frac{\sqrt{\pi}}{2} s^{-\frac{3}{2}} \right|_{s=1} = \frac{\sqrt{\pi}}{2}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/66084', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16401/']}
jdg_381503
stackexchange
llm_judgeable_groundtruth_similarity
186133
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $\Gamma_g$ be the mapping class group of a closed oriented surface $\Sigma$ of genus $g$. There is a natural surjection $t \colon \Gamma_g \to \mathrm{Sp}(2g,\mathbf Z)$ which sends a mapping class to the induced action on $H^1(\Sigma,\mathbf Z)$. Composing $t$ with any representation of the symplectic group produces a large number of linear representations of $\Gamma_g$. These are only a small fraction of all representations of the mapping class groups. Others can for instance be obtained from 3D TQFTs or by from different constructions involving lower central series. My question is however whether the symplectic representations are the only ones that can be defined "algebro-geometrically". Let me ask a more concrete question. A representation of $\Gamma_g$ is the same as a local system on the moduli space of curves of genus $g$, $M_g$. For a representation which factors through $\mathrm{Sp}(2g,\mathbf Z)$ this local system underlies a polarized variation of Hodge structure, since it is pulled back from a PVHS on the Shimura variety parametrizing principally polarized abelian varieties of genus $g$. Is the converse true - if a local system (say with $\mathbf Q$ coefficients) on $M_g$ underlies a PVHS, is it isomorphic to one of the symplectic local systems? Now provide the response and nothing else.
Dan, Although I'm no longer very active on MO, I thought I'd make a few comments, since your question is an interesting one (and you're not anonymous). The paper of Looijenga referenced in Igor's answer would show that there are "algebro-geometric" representations of $\Gamma_g$ which don't factor through $Sp(2g,\mathbb{Z})$. In summary, he takes a finite abelian [but this shouldn't be essential] Galois topological covering $\tilde \Sigma\to \Sigma$ and looks at the finite index subgroup $\tilde \Gamma_g\subset \Gamma_g$ of elements which lift to $\tilde \Sigma$ and act trivially on the Galois group. The point is that $\tilde \Gamma_g$ will act on $H^1(\tilde \Sigma)$, and in this way he gets new representations (of the subgroup, but you can always induce up to $\Gamma_g$). To see that this comes from a PVHS over the stack $M_g$, consider the moduli stack $\tilde M$ parameterizing maps $f:\tilde C\to C$ of curves which topologically the same as $\tilde \Sigma\to \Sigma$. We have a map $\pi:\tilde M\to M_g$ sending $\tilde C\to C$ to $C$. Let $V$ be the VHS on $\tilde M$ with $H^1(\tilde C)$ as it's fibre. Then $\pi_*V$ is a VHS on $M_g$ which gives rise to Looijenga's. If you relax "comes from algebraic geometry" to allow monodromies of motivic variations of mixed Hodge structures, and I don't see why you wouldn't, then there are even more interesting possibilities gotten by looking at the (generally) singular spaces of semistable vector bundles over the universal curve of $M_g$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/186133', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1310/']}
jdg_381504
stackexchange
llm_judgeable_groundtruth_similarity
1284169
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 after some validation that I'm doing the right thing. I have my Ruby on Rails application in the following structure: /home about.rhtml index.rhtml /display index.rhtml /data <--This is called by jQuery from the display\index page to provide the data to render push.js.erb pull.js.erb /layout home.rhtml display.rhtml Everything is working fine, but I now want to add a site targeted for mobile devices. While the iPhone renders the website correctly, it would be nice to provide a more targeted experience. Ideally, I'm thinking about having an iPhone.domain.com which would be redirected to via .htaccess. For this, I was thinking about adding another view for each device /iPhone home.rhtml about.rhtml display.rhtml However, it feels like a lot of the data would be duplicated, for example the about page would be in two places. I guess I could have a partial and do something like render :partial => 'home/about' but that seems a little hacky. How can I develop my site to support this? I was thinking about a structure such as, but again not sure how to structure the code - how do I tell it to render the view in the iPhone directory... while not having the master layout applied /display /iphone index.rhtml I would really like some advice on the best way to approach this and structure the application. While the applications follow a structure at the moment, they could go off in different directions.. Thank you Ben Now provide the response and nothing else.
I would strongly recommend leaving the controller structure the same across all device types. Particularly if you are using Rails' RESTful routes your controllers should be closely matched to the domain model of your data. Whether that data is then presented to a desktop browser, to an iPhone, to a different type of mobile device, to a JSON/XML REST API client etc. is mostly a matter of the presentation layer, not the controller/routing layer. So an elegant solution would be: Detect device type based on User Agent (you may want to refer to the WURFL User Agent database); use Rails' respond_to mechanism to render a different view format for each device type; define a layout for each device type (e.g. using the XHTML Mobile Profile doctype for mobile devices); include different CSS files depending on device type. There are some plugins which try to make this easier: have a look at brendanlim's Mobile Fu and noelrappin's Rails iUI (both on GitHub). Also Brendan Lim's presentation at Rails Underground has a few ideas. What you should be aiming for is something like: def show @foo = Foo.find(params[:id]) respond_to do |format| format.html # => show.html.erb format.iphone # => show.iphone.erb format.blackberry # => show.blackberry.erb endend You should also allow users on mobile devices to override the user agent detection if they really want to see the desktop version of the site. A cookie with a long expiry time is probably the best way to do this, so that the site remembers the choice next time the user returns. Some mobile devices have rubbish cookie support, but then they probably won't want the desktop version of the site anyway because it probably won't work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1284169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61712/']}
jdg_381505
stackexchange
llm_judgeable_groundtruth_similarity
1762147
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 apologize if this is a somewhat naive question, but is there any particular reason mathematicians disproportionately study the field $\mathbb{R}$ and its subsets (as opposed to any other algebraic structure)? Is this because $\mathbb{R}$ is "objectively" more interesting in that studying it allows one to gain deep insights into mathematics, or is it sort of "arbitrary" in the sense that we are inclined to study $\mathbb{R}$ due to historical reasons, real-world applications and because human beings have a strong natural intuition of real numbers? Edit: Note that I am not asking why $\mathbb{Q}$ is insufficient as a number system; this has been asked and answered on this site and elsewhere. Rather, why, in a more deep sense, are $\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R}$ so crucial to mathematics? Would we be able to construct a meaningful study of mathematics with absolutely no reference to these sets, or are they fundamentally imperative? Now provide the response and nothing else.
I've often asked myself the same thing, and this is what I tell myself. $\mathbb R$ is (up to order-preserving field isomorphism) the only totally ordered, complete field. This is pretty big news, because these two nice structures lead to so many others we find useful to study in math. $\mathbb R$ (and more generally $\mathbb R^n$) is so great because a plethora of these fundamental "structures" studied in math are present in (at least some subset of) $\mathbb R$. When we learn of new concepts, it's natural (crucial) to seek examples, and we often find solace in the usual first stop -- $\mathbb R^n$. Here's a poor-at-best survery of some of the aforementioned structures that $\mathbb R$ has. Algebra Group -- we can combine elements, i.e., $a + b$, invert them, i.e., $a^{-1}$. Field -- we get more ways to combine elements, $+, -, \times, \div$. Ordered field -- we get to do things like transitivity, i.e., $a < b \wedge b < c \implies a < c$, and "add inequalities", i.e., $a \leq b \wedge c \leq d \implies a + c \leq b + d$. Vector space -- linear algebra's pretty important. Arrow-like addition is very physical. Analysis Completeness -- analysts love sequences... to converge. This allows for a lot of "take a sequence..." arguments which start with a probably-desired sequence that ends up being Cauchy. Compactness -- we always want to exploit compactness in analysis, and $\mathbb R^n$ has a particularly nice characerization of it. Hilbert Space -- we all love Hilbert space. Orthogonality is a useful tool. So is the spectral theorem. Measure space -- measuring is very physical, and crucial for integrating! $\mathbb R$ is the natural setting for the famous Lebesgue measure, and all measures map into the "subset" $[0,\infty]$ of $\mathbb R$. For Riemann integration, the (Darboux) definitions hinge on the least upper bound property of $\mathbb R$. Geometry Metric Space -- we can measure distances $d(p,q)$ between points. This is very physical. The triangle inequality is here too, which is even more useful in normed spaces, where it reads $\|u + v\| \leq \|u\| + \|v\|$, because it leads to many useful estimates in analysis. Manifolds -- things that by definition locally look like $\mathbb R^n$. Many "objects" that we deal with early in math are manifolds (we just didn't know it at the time). All of the separation axioms (Hausdorff, regular, normal, ...). All of the countability axioms (separable, Lindelof, ...). Not shown (for the sake of space and the inevitable lack of completeness) is the interrelatedness between many of these properties for $\mathbb R$, which is another indispensable virtue of $\mathbb R$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1762147', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/238417/']}
jdg_381506
stackexchange
llm_judgeable_groundtruth_similarity
9468878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to open an existing pdf, add some text and then output as content disposition using itext sharp. I have the following code. Where it falls down it is that i want to output as memory stream but need to filestream to open the original file. Here's what i have. Obviously defining PdfWriter twice won't work. public static void Create(string path) { var Response = HttpContext.Current.Response; Response.Clear(); Response.ContentType = "application/pdf"; System.IO.MemoryStream m = new System.IO.MemoryStream(); Document document = new Document(); PdfWriter wri = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create)); PdfWriter.GetInstance(document, m); document.Open(); document.Add(new Paragraph(DateTime.Now.ToString())); document.NewPage(); document.Add(new Paragraph("Hello World")); document.Close(); Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.End(); } Now provide the response and nothing else.
You've got a couple of problems that I'll try to walk you through. First, the Document object is only for working with new PDFs, not modifying existing ones. Basically the Document object is a bunch of wrapper classes that abstract away the underlying parts of the PDF spec and allow you to work with higher level things like paragraphs and reflowable content. These abstractions turn what you think of "paragraphs" into raw commands that write the paragraph one line at a time with no relationship between lines. When working with an existing document there's no safe way to say how to reflow text so these abstractions aren't used. Instead you want to use the PdfStamper object. When working with this object you have two choices for how to work with potentially overlapping content, either your new text gets written on top of existing content or your text gets written below it. The two methods GetOverContent() or GetUnderContent() of an instantiated PdfStamper object will return a PdfContentByte object that you can then write text with. There's two main ways to write text, either manually or through a ColumnText object. If you've done HTML you can think of the ColumnText object as using a big fixed-position single row, single column <TABLE> . The advantage of the ColumnText is that you can use the higher level abstractions such as Paragraph . Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that show off the above. See the code comments for any questions. It should be pretty easy to convert this to ASP.Net. using System;using System.IO;using System.Windows.Forms;using iTextSharp.text;using iTextSharp.text.pdf;namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string existingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf"); string newFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf"); using (FileStream fs = new FileStream(existingFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document doc = new Document(PageSize.LETTER)) { using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); doc.Add(new Paragraph("This is a test")); doc.Close(); } } } //Bind a PdfReader to our first document PdfReader reader = new PdfReader(existingFile); //Create a new stream for our output file (this could be a MemoryStream, too) using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None)) { //Use a PdfStamper to bind our source file with our output file using (PdfStamper stamper = new PdfStamper(reader, fs)) { //In case of conflict we want our new text to be written "on top" of any existing content //Get the "Over" state for page 1 PdfContentByte cb = stamper.GetOverContent(1); //Begin text command cb.BeginText(); //Set the font information cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 16f); //Position the cursor for drawing cb.MoveText(50, 50); //Write some text cb.ShowText("This was added manually"); //End text command cb.EndText(); //Create a new ColumnText object to write to ColumnText ct = new ColumnText(cb); //Create a single column who's lower left corner is at 100x100 and upper right is at 500x200 ct.SetSimpleColumn(100,100,500,200); //Add a higher level object ct.AddElement(new Paragraph("This was added using ColumnText")); //Flush the text buffer ct.Go(); } } this.Close(); } }} As to your second problem about the FileStream vs MemoryStream , if you look at the method signature for almost every (actually all as far as I know) method within iTextSharp you'll see that they all take a Stream object and not just a FileStream object. Any time you see this, even outside of iTextSharp, this means that you can pass in any subclass of Stream which includes the MemoryStream object, everything else stays the same. The code below is a slightly modified version of the one above. I've removed most of the comments to make it shorter. The main change is that we're using a MemoryStream instead of a FileStream . Also, when we're done with the PDF when need to close the PdfStamper object before accessing the raw binary data. (The using statment will do this for us automatically later but it also closes the stream so we need to manually do it here.) One other thing, never, ever use the GetBuffer() method of the MemoryStream . It sounds like what you want (and I have mistakenly used it, too) but instead you want to use ToArray() . GetBuffer() includes uninitialized bytes which usually produces corrupt PDFs. Also, instead of writing to the HTTP Response stream I'm saving the bytes to array first. From a debugging perspective this allows me to finish all of my iTextSharp and System.IO code and make sure that it is correct, then do whatever I want with the raw byte array. In my case I don't have a web server handy so I'm writing them to disk but you could just as easily call Response.BinaryWrite(bytes) string existingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf");string newFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf");PdfReader reader = new PdfReader(existingFile);byte[] bytes;using(MemoryStream ms = new MemoryStream()){ using (PdfStamper stamper = new PdfStamper(reader, ms)) { PdfContentByte cb = stamper.GetOverContent(1); ColumnText ct = new ColumnText(cb); ct.SetSimpleColumn(100,100,500,200); ct.AddElement(new Paragraph("This was added using ColumnText")); ct.Go(); //Flush the PdfStamper's buffer stamper.Close(); //Get the raw bytes of the PDF bytes = ms.ToArray(); }}//Do whatever you want with the bytes//Below I'm writing them to disk but you could also write them to the output buffer, toousing (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None)) { fs.Write(bytes, 0, bytes.Length);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9468878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461880/']}
jdg_381507
stackexchange
llm_judgeable_groundtruth_similarity
1402483
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 title suggests, I had problems with a program of mine where I used a std::list as a stack and also to iterate over all elements of the list. The program was taking way too long when the lists became very big. Does anyone have a good explanation for this? Is it some stack/cache behavior? (Solved the problem by changing the lists to std::vector and std::deque (an amazing data structure by the way) and everything suddenly went so much faster) EDIT: I'm not a fool and I don't access elements in the middle of the lists. The only thing I did with the lists was to remove/add elements at the end/beginning and to iterate through all elements of the list.And I always used iterators to iterate over the list. Now provide the response and nothing else.
Lists have terrible (nonexistent) cache locality. Every node is a new memory allocation, and may be anywhere . So every time you follow a pointer from one node to the next, you jump to a new, unrelated, place in memory. And yes, that hurts performance quite a bit. A cache miss may be two orders of magnitudes slower than a cache hit. In a vector or deque, pretty much every access will be a cache hit. A vector is one single contiguous block of memory, so iterating over that is as fast as you're going to get. A deque is several smaller blocks of memory, so it introduces the occasional cache miss, but they'll still be rare, and iteration will still be very fast as you're getting mostly cache hits. A list will be almost all cache misses. And performance will suck. In practice, a linked list is hardly ever the right choice from a performance point of view. Edit :As a comment pointed out, another problem with lists is data dependencies. A modern CPU likes to overlap operations. But it can't do that if the next instruction depends on the result of this one. If you're iterating over a vector, that's no problem. You can compute the next address to read on the fly, without ever having to check in memory. If you're reading at address x now, then the next element will be located at address x + sizeof(T) where T is the element type. So there are no dependencies there, and the CPU can start loading the next element, or the one after it, immediately, while still processing an earlier element. That way, the data will be ready for us when we need it, and this further helps mask the cost of accessing data in RAM. In a list, we need to follow a pointer from node i to node i+1 , and until i+1 has been loaded, we don't even know where to look for i+2 . We have a data dependency, so the CPU is forced to read nodes one at a time, and it can't start reading future nodes ahead of time, because it doesn't yet know where they are. If a list hadn't been all cache misses, this wouldn't have been a big problem, but since we're getting a lot of cache misses, these delays are costly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1402483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10889/']}
jdg_381508
stackexchange
llm_judgeable_groundtruth_similarity
166734
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 a newly installed (and updated) Centos 7 server I use for testing. I implemented RSA key based authentication for ssh and set PermitRootLogin to without-password When I logged on this morning I ran netstat -plant and found a couple of established connections on port 22 from China and France. I find it hard to believe that a 4096 bit rsa key can be cracked within the space of one evening. Are there any exploits / vulnerabilities that can be used to circumvent key-based authentication with OpenSSH? Is key-based auth the best option to allow access with SSH? What are the alternatives? Now provide the response and nothing else.
When I logged on this morning I ran netstat -plant and found a couple of established connections on port 22 from China and France. How long did you see them for? If you have an SSH server on the Internet, people are going to be constantly scanning for it and attempting dictionary attacks of common passwords. So systems will connect, try multiple passwords, and have enforced delays between tries as your system wants to limit brute force attacks. All this means is TCP connections "established" for seconds or even minutes. They aren't authenticated SSH sessions, they're just TCP connections. Here, look: $ netstat -tn | grep :22 | egrep -v "[my address]"tcp 0 1080 192.168.1.2:22 123.183.209.136:25690 ESTABLISHEDtcp 0 1 192.168.1.2:22 123.183.209.136:40117 FIN_WAIT1 a couple minutes later: $ netstat -tn | grep :22tcp 0 1080 192.168.1.2:22 123.183.209.136:48456 ESTABLISHED In the first snapshot we see that there's one established session, and one still being torn down. A couple minutes later, there's a new session (notice the client port has changed to 48456). So this person is constantly opening a TCP connection, trying to authenticate, and when that connection gets shut down for too many tries they just open another one. I find it hard to believe that a 4096 bit rsa key can be cracked within the space of one evening. Are there any exploits / vulnerabilities that can be used to circumvent key-based authentication with OpenSSH? Is key-based auth the best option to allow access with SSH? What are the alternatives? Don't panic yet. Watch the connections; unless you see one last for a significant period of time you probably don't have to worry. You can also check last output to see if anyone is actually logging in, and correlate their source address (e.g., don't worry about logins from the IP you log in from): $ lastgowenfawr pts/0 192.168.1.3 Thu Aug 3 18:55 still logged ingowenfawr pts/0 172.16.43.21 Thu Aug 3 03:29 - 03:29 (00:00)gowenfawr pts/0 172.16.43.21 Thu Aug 3 03:19 - 03:29 (00:09)gowenfawr pts/0 172.16.43.21 Thu Aug 3 03:04 - 03:06 (00:02)gowenfawr pts/1 192.168.1.3 Wed Aug 2 19:44 - 21:09 (01:25)wtmp begins Wed Aug 2 19:44:26 2017 Although, of course, if someone did compromise your system, you couldn't trust last or netstat anyway.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/166734', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/135028/']}
jdg_381509
stackexchange
llm_judgeable_groundtruth_similarity
2188070
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: Using the Taylor series expansion we have (for a sufficiently regular function $f$):$$f(x+a)=\sum_{k=0}^n \frac{f^{(k)}(x)a^k}{k!}$$So, defining the differential operator $D=\frac{d}{dx}$ and using the series expansion definition of the exponential function, we can write:$$S_a f(x)=\exp(aD) f(x)$$ where $S_a f(x)=f(x+a)$ is the shift operator. This gives an ''intuitive'' meaning to the exponential of the differential operator : $\exp(aD)=S_a$. We can extend this intuition without problems and say that: $\log S_a=aD$ ? And we can also found one (or more) operator $T=\log (aD)$, such that $\exp T=aD$? I have found many references to the similar question for linear operators in finite dimensional vector space, but very little about the infinite dimensional case. Someone know some good reference in the web? Now provide the response and nothing else.
At least from one perspective, what you're looking at is something called functional calculus , which is the business of defining and computing with functions of operators on vector spaces, typically (infinite-dimensional) Hilbert spaces. However, if you're specifically interested in functions of operators constructed from (partial) differentiation, then there is a specialised theory called the theory of pseudo-differential operators , which, very roughly speaking, uses the Fourier transform to "diagonalise" (partial) differentiation as an operator on a suitable function space. So, let $\hat{f}$ denote the Fourier transform of a (sufficiently well-behaved) function $f$ and let $\check{g}$ denote the inverse Fourier transform of a (sufficiently well-behaved) function $g$, so that$$ \hat{f}(k) = \int_{-\infty}^\infty f(x)e^{-2\pi i kx}\,dx, \quad \check{g}(x) = \int_{-\infty}^\infty g(k) e^{2\pi i kx}\,dk.$$If $f$ is a rapidly-decreasing smooth function on the real line, then, it's a basic property of the Fourier transform that$$ \widehat{Df}(k) = 2\pi i k \hat{f}(k),$$or equivalently, that$$ Df(x) = \int_{-\infty}^\infty 2\pi i k \hat{f}(k) e^{2\pi i kx}\,dk.$$As a result, if $p(t) = \sum_{j=1}^m a_j t^j$ is a polynomial, so that$$ p(D)f(x) := \sum_{j=1}^m a_j D^jf(x) = \sum_{j=1}^m a_j f^{(j)}(x),$$then one can check that$$ \widehat{p(D)f}(x) = p(2\pi i k)\hat{f}(k),$$or equivalently,$$ p(D)f(x) = \int_{-\infty}^\infty p(2\pi i k)\hat{f}(k)e^{2\pi i kx}\,dx.$$On the other hand, it is also a basic property of the Fourier transform that$$ \widehat{S_af}(k) = e^{2\pi i ak}\hat{f}(k) = e^{a(2\pi i k)} \hat{f}(k),$$or equivalently, that$$ S_af(x) = \int_{-\infty}^\infty e^{a(2\pi i k)}\hat{f}(k)e^{2\pi i kx}\,dk,$$ which suggests, independently of Taylor series, that $S_a = e^{aD}$ in some suitable sense. Hence, if $p$ is any reasonable function defined on (some part of) the imaginary axis of the complex plane, then one can try to define $p(D)$ by$$p(D)f(x) = \int_{-\infty}^\infty p(2\pi i k)\hat{f}(k)e^{2\pi i k}\,dk$$for $f$ in some suitable domain---such operators are what one calls pseudo-differential operators . So, let's apply this machinery to defining the logarithm of $D$. Let $\operatorname{Log}$ denote the principal branch of the logarithm, so that, in particular,$$ \forall k \in \mathbb{R} \setminus \{0\}, \quad \operatorname{Log}(2\pi i k) = \log(2\pi \lvert k \rvert) +i \operatorname{sgn}(k)\frac{\pi}{2}.$$Then, for any rapidly-decreasing smooth function $f$ such that$$ \lim_{k \to 0} \log(\lvert k \rvert) \hat{f}(k)$$exists, one should be able to define$$ \operatorname{Log}(D)f(x) = \int_{-\infty}^\infty \operatorname{Log}(2\pi i k)\hat{f}(k)e^{2\pi i kx}\,dk.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2188070', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/187568/']}
jdg_381510
stackexchange
llm_judgeable_groundtruth_similarity
2486314
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In Ruby, there's Modules and you can extend a class by "mixing-in" the module. module MyModule def printone print "one" endendclass MyClass include MyModuleendtheOne = MyClass.newtheOne.printone >> one In Objective-C, I find that I have a set of common methods that I want a number of Class to "inherit". What other ways can I achieve this without creating a common class and deriving all from that common class? Now provide the response and nothing else.
Edit : changes added because some people feel I am responsible for the limitations of Objective-C. Short answer : you can't. Objective-C doesn't have the equivalent of Ruby mixins. Slightly less short answer : Objective-C does have something with arguably the same flavour: protocols. Protocols (Interfaces in some other languages), are a way to define a set of methods an class that adopts that protocols is committing to implementing. A protocol doesn't provide an implementation though. That limitation prevents using protocols as an exact equivalent to Ruby mixins. Even less short answer: However, the Objective-C runtime has an exposed API that lets you play with the dynamic features of the language. Then you step outside the language, but you can have protocols with default implementations (also called concrete protocols). Vladimir's answer shows one way to do that. At that point it seems to me you get Ruby mixins alright. However, I am not sure I would recommend doing that. In most cases, other patterns fit the bill without playing games with the runtime. For example, you can have a sub-object that implement the mixed-in method ( has-a instead of is-a ). Playing with the runtime is OK, but has 2 drawbacks: You make your code less readable as it requires readers to know a lot more than the language. Sure you can (and should) comment it, but remember that any necessary comment can be seen as an implementation defect. You depend on that implementation of the language. Sure, Apple platforms are by far the most common ones for Objective-C but don't forget Cocotron or GnuStep (or Etoilé) which have different runtimes, which may or may not be compatible with Apple's on that respect. As a side note, I state below that categories cannot add state (instance variables) to a class. By using the runtime API, you can lift that limitation too. This is beyond the scope of this answer however. Long answer: Two Objective-C features look like possible candidates: categories and protocols. Categories are not really the right choice here, if I understand the question properly. The right feature is a protocol. Let me give an example. Suppose you want a bunch of your classes to have a specific ability called "sing". Then you define a protocol: @protocol Singer - (void) sing;@end Now you can declare that any of your own classes adopts the protocol the following way: @interface Rectangle : Shape <Singer> { <snip>@end@interface Car : Vehicle <Singer> { <snip>@end By declaring that they adopt the protocol they commit themselves to implementing the sing method. For example: @implementation Rectangle- (void) sing { [self flashInBrightColors];}@end@implementation Car- (void) sing { [self honk];}@end Then you use those classes for example like this: void choral(NSArray *choir) // the choir holds any kind of singer{ id<Singer> aSinger; for (aSinger in choir) { [aSinger sing]; }} Notice that the singers in the array don't need to have a common superclass. Notice also that a class can have only one superclass, but many adopted protocols. Notice finally that type checking is done by the compiler. In effect, the protocol mechanism is multiple inheritance used for the mixin pattern. That multiple inheritance is severely limited because a protocol cannot add new instance variables to a class. A protocol only describes a public interface adopters must implement. Unlike Ruby modules it does not contain an implementation. That's the most of it. Let's mention categories however. A category is declared not in angle brackets, but between parenthesis. The difference is that a category can be defined for an existing class to expand it without subclassing it. You can even do so for a system class. As you can imagine, it's possible to use categories to implement something similar to mixin. And they were used that way for a long time usually as category to NSObject (the typical root of the inheritance hierarchy), to such an extent that they were called "informal" protocols. It's informal because 1- no type checking is done by the compiler, and 2- implementing the protocol methods is optional. There is no need today to use categories as protocols, especially because the formal protocols can now declare that some of their methods are optional with the keyword @optional or required (the default) with @required . Categories are still useful to add some domain specific behavior to an existing class. NSString is a common target for that. It's also interesting to point out that most (if not all) of NSObject facilities are in fact declared in a NSObject protocol. This means that it's not really compelling to use NSObject as a common superclass for all classes, though this is still commonly done for historical reasons, and well... because there is no drawback for doing so. But some system classes, such as NSProxy , are not NSObject .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2486314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298166/']}
jdg_381511
stackexchange
llm_judgeable_groundtruth_similarity
5658197
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 around 500 configurable products that I need to add a new attribute to. For example, they already have Color as an attribute. How would I go about adding Size to the existing configurable products? Now provide the response and nothing else.
Adding the attribute to the attribute set and then updating all the simple products' attributes is not sufficient. Magento asks what 'configurable attributes' to use when you initially create a configurable product; the new attribute will therefore not be applied to existing configurable product(s) and their child products. I've tested the below DB workaround hack on CE 1.6.2 and it seems to be working: Create attribute Drag it to appropriate attribute set Go to phpmyadmin, table ‘ catalog_eav_attribute ’ and look at the last one, note the ‘attribute id’, also note the product id -> go to catalog_product_entity and look for the configurable product you want, and note entity_id -> this is the product_id Go to catalog_product_super_attribute and insert new record with product_id and attribute_id , note of the product_super_attribute_id Go to catalog_product_super_attribute_label and insert new record with product_super_attribute_id and the value of your new attribute, like ‘Color’ or ‘Size’ which you used when adding the attribute in the admin Go back to admin and click the configurable product, you will notice none of your child products is associated to your configurable product. Click one of the child products, and select appropriate attribute value, you may also change the sku. Export all child products and add the new attribute and sku values to it, import it back and you are done or you may have to manually change all in the admin without using the dataflow. credit: http://www.magentocommerce.com/boards/viewthread/43288/#t330918
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5658197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416661/']}
jdg_381512
stackexchange
llm_judgeable_groundtruth_similarity
1038857
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 just came across this thread, and i asked myself: I know that $\sum^\infty_{n=0} x^n = \frac{1}{1-x}$ But what happens when we set up the sum like $$\sum^\infty_{n=0} nx^n = ?$$ There is probably a formula for that as well, at least there must be some coincidence, for the limited sums i already saw the prove in the thread i mentioned above. My books could not help me out so far.. If there is a formula for this, i would also like to see the derivation of it.. Searched the web with no luck so far. If you know a website or thread where this is explained, probably a link is enough for an answer.. I appreciate your help! Now provide the response and nothing else.
Note that for $|x| < 1$, we have $$\sum_{n=0}^\infty nx^n = x \sum_{n=0}^\infty nx^{n-1} = x \sum_{n=0}^\infty \frac{d\ }{dx} x^n = x \frac{d\ }{dx} \sum_{n=0}^\infty x^n = x \frac{d\ }{dx} \frac{1}{1-x} = \frac{x}{(1-x)^2}$$ You can now write down an expression for your sum.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1038857', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186763/']}
jdg_381513
stackexchange
llm_judgeable_groundtruth_similarity
2328128
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: Assume that the: $$\sum_{n=1}^\infty \frac{a_n}{b_n}$$ and $$\sum_{n=1}^\infty \frac{b_n}{c_n}$$are convergent and irrational, then if$$\sum_{n=1}^\infty \frac{a_n}{c_n}$$ is convergent should it also be irrational then for the integer $a_n$, $b_n$ and $c_n$? I assume this is false, but can not find any counterexample. Now provide the response and nothing else.
Let $a_n = n+1, b_n = (-1)^n n(n+1), c_n = n(n+1)^2$ Then $$\sum_{n=1}^{\infty} \frac{a_n}{b_n} = -\ln 2$$$$\sum_{n=1}^{\infty} \frac{b_n}{c_n} = \ln 2 -1$$$$\sum_{n=1}^{\infty} \frac{a_n}{c_n} = 1$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2328128', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/331849/']}
jdg_381514
stackexchange
llm_judgeable_groundtruth_similarity
17241614
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reading C++ Primer and couldn't quite understand when an expression yields an object type, and when it yields a reference type to the object. I quote from the book: When we apply decltype to an expression that is not a variable, we get the type that > that expression yields. Generally speaking, decltype returns a reference type for expressions that yield objects that can stand on the left-hand side of the assignment. Considering the code below: int i = 3, *ptr = &i, &ref = i;decltype(ref + 0) j; In the above code, the expression "ref + 0" results in an inherent operation of addition of value of the object that ref refers to, i and 0. Hence, going by the first rule the expression yields an int type.But going by the second rule, as the expression yields the type of an object that can stand on the left hand side of an assignment (in this case int), shouldn't the decltype yield a ref to int(int&) type? The book also says, for the following code decltype(*ptr) k; k has type int& and not int, the type which the expression results in. It also says that for an assignment expression like in code below decltype(a = b) l; l would have the type of reference to object on the left hand side of the assignment operation. How would we know which expressions yield the object type and which yield the reference to the object type? Now provide the response and nothing else.
It is not easy to understand these concepts without getting formal. The primer probably does not want to confuse you and avoids introducing terms such as " lvalue ", " rvalue ", and " xvalue ". Unfortunately, these are fundamental in order to understand how decltype works. First of all, the type of an evaluated expression is never a reference type, nor a top-level const -qualified type for non-class types (e.g. int const or int& ). If the type of an expression turns out to be int& or int const , it gets immediately transformed into int prior to any further evaluation. This is specified in paragraphs 5/5 and 5/6 of the C++11 Standard: 5 If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue , depending on the expression. 6 If a prvalue initially has the type “cv T,” where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis. So much for expressions. What does decltype do? Well, the rules that determine the result of decltype(e) for a given expression e are specified in paragraph 7.1.6.2/4: The type denoted by decltype(e) is defined as follows: — if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e . If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed; — otherwise, if e is an xvalue , decltype(e) is T&& , where T is the type of e ; — otherwise, if e is an lvalue , decltype(e) is T& , where T is the type of e ; — otherwise, decltype(e) is the type of e . The operand of the decltype specifier is an unevaluated operand (Clause 5). This can indeed sound confusing. Let's try to analyze it part by part. First of all: — if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e . If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed; This is simple. If e is just the name of a variable and you do not put it within parentheses, then the result of decltype is the type of that variable. So bool b; // decltype(b) = boolint x; // decltype(x) = intint& y = x; // decltype(y) = int&int const& z = y; // decltype(z) = int const&int const t = 42; // decltype(t) = int const Notice, that the result of decltype(e) here is not necessarily the same as the type of the evaluated expression e . For instance, the evaluation of the expression z yields a value of type int const , not int const& (because by paragraph 5/5 the & gets stripped away, as we have seen previously). Let's see what happens when the expression is not just an identifier: — otherwise, if e is an xvalue , decltype(e) is T&& , where T is the type of e ; This is getting complicated. What is an xvalue ? Basically, it is one of the three categories an expression can belong to ( xvalue , lvalue , or prvalue ). An xvalue is normally obtained when invoking a function with a return type which is an rvalue reference type, or as the result of a static cast to an rvalue reference type. The typical example is a call to std::move() . To use the wording from the Standard: [ Note: An expression is an xvalue if it is: — the result of calling a function, whether implicitly or explicitly, whose return type is an rvalue reference to object type, — a cast to an rvalue reference to object type, — a class member access expression designating a non-static data member of non-reference type in which the object expression is an xvalue , or — a .* pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member. In general, the effect of this rule is that named rvalue references are treated as lvalues and unnamed rvalue references to objects are treated as xvalues ; rvalue references to functions are treated as lvalues whether named or not. —end note ] So for instance, the expressions std::move(x) , static_cast<int&&>(x) , and std::move(p).first (for an object p of type pair ) are xvalues. When you apply decltype to an xvalue expression, decltype appends && to the type of the expression: int x; // decltype(std::move(x)) = int&& // decltype(static_cast<int&&>(x)) = int&& Let's continue: — otherwise, if e is an lvalue , decltype(e) is T& , where T is the type of e ; What is an lvalue ? Well, informally, lvalue expression are expressions which denote objects that can be repeatably referenced in your program - for instance variables with a name and/or objects you can take the address of. For an expression e of type T that is an lvalue expression, decltype(e) yields T& . So for instance: int x; // decltype(x) = int (as we have seen) // decltype((x)) = int& - here the expression is parenthesized, so the // first bullet does not apply and decltype appends & to the type of // the expression (x), which is int A function call for a function whose return type is T& is also an lvalue expression, so: int& foo() { return x; } // decltype(foo()) = int& Finally: — otherwise, decltype(e) is the type of e . If the expression is not an xvalue nor an lvalue (in other words, if it is a prvalue ), the result of decltype(e) is simply the type of e . Unnamed temporaries and literals are prvalues . So for instance: int foo() { return x; } // Function calls for functions that do not return // a reference type are prvalue expressions// decltype(foo()) = int// decltype(42) = int Let's apply the above to the examples from your question. Given these declarations: int i = 3, *ptr = &i, &ref = i;decltype(ref + 0) j;decltype(*ptr) k;decltype(a = b) l; The type of j will be int , because operator + returns a prvalue of type int . The type of k will be int& , because the unary operator * yields an lvalue (see paragraph 5.3.1/1). The type of l is also int& , because the result of operator = is an lvalue (see paragraph 5.17/1). Concerning this part of your question: But going by the second rule, as the expression yields the type of an object that can stand on the left hand side of an assignment (in this case int), shouldn't the decltype yield a ref to int(int&) type? You probably misinterpreted that passage from the book. Not all objects of type int can be on the left side of an assignment. For instance, the assignment below is illegal: int foo() { return 42; }foo() = 24; // ERROR! foo() is a prvalue expression, cannot be on the left // side of an assignment Whether or not an expression can appear on the left side of an assignment (notice, that we are talking about the built-in assignment operator for fundamental data types here) depends on the value category of that expression ( lvalue , xvalue , or prvalue ), and the value category of an expression is independent from its type.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17241614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1290303/']}
jdg_381515
stackexchange
llm_judgeable_groundtruth_similarity
33665241
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that the data contained in an OpenCV matrix is not guaranteed to be continuous. To make myself clear, here is a paragraph from Opencv documentation : OpenCV provides a function called isContinuous() to test if the data of a given matrix is continuous. My questions are If I create a new matrix as follows cv::Mat img = cv::imread(img_name) Is the data in img guaranteed to be continuous? I know that creating a new matrix by borrowing data from the existing matrix would result in discontinuous data cv::Mat small_mat = large_mat.col(0); The above code creates a new matrix small_mat by borrowing the 0 th column of large_mat , leading to discontinuous data in small_mat . So the question is if I create a brand new matrix without borrowing data from the existing matrix, will the brand new matrix have continuous data or discontinuous data? Is the following code guaranteed to create a matrix with continuous data? cv::Mat mat(nRows, nCols, CV_32FC1); Now provide the response and nothing else.
You can see in the OpenCV doc for isContinuous : The method returns true if the matrix elements are stored continuously without gaps at the end of each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. Matrices created with Mat::create() are always continuous. But if you extract a part of the matrix using Mat::col(), Mat::diag() , and so on, or constructed a matrix header for externally allocated data, such matrices may no longer have this property. So, as long as you are creating a new matrix (i.e. you're calling create ), your matrix will be continuous. create works like: If the current array shape and the type match the new ones, return immediately. Otherwise, de-reference the previous data by calling Mat::release(). Initialize the new header. Allocate the new data of total()*elemSize() bytes. Allocate the new, associated with the data, reference counter and set it to 1. This means that when you (implicitly) call create, the matrix will be continuous (step 3). Your questions If I create a new matrix with imread is the data guaranteed to be continuous Yes , because imread internally calls create . I know that creating a new matrix by borrowing data from existing matrix would result in incontinuous data. Correct, data will be non continuous . To make the new matrix continuous, you can call clone() , which calls create to create the new matrix. if I create a brand new matrix without borrowing data from existing matrix, will the brand new matrix have incontinuous data? Yes , the constructor internally calls create . Matrix constructor is guaranteed to create a matrix with continuous data? Yes , the constructor internally calls create . This is a small example to summarize: #include <opencv2\opencv.hpp>#include <iostream>using namespace std;using namespace cv;int main(){ // Read image Mat img = imread("path_to_image"); cout << "img is continuous? " << img.isContinuous() << endl; // Yes, calls create internally // Constructed a matrix header for externally allocated data Mat small_mat = img.col(0); cout << "small_mat is continuous? " << small_mat.isContinuous() << endl; // No, you're just creating a new header. // Matrix (self) expression small_mat = small_mat + 2; cout << "small_mat is continuous? " << small_mat.isContinuous() << endl; // No, you're not even creating a new header // Matrix expression Mat expr = small_mat + 2; cout << "expr is continuous? " << expr.isContinuous() << endl; // Yes, you're creating a new matrix // Clone Mat small_mat_cloned = img.col(0).clone(); cout << "small_mat_cloned is continuous? " << small_mat_cloned.isContinuous() << endl; // Yes, you're creating a new matrix // Create Mat mat(10, 10, CV_32FC1); cout << "mat is continuous? " << mat.isContinuous() << endl; // Yes, you're creating a new matrix return 0;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33665241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1044789/']}
jdg_381516
stackexchange
llm_judgeable_groundtruth_similarity
11177348
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I have a List like: List<String> list = new ArrayList<>();list.add("a");list.add("h");list.add("f");list.add("s"); While iterating through this list I want to add an element at the end of the list. But I don't want to iterate through the newly added elements that is I want to iterate up to the initial size of the list. for (String s : list) /* Here I want to add new element if needed while iterating */ Can anybody suggest me how can I do this? Now provide the response and nothing else.
You can't use a foreach statement for that. The foreach is using internally an iterator: The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. (From ArrayList javadoc) In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually: int listSize = list.size();for(int i = 0; i < listSize; ++i) list.add("whatever"); Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11177348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1440250/']}
jdg_381517
stackexchange
llm_judgeable_groundtruth_similarity
2250722
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: Hi i was wondering if anyone could help me with my revision This is a question of a past paper i'm stuck on. Let $$f:[a,b]\to \Re$$ be Riemann intergrable. Part (a) is to prove that f is bounded and part (b) is to Give an example of a bounded function f that is not Riemann integrable my attempt for part (a) is since f is Riemann intergrable then it is continuous on [a,b] which means that it must also be bounded? or is this incorrect i find this topic rather difficult For part (b) i dont really have a clue i cant recall any function like the one they ask for Now provide the response and nothing else.
To show that $f$ cannot be both unbounded and Riemann integrable, it is enough to produce some $\epsilon > 0$ such that for any real number $I$ and any $\delta > 0$ there is a tagged partition $P$ with $\|P\| < \delta$ and with a Riemann sum satisfying $$|S(P,f) - I| > \epsilon$$ Since $f$ is unbounded it must be unbounded on at least one subinterval $[x_{j-1},x_j].$ Using the reverse triangle inequality we have $$|S(P,f) - I| = \left|f(t_j)(x_j - x_{j-1}) + \sum_{k \neq j}f(t_k)(x_k - x_{k-1}) - I \right| \\ \geqslant |f(t_j)|(x_j - x_{j-1}) - \left|\sum_{k \neq j}f(t_k)(x_k - x_{k-1}) - I \right|$$ Since $f$ is unbounded on $[x_{j-1},x_j]$, choose $t_j$ such that $$|f(t_j)| > \frac{\epsilon + \left|\sum_{k \neq j}f(t_k)(x_k - x_{k-1}) - I \right|}{x_j - x_{j-1}},$$ and it follows that $$|S(f,P) - I| > \epsilon.$$ Thus, when $f$ is unbounded, it is impossible to find $I$ such that for every $\epsilon > 0$ and sufficiently fine partitions, the condition $|S(P,f) - I| < \epsilon$ holds. We can always select the tags so that the inequality is violated.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2250722', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_381518
stackexchange
llm_judgeable_groundtruth_similarity
352034
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking to improve the readability of a lengthy C++ function. This function contains a number (> a dozen) variables that are used throughout. The main logic of the code is a long list of condition checks (sometimes nested, sometimes with loops) followed by various actions. Because of the lengthy number of lines detailing the actions to be performed mixed in with the logical/looping glue, it can be quite hard to follow what's going on. There's no simple way to siphon off these actions into separate functions without arbitrary, ugly function signatures noting whatever subset of variables happen to be needed. One drastic solution might be to replace the function with a singleton class, with the function's variables and sub-actions becoming private member variables and private member. However, I'm looking for a simpler alternative. My idea is to define a list of actions at the top of my function through lambda functions, and then below this perform the function's logic using these one-off lambdas. This would look something like (entirely schematically); void function() { // variables int a, b, c, d, ...; // actions to be performed auto func1 = [&] () { ... code using a,b, etc. }; auto func2 = [&] () { ... }; auto func3 = [&] () { ... }; ... // main logic if (<condition 1>) { if (<condition 2>) func1(); else func2(); } else { func2(); func3(); } ... // etc} These lambda functions would occasionally save code, in the the cases where they replace repeated code fragments, but would usually just improve readability -- at least to my eyes. Is this a good practice in general? Do others find that this improves readability, and what is the cost of using these lambda functions? Now provide the response and nothing else.
Does it improve readability ? Your way of using lambdas to break-down a larger function in smaller parts is similar to the nested functions in Pascal, ADA and other languages. It indeed improves the readability of the main part of your function body: there are less statements to read to understand what it does. This is the main purpose of nested functions. Of course, I assume that nowadays, most programmers are familiar with the syntax of lambdas. However, is it a good idea ? Scott Meyers, in his book Effective Modern C++ warns against the use of default capture in lambdas. His main worry is about dangling references (e.g. if a lambda is defined in a block and is used out of the scope of this block when the variable doesn't exist anymore), which seems not to be an issue in your case. But he also underlines another problem: the illusion of having a self-contained function. And here lies the major weakness of your approach: you have the impression that your lambda is self contained, but in fact it's completely dependent of the rest of the code, and you don't see easily in your lambda where the captured values are coming from, which assumptions you can make on them, etc... as the link with the main body is based on the captured variables, which can be read or written, it is in fact very difficult to guess all the side effects hidden in your lambda invocation, which could influence your main part. so it's very difficult to identify assumptions and invariants in the code, both of the lambda, and of your mega function in addition, you could accidentally change a variable that you forgot to declare locally in your lambda, and one happens to have the same name in the function. First advice: at least, enumerate explicitly the variables captured by your lambda, in order to better control the potential side effects. Second advice: once this works, you could think of strengthening your structure further, by evolving from capture to parameter passing. If there are too many of them, you'd have to refactor. One approach could be to make your function a callable class, promoting your throw away lambdas to member functions, and making the variables used throughout the computation member variables. But it's difficult to say if it's the best option from the elements you gave. And why are you in such a situation ? The next think to think about, is why you have such a big function in the first place. If you'd follow Uncle Bob's advice given in his book Clean Code (summary of the function topic on this blog page ) you should have: small functions, that do one thing (single responsibility), and that do only things at one level of abstraction
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/352034', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/276912/']}
jdg_381519
stackexchange
llm_judgeable_groundtruth_similarity
60177847
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 use css and scss in next.js app. I have next.config.js in my project. This configuration is for scss : // next.config.jsconst withSass = require('@zeit/next-sass');module.exports = withSass({ cssModules: true, cssLoaderOptions: { importLoaders: 1, localIdentName: "[local]___[hash:base64:5]", }}) I don't know how to combine const withCSS = require('@zeit/next-css'); with my current config. I would like to use custom config for scss (from my code snipet). Can someone help me configure next for css and scss modules? I tried: // // next.config.jsconst withSass = require('@zeit/next-sass');const withCSS = require('@zeit/next-css');module.exports = withCSS(withSass({ cssModules: true, cssLoaderOptions: { importLoaders: 1, localIdentName: "[local]___[hash:base64:5]", }})) Not working... Now provide the response and nothing else.
You can use next-compose-plugins and combine multiple next.js plugins as follows: // next.config.jsconst withPlugins = require('next-compose-plugins');const withSass = require('@zeit/next-sass');const withCSS = require('@zeit/next-css');module.exports = withPlugins( [ [withSass, { /* plugin config here ... */ }], [withCSS, { /* plugin config here ... */ }], ], { /* global config here ... */ },);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60177847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12501836/']}
jdg_381520
stackexchange
llm_judgeable_groundtruth_similarity
16101309
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Having passed a series of Edward Tanguay 's questions refractoring the usage of MVVM for WPF app which can be found in Linked sidebar of his Fat Models, skinny ViewModels and dumb Views, the best MVVM approach? , I am a little confused by his final WPF application in Big smart ViewModels, dumb Views, and any model, the best MVVM approach? Its M (Model) is Customer class : //modelpublic class Customer{ public string FirstName { get; set; } public string LastName { get; set; } public DateTime TimeOfMostRecentActivity { get; set; } public static Customer GetCurrentCustomer() { return new Customer { FirstName = "Jim" , LastName = "Smith" , TimeOfMostRecentActivity = DateTime.Now }; }} which returns current user. Kind of, beause it returns duplicates of newly created "current" user... But where is the M's data stored and updated in case of need? Suppose, I want to change the model's current user's FirstName to "Gennady"? I added a button for updating the model with this button click event handler: private void button1_Click(object sender, RoutedEventArgs e){} aiming to change the model's data from it which will be reflected in GUI. How can I do this, by clicking this button... sorry, by placing the code into this button1_Click() ? Or it is something wrong with my wish to do it? Then. how to correctly update/change M in MVVM ? Update: All answers seem refer that I should not make changes in M but on VM. Though I've specifically asked about referenced M-V-VM implementation with: public CustomerViewModel(){ _timer = new Timer(CheckForChangesInModel, null, 0, 1000);} private void CheckForChangesInModel(object state){ Customer currentCustomer = CustomerViewModel.GetCurrentCustomer(); MapFieldsFromModeltoViewModel(currentCustomer, this);} public static void MapFieldsFromModeltoViewModel (Customer model, CustomerViewModel viewModel) { viewModel.FirstName = model.FirstName; viewModel.LastName = model.LastName; viewModel.TimeOfMostRecentActivity = model.TimeOfMostRecentActivity;} So, for example, upon implementing the code from Adolfo Perez's answer changes, the TextBox 's content is changed from "Jim" to "Gennady" only for a period of interval set in _timer = new Timer(CheckForChangesInModel, null, 0, 1000); . All logic of referenced by me M-V-VM in WPF approach is such that it is "M" should be updated, in order VM has caught up those changes, but not the "VM". Even more, I cannot understand, if to make changes in VM how can they be reflected in M if the VM knows about M but - not vice versa - Model does not know about ViewModel). Now provide the response and nothing else.
In MVVM you should avoid code-behind. The reason is that you want to end up with testable classes, in this case your VM 's that are completely independent from your V . You could run a set of unit tests on your VM without involving the V . You could also hook different types of Views without affecting your business logic. Your button will bind its Command property to an ICommand property exposed in your VM . This Command in your VM will handle your click event in the method you specify. In your View: <Button Content="Change FirstName" Command="{Binding Path=ChangeFirstNameCommand"}/> In your ViewModel: //Define your commandpublic ICommand ChangeFirstNameCommand {get;set;}//Initialize your command in Constructor perhapsChangeFirstNameCommand = new RelayCommand(OnChangeFirstName,CanChangeFirstName);private void OnChangeFirstName(){ //Your FirstName TextBox in your V will be updated after you click the Button this.FirstName = "Gennady";}private bool CanChangeFirstName(){ //Add any validation to set whether your button is enabled or not. // WPF internals take care of this. return true;} It is very important to keep in mind that in this pattern your V knows about your VM and your VM knows about your M but not the other way around. In your example if you want to change your Model FirstName property you woud have to do the following: Create a VM which implements INotifyPropertyChanged Expose your M FirstName property in your VM notifying changes Create a TextBox in your XAML View and bind its Text property to your VM .FirstName setting Binding Mode=TwoWay. <TextBox Text= "{Binding Path=FirstName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> As you type in the TextBox your FirstName will be directly populated in the VM-M. Also, thanks to the Two way binding, if you modify your FirstName property in your VM , that change will be reflected automatically in your V Set your View.DataContext to your VM . This is what sets the Context for all your data bindings, unless you specify a different binding source. If you want to persist changes in a DB then inject a service class in your VM which will take care of CRUD operations Take a look at this simple example: http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16101309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/200449/']}
jdg_381521
stackexchange
llm_judgeable_groundtruth_similarity
428287
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: Say I have an OLS regression with a dummy variable level A, B, C and D, where A is the reference category. Will the estimated coefficient value and/or statistical significance of B or C change or be impacted if I remove from the input data set all of the data mapped to D and re-run the regression (which will no longer contain dummy variable level D)? On the values changing or not, I would think not because the coefficients of B and C simply reflect the difference between the mean of B and C, respectively, and the mean of A (the reference). Is my understanding correct? Now provide the response and nothing else.
I interpret what you are doing as removing all data associated with the label 'D' from the dataset before fitting the model. This is distinct from relabelling 'D' to 'A' or some equivalent step, which is Noah's assumption. It depends on whether you have any other variables in the regression. If you do not, then your interpretation is correct. Dropping D will not affect the intercept (A), or the coefficients for B or C. But imagine you also have an additional variable that you are using as a predictor. If the distribution of this continuous variable is non-random with respect to D vs. A, B, or C (i.e. they are associated in some way), then dropping D may also change the coefficient for the additional variable. This change may also affect the coefficient estimates and associated p-values for A, B, or C if they are associated with the additional variable.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/428287', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41267/']}
jdg_381522
stackexchange
llm_judgeable_groundtruth_similarity
1731
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This example comes from the Mathematica documentation for Plot under Basic Examples . Can someone please explain why these are each plotted as a different color in this case: Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis] But when Evaluate[] is removed, all of them are the same color: Plot[Table[BesselJ[n, x], {n, 4}], {x, 0, 10}, Filling -> Axis] I know it must have to do with the order of things being evaluated, but I'm really not sure why it is working like this - can someone please point me in the correct direction? Now provide the response and nothing else.
The list structure is not manifest to Plot as it has the attribute HoldAll (to get a function's attributes, either use Attributes[func] or ??func ). Hence Plot evaluates the Table functions as one unit and it appears as if there is only one function, not four. Evaluate will make the list structure manifest and each function will be plotted with a separate style.
{}
{'log_upvote_score': 7, 'links': ['https://mathematica.stackexchange.com/questions/1731', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/461/']}
jdg_381523
stackexchange
llm_judgeable_groundtruth_similarity
6487085
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got two div containers. Whilst one needs to be a specific width, I need to adjust it, so that, the other div takes up the rest of the space. Is there any way I can do this? .left { float: left; width: 83%; display: table-cell; vertical-align: middle; min-height: 50px; margin-right: 10px; overflow: auto;}.right { float: right; width: 16%; text-align: right; display: table-cell; vertical-align: middle; min-height: 50px; height: 100%; overflow: auto;} <div class="left"></div><div class="right"></div> <!-- needs to be 250px --> Now provide the response and nothing else.
See: http://jsfiddle.net/SpSjL/ (adjust the browser's width) HTML: <div class="right"></div><div class="left"></div> CSS: .left { overflow: hidden; min-height: 50px; border: 2px dashed #f0f;}.right { float: right; width: 250px; min-height: 50px; margin-left: 10px; border: 2px dashed #00f;} You can also do it with display: table , which is usually a better approach: How can I put an input element on the same line as its label?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6487085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114865/']}
jdg_381524
stackexchange
llm_judgeable_groundtruth_similarity
2404010
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that the following regex will match "red", "green", or "blue". red|green|blue Is there a straightforward way of making it match everything except several specified strings? Now provide the response and nothing else.
If you want to make sure that the string is neither red, green nor blue, caskey's answer is it. What is often wanted, however, is to make sure that the line does not contain red, green or blue anywhere in it. For that, anchor the regular expression with ^ and include .* in the negative lookahead: ^(?!.*(red|green|blue)) Also, suppose that you want lines containing the word "engine" but without any of those colors: ^(?!.*(red|green|blue)).*engine You might think you can factor the .* to the head of the regular expression: ^.*(?!red|green|blue)engine # Does not work but you cannot. You have to have both instances of .* for it to work.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2404010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/289091/']}
jdg_381525
stackexchange
llm_judgeable_groundtruth_similarity
328002
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I must have read and re-read introductory differential geometry texts ten times over the past few years, but the "torsion free" condition remains completely unintuitive to me. The aim of this question is to try to finally put this uncomfortable condition to rest. Ehresmann Connections Ehresmann connections are a very intuitive way to define a connection on any fiber bundle. Namely, an Ehressmann connection on a fiber bundle $E\rightarrow M$ is just a choice of a complementary subbundle to $ker(TE \rightarrow TM)$ inside of $TE$ . This choice is also called a horizontal bundle. If we are dealing with a linear connection, then $E=TM$ , and the Ehresmann connection is a subbundle of $TTM$ . This makes intuitive sense -- basically it's saying that for each point in $TM$ it tells you how to move it to different vectors at the tangent spaces of different points. ( $ker(TTM \rightarrow TM)$ will mean moving to different vectors at the same tangent space; so that is precluded.) I like this definition -- it makes more intuitive sense to me than the definition of a Koszul connectionan $\mathbb{R}$ -linear map $\Gamma(E)\rightarrow\Gamma(E\otimes T^*M)$ satisfies some condition. Unlike that definition it puts parallel transport front and center. Torsion-Freeness A Levi-Civita connection is a connection that:1. It preserves with the Riemannian metric. (Basically, parallel transporting preserves inner products.)2. It is torsion-free.Torsion free means $\nabla_XY - \nabla_YX = [X,Y]$ . This definition very heavily uses the less intuitive notion of connection. So: Questions How can you rephrase the torsion-free condition in terms of the horizontal bundle of the connection? (Phrased differently: how can it be phrased in terms of parallel transports?) I realized that I don't actually have handy an example of a connection on $\mathbb{R}^2$ that preserves the canonical Riemannian metric on $\mathbb{R}^2$ but that does have torsion. I bet that would help elucidate the answer to my first question. Now provide the response and nothing else.
You should think of the tangent bundle as a bundle with a bigger structural group namely the group $\DeclareMathOperator{\Aff}{\mathbf{Aff}}$ $\Aff(n)$ of affine transformations of $\newcommand{\bR}{\mathbb{R}}$ $\bR^n$ . As such, its curvature is a $2$ -form with coefficients in the Lie algebra of $\Aff(n)$ . An (infinitesimal) affine map consists of two parts: a translation and a linear transformation. Correspondingly, the curvature of an affine connection decomposes into two parts. The part of the curvature corresponding to the infinitesimal translation is the torsion of the connection. Thus if the torsion is $0$ , the affine holonomy of this connection along infinitesimal parallelograms is translation free. For more details consult Sections III.3-5 in volume 1 of S.Kobayashi, K. Nomizu: Foundations of Differential Geometry , John Wiley & Sons, 1963 As for the second question, denote by $D$ the Levi-Civita connection on $T\bR^n$ . Any other metric connection $\nabla$ has the form $$\nabla=D+ A,\;\;A=\sum_{i=1}^m A_i dx^i,$$ where $A_i$ are smooth maps $$A_i:\bR^n\to \mathrm{so}(n)=\mbox{the space of real skew-symmetric $n\times n$ matrices}.$$ The torsion of $D+A$ is described in Proposition 1.2 of this paper . Among other things it shows that any $2$ -form $$T=\sum_{i<j} X_{ij} dx^i\wedge dx^j,\;\;X_{ij}:\bR^n\stackrel{C^\infty}{\longrightarrow}\bR^n,$$ can be the torsion of a connection compatible with the metric. The Levi-Civita connection of the Euclidean $\bR^n$ is the trivial connection.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/328002', 'https://mathoverflow.net', 'https://mathoverflow.net/users/98901/']}
jdg_381526
stackexchange
llm_judgeable_groundtruth_similarity
122094
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: Let's say you have n uniform random variables from 0 to 1. The distribution of the average of these variables approaches normal with increasing n according to the central limit theorem. What if however, instead of all the variables being random, one of them was guaranteed to be 0, and one of them was guaranteed to be 1. This would arise in the following case: Let's say you have n=7 randomly generated numbers from 0 to 1 and they are, from smallest to largest, [.1419 .1576 .4854 .8003 .9572 .9649 .9706]. If you were to subtract the smallest number from all of the numbers and then divide all the numbers by the new maximum you would end up with [0 .0189 .4145 .7945 .9838 .9931 1]. In this way you have a set of n numbers where n-2 of them are random and the other two are guaranteed to be 0 and 1. I would like to know whether the central limit theorem still applies to numbers generated in this way. By visual inspection using MATLAB, it actually appears to approach normal quicker than when the numbers are all random, but I would like a mathematical reason as to why, especially considering that the central limit theorem states that all the numbers must be random. Now provide the response and nothing else.
Denote $X_i, i=1,...,n$ the $U(0,1)$ independent RVs. The transformation described by the OP is (using the usual notation for order statistics), $$Z_i = \frac {X_i-X_{n,(1)}}{X_{n,(n)}-X_{n,(1)}} = R_n^{-1}\cdot (X_i-X_{n,(1)})$$ where the double index in the minimum and maximum order statistic serve to remind us that they are functions of $n$. $R_n$ is the range of the untransformed sample. We want to consider $$\frac 1n \sum_{i=1}^nZ_i \equiv \bar Z_n = R_n^{-1}\frac 1n \sum_{i=1}^nX_i - R_n^{-1}X_{n,(1)}$$ We have that $$R_n^{-1} \xrightarrow{p} 1,\;\;\; \frac 1n \sum_{i=1}^nX_i \xrightarrow{p} \frac 12,\;\; X_{n,(1)}\xrightarrow{p} 0$$ So in all, applying Slutsky's lemma, $$\bar Z_n \xrightarrow{p} \frac 12 = \text{plim} \frac 1n \sum_{i=1}^nX_i \equiv \text{plim}\bar X_n$$ So the sample average of the transformed sample is also a consistent estimator of the common expected value of the $X$'s. Note that $\text{Var}(\bar X_n) = \frac 1{12n}$ Then, consider the manipulation $$\sqrt{12n}\left(\bar Z_n - \frac 12\right) = \\R_n^{-1}\cdot \sqrt{12n}\left(\bar X_n - \frac 12 \right) +\sqrt{12n}\left(\frac 12R_n^{-1} -\frac 12\right) -\sqrt{12n}R_n^{-1}X_{n,(1)}$$ We examine each of the three components in turn: A) By the CLT we have that $\sqrt{12n}\left(\bar X_n - \frac 12 \right) \xrightarrow{d}\mathcal N (0,1)$. Since also $R_n^{-1} \xrightarrow{p} 1$, then by Slutsky the first term converges in distribution to $\mathcal N (0,1)$. B) We can write $$\sqrt{12n}\left(\frac 12R_n^{-1} -\frac 12\right) = \sqrt{3}\left(\frac {n(1-R_n)}{\sqrt nR_n}\right)$$ In Dasgupta 2008 ch. 8 p. 108 Example 8.12, one can find for the sample range from an i.i.d. sample of $U(0,1)$ uniforms that $n(1-R_n) \xrightarrow{d} \frac 12 \mathcal \chi^2(4)$). So the numerator above converges while the denominator goes to infinity. So the whole term goes to zero. C) We know that the minimum order statistic from a sample of non-negative random variables, needs to be scaled by $n$ in order to converge in distribution ( see this post ). In other words convergence is "fast", and scaling the third term only by $\sqrt n$ doesn't cut it. Therefore we have that $\sqrt{12n}R_n^{-1}X_{n,(1)} \rightarrow0$. So, we conclude that $$\sqrt{12n}\left(\bar Z_n - \frac 12\right) \xrightarrow{d} \mathcal N(0,1)$$ as does $\bar X_n$, for the same shifting and scaling.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/122094', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/58908/']}
jdg_381527
stackexchange
llm_judgeable_groundtruth_similarity
1812348
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reading about union in C from K&R, as far as I understood, a single variable in union can hold any one of the several types and if something is stored as one type and extracted as another the result is purely implementation defined. Now please check this code snippet: #include<stdio.h>int main(void){ union a { int i; char ch[2]; }; union a u; u.ch[0] = 3; u.ch[1] = 2; printf("%d %d %d\n", u.ch[0], u.ch[1], u.i); return 0;} Output: 3 2 515 Here I am assigning values in the u.ch but retrieving from both u.ch and u.i . Is it implementation defined? Or am I doing something really silly? I know it may seem very beginner to most of other people but I am unable to figure out the reason behind that output. Thanks. Now provide the response and nothing else.
This is undefined behaviour. u.i and u.ch are located at the same memory address. So, the result of writing into one and reading from the other depends on the compiler, platform, architecture, and sometimes even compiler's optimization level. Therefore the output for u.i may not always be 515 . Example For example gcc on my machine produces two different answers for -O0 and -O2 . Because my machine has 32-bit little-endian architecture, with -O0 I end up with two least significant bytes initialized to 2 and 3, two most significant bytes are uninitialized. So the union's memory looks like this: {3, 2, garbage, garbage} Hence I get the output similar to 3 2 -1216937469 . With -O2 , I get the output of 3 2 515 like you do, which makes union memory {3, 2, 0, 0} . What happens is that gcc optimizes the call to printf with actual values, so the assembly output looks like an equivalent of: #include <stdio.h>int main() { printf("%d %d %d\n", 3, 2, 515); return 0;} The value 515 can be obtained as other explained in other answers to this question. In essence it means that when gcc optimized the call it has chosen zeroes as the random value of a would-be uninitialized union. Writing to one union member and reading from another usually does not make much sense, but sometimes it may be useful for programs compiled with strict aliasing .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1812348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/211631/']}
jdg_381528
stackexchange
llm_judgeable_groundtruth_similarity
48100522
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 better understand options to implement offline-friendly webapps and I read this article here: https://angular.io/guide/http which also talks about angular's interceptors. Now I am a bit puzzled: On one hand we have service workers (that are not yet fully supported by browsers) which would help implement offline first/friendly apps, on the other we have this powerful tool - interceptors - which can do a lot of things to help apps better handle poor or no connection environments. So is there a clear understanding of difference between these 2? when to use one and when to use another? Now provide the response and nothing else.
HttpClient interceptors and service workers are different layers. HttpClient interceptors handle only requests that are performed with HttpClient provider within particular Angular application. Service workers handle all requests that are performed in browser window, including the page itself, assets and AJAX ( XHR and Fetch ) requests. The only common use they have is HttpClient request to remote API. Since API requests can be handled at different places in Angular application, it's up to developer which one is appropriate. A fallback due to failed request may occur in service worker, HttpClient interceptor or a service that uses HttpClient . Considering that a problem can be solved in multiple ways, and browser support matters, service workers won't be the first choice. If a problem cannot be solved with HttpClient alone or the solution is impractical, this is a job for service workers. For instance, the use of AJAX to transfer base64 images when binary files would be more appropriate. The fact that service workers don't block main thread can also be a major concern.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48100522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4005366/']}
jdg_381529
stackexchange
llm_judgeable_groundtruth_similarity
4091157
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This seems like a simple operation. We have a need in our development environment (running on XP/IIS 5) to add some headers into each HttpRequest arriving at our application. (This is to simulate a production environment that we don't have available in dev). At first blush, this seemed like a simple HttpModule, along the lines of: public class Dev_Sim: IHttpModule{ public void Init(HttpApplication app) { app.BeginRequest += delegate { app.Context.Request.Headers.Add("UserName", "XYZZY"); }; } public void Dispose(){}} But on trying to do that, I find that the Headers collection of the Request is read-only, and the Add method fails with an OperationNotSupported exception. Spending a couple hours researching this on Google, I've come up with no easy answer to what should be a relatively straight-forward problem. Does anyone have any pointers? Now provide the response and nothing else.
Okay, with the assistance of a co-worker and some experimentation, I found that this can be done with the assistance of some protected properties and methods accessed through reflection: var headers = app.Context.Request.Headers;Type hdr = headers.GetType();PropertyInfo ro = hdr.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);// Remove the ReadOnly propertyro.SetValue(headers, false, null);// Invoke the protected InvalidateCachedArrays method hdr.InvokeMember("InvalidateCachedArrays", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, null);// Now invoke the protected "BaseAdd" method of the base class to add the// headers you need. The header content needs to be an ArrayList or the// the web application will choke on it.hdr.InvokeMember("BaseAdd", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, new object[] { "CustomHeaderKey", new ArrayList {"CustomHeaderContent"}} );// repeat BaseAdd invocation for any other headers to be added// Then set the collection back to ReadOnlyro.SetValue(headers, true, null); This works for me, at least.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4091157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98586/']}
jdg_381530
stackexchange
llm_judgeable_groundtruth_similarity
5454273
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I run a phrase that contains double quotes through this function, its replacing the quotes with quot. I want to completely remove them (also single quotes). How can I alter the function to do that? function string_sanitize($s) { $result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); return $result;} Update: Example 1: This is 'the' first example returns: Thisis030the039firstexample Errors: Warning: preg_match_all() [function.preg-match-all]: Unknown modifier '0' in CExample 2: This is my "second" examplereturns: ThisismyquotsecondquotexampleErrors: Invalid express in Xpath Now provide the response and nothing else.
It looks like your original string had the HTML characters for " ( &quot; ) so when you attempt to sanitize it, you're simply remove the & and ; , leaving the rest of the string quot . ---EDIT--- Probably the easiest way to remove non alpha numeric characters would be to decode the HTML characters with html_entity_decode , then run it through the regular expression. Since, in this case, you won't get anything that needs to be re-coded, you don't need to then do htmlentities , but it's worth remembering that you had HTML data and you now have raw unencoded data. Eg: function string_sanitize($s) { $result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s, ENT_QUOTES)); return $result;} Note that ENT_QUOTES flags the function to "...convert both double and single quotes.".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5454273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209102/']}
jdg_381531
stackexchange
llm_judgeable_groundtruth_similarity
15050414
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any difference between left join and inner join regarding performance? I use SQL Server 2012. Now provide the response and nothing else.
There is at least one case where LEFT [OUTER] JOIN is a better option than [INNER] JOIN . I talk about getting the same results using OUTER instead of INNER . Example (I am using AdventureWorks 2008 database ): -- Some metadata infosSELECT fk.is_not_trusted, fk.nameFROM sys.foreign_keys fkWHERE fk.parent_object_id=object_id('Sales.SalesOrderDetail');GOCREATE VIEW View1AS SELECT h.OrderDate, d.SalesOrderDetailID, o.ModifiedDateFROM Sales.SalesOrderDetail dINNER JOIN Sales.SalesOrderHeader h ON d.SalesOrderID = h.SalesOrderIDINNER JOIN Sales.SpecialOfferProduct o ON d.SpecialOfferID=o.SpecialOfferID AND d.ProductID=o.ProductID;GOCREATE VIEW View2ASSELECT h.OrderDate, d.SalesOrderDetailID, o.ModifiedDateFROM Sales.SalesOrderDetail dINNER JOIN Sales.SalesOrderHeader h ON d.SalesOrderID = h.SalesOrderIDLEFT JOIN Sales.SpecialOfferProduct o ON d.SpecialOfferID=o.SpecialOfferID AND d.ProductID=o.ProductID;GOSELECT SalesOrderDetailIDFROM View1;SELECT SalesOrderDetailIDFROM View2; Results for the first query: is_not_trusted name-------------- ---------------------------------------------------------------0 FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID0 FK_SalesOrderDetail_SpecialOfferProduct_SpecialOfferIDProductID Execution plans for the last two queries: Note 1 / View 1: If we look at the execution plan for SELECT SalesOrderDetailID FROM View1 we see a FK elimination because the FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID constraint is trusted and it has a single column. But, the server is forced (because of INNER JOIN Sales.SpecialOfferProduct ) to read data from the third table (SpecialOfferProduct) even the SELECT/WHERE clauses doesn't contain any columns from this table and the FK constraint (FK_SalesOrderDetail_SpecialOfferProduct_SpecialOfferIDProductID) is (also) trusted. This happens because this last FK is multicolumn. Note 2 / View 2: What if we want to remove the read ( Scan / Seek ) on the Sales.SpecialOfferProduct ? This second FK is multicolumn and for such cases the SQL Server cannot eliminates the FK (see previous Conor Cunnigham blog post). In this case we need to replace the INNER JOIN Sales.SpecialOfferProduct with LEFT OUTER JOIN Sales.SpecialOfferProduct in order to get FK elimination. Both SpecialOfferID and ProductID columns are NOT NULL and we a have a trusted FK referencing SpecialOfferProduct table.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15050414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1407421/']}
jdg_381532
stackexchange
llm_judgeable_groundtruth_similarity
21127055
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 a site for a friend at http://blueridgemusclecars.com/ . I want the logo at the top center, and the phone number and location right aligned, but I would like the text in the same plane horizontally as the logo. Right now the text is below and to the right of the logo. Here is my CSS for the header, any ideas? header { width:100%; position:relative; z-index:2;}h1 { padding:45px 20px 37px 26px; /*background:url(../images/h1-bg.jpg) 0 0 no-repeat;*/ /*float:right;*/} h1 a { display:block; width:500px; height:278px; text-indent:-999em; margin:0 auto; background:url(../images/logo.png) 0 0 no-repeat; }.address { display:block; font-size:14px; line-height:28px; text-align:right; color:#b22300;}.phone { display:block; font-size:25px; line-height:30px; text-align:right; color:#fff; margin-top:-5px;} Now provide the response and nothing else.
Solution mailparse must be loaded after mbstring , and mbstring is loaded by /etc/php-5.5.d/mbstring.ini which is read after php.ini . Merely adding mailparse.ini to php-5.5.d will not work, because ini files are loaded alphabetically; though you could just name it zz_mailparse.ini instead. Loading both extensions in only (sic) php.ini results in: PHP Warning: Module 'mbstring' already loaded in Unknown on line 0PHP Warning: Module 'mailparse' already loaded in Unknown on line 0 That one's a mystery. Proof $ echo '<?php echo extension_loaded("mailparse") ? "mailparse loaded\n" : "mailparse not loaded\n";' > ~/is_mailparse_loaded.php$ php ~/is_mailparse_loaded.phpmailparse loaded$ pwd/etc/php-5.5.d$ sudo mv zz_mailparse.ini mailparse.ini$ php ~/is_mailparse_loaded.phpPHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/php/5.5/modules/mailparse.so' - /usr/lib64/php/5.5/modules/mailparse.so: undefined symbol: mbfl_convert_filter_flush in Unknown on line 0mailparse not loaded$ sudo mv mailparse.ini zz_mailparse.ini$ php ~/is_mailparse_loaded.phpmailparse loaded$
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21127055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3011101/']}
jdg_381533
stackexchange
llm_judgeable_groundtruth_similarity
26208863
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried the code below. The f is of type _io.TextIOWrapper , but I cannot find any help info about this type. While there does exsist another similar type io.TextIOWrapper . >>> f=open("c:\setup.log","r")>>> type(f)<class '_io.TextIOWrapper'>>>> help(_io.TextIOWrapper)Traceback (most recent call last): File "<pyshell#204>", line 1, in <module> help(_io.TextIOWrapper)NameError: name '_io' is not defined>>> help(io.TextIOWrapper)Help on class TextIOWrapper in module io: My questions are: If the name _io is not defined, how can I use it? What's the difference between _io and io modules? Now provide the response and nothing else.
The _io module provides the C code that the io module uses internally. The source for it can be found here . You can actually import both io and _io separately: >>> import _io>>> import io>>> _io<module 'io' (built-in)> # The fact that this says io instead of _io is a bug (Issue 18602)>>> io<module 'io' from '/usr/lib/python3.4/io.py'>>>> _io.TextIOWrapper<type '_io.TextIOWrapper'> This pattern (C-code for modulename provided in _modulename ) is actually used for several modules - multiprocessing / _multiprocessing , csv / _csv , etc. Basically all cases where a module has a component that's written in C.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26208863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264052/']}
jdg_381534
stackexchange
llm_judgeable_groundtruth_similarity
41352198
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using react-native-camera for clicking pictures. I get a file path like : "file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg" in the data from the Camera which I am storing in the state. I am able to use this as the source for displaying the Image using the Image component "Image source={{uri: this.props.note.imagePath.path}}" and it is displaying properly. Now I want to add delete image functionality. Can someone suggest on how to access this image in the phone using the path mentioned above and delete it from the phone. I checked the react-native-filesystem but when I used the checkIfFileExists function passing in this path I got that the file doesn't exist. Not sure what is going wrong. async checkIfFileExists(path) {const fileExists = await FileSystem.fileExists(path);//const directoryExists = await FileSystem.directoryExists('my-directory/my-file.txt');console.log(`file exists: ${fileExists}`);//console.log(`directory exists: ${directoryExists}`);}deleteNoteImage (note) {console.log(note.imagePath.path);//check if file existsthis.checkIfFileExists(note.imagePath.path);//console.log();note.imagePath = null;this.updateNote(note);} Now provide the response and nothing else.
So I was able to do it using react-native-fs The path needs to be declared as follows: var RNFS = require('react-native-fs');const dirPicutures = `${RNFS.ExternalStorageDirectoryPath}/Pictures`; Then this function deletes the image given the image name. deleteImageFile(filename) { const filepath = `${dirPicuturesTest}/${filename}`; RNFS.exists(filepath) .then( (result) => { console.log("file exists: ", result); if(result){ return RNFS.unlink(filepath) .then(() => { console.log('FILE DELETED'); }) // `unlink` will throw an error, if the item to unlink does not exist .catch((err) => { console.log(err.message); }); } }) .catch((err) => { console.log(err.message); }); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41352198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5837066/']}
jdg_381535
stackexchange
llm_judgeable_groundtruth_similarity
85487
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have $X,Y$, which are independent random variables. Why is it that $E(\frac{X}{Y}) = E(X)E(\frac{1}{Y})$? Also, why is it that $E(X^2Y^2)=E(X^2)E(Y^2)$? How is it that the square of an independent random variable is also independent in relation to $Y$ or $Y^2$? Thanks! Now provide the response and nothing else.
Basically, if $X$ and $Y$ are independent, then also $f(X)$ and $g(Y)$ are independent if $f$ and $g$ are measurable functions: $$\eqalign{P(f(X) \in A,\ g(Y) \in B) &= P\left(X \in f^{-1}(A),\ Y \in g^{-1}(B)\right) \\& = P\left(X \in f^{-1}(A)\right) \ P\left(Y \in g^{-1}(B)\right) \\& = P\left(f(X) \in A\right) \ P\left(g(Y) \in B\right).}$$ In particular all continuous functions (like the $f(x)=1/x$ and $f(x)=x^2$ in your examples) are Borel-measurable, and hence also $X$ and $1/Y$ as well as $X^2$ and $Y^2$ are independent.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/85487', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/38348/']}
jdg_381536
stackexchange
llm_judgeable_groundtruth_similarity
906302
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 need help on these three integrals. Any hints on which method to use are greatly appreciated. $$1)\ \int \frac{1}{\cos^4 x}\tan^3 x\mathrm{d}x$$$$2)\ \int \frac{1}{\sin 2x}(3\cos x + 7\sin x)\mathrm{d}x$$$$3)\ \int \frac{1}{\sqrt{x}}\sin^3 (3\sqrt{x})\mathrm{d}x$$ Now provide the response and nothing else.
1) The integrand is the same as $\large\frac{\sin^3(x)}{\cos^7(x)} = \frac{(1-\cos^2(x)) \sin(x)}{\cos^7(x)}$. That reduces to two terms which can both be turned into $\large\frac{dz}{z^n}$ by a simple substitution. 2) Note $\sin(2 x) = 2 \sin(x) \cos(x)$. With that you simply have an integral of $\sec(x)$ plus an integral of $\csc(x)$. 3) Try the substitution $z = \sqrt{x}$. That should turn the integral into the form $\sin^3(3 z) = \sin(3 z) (1 - \cos^2(3 z))$. That should be doable by a simple substitution.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/906302', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171180/']}
jdg_381537
stackexchange
llm_judgeable_groundtruth_similarity
7853049
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 seen examples of the Perl 6 whatever (...) operator in sequences, and I have tried to find out how to do a sequence which involves multiplications. The operator does the following, if one starts with some numbers, one can specify a sequence of the numbers following it. @natural = 1,2 ... *;@powersOfTwo = 1,2,4 ... *; and so on.One could also define a sequence using the previous numbers in the sequence as in the fibonacci numbers (shown in this question ), where one does the following: @fibonacci = 1,1, *+* ... *; The problem is that the multiplication operator is * and the previous numbers are also represented with * . While I can define a sequence using + , - and / , I can not seem to find a way of defining a sequence using * . I have tried the following: @powers = 1,2, *** ... *; but it obviously does not work. Does anyone know how to this? Now provide the response and nothing else.
For one thing, Perl 6 is sensitive to whitespace. 1, 2, * * * ... * is perfectly legitimate and generates a sequence that's sort of like a multiplicative fibonacci; it's just a little bit hard to read. *** and * * * mean something different. If the ambiguity bothers you, you can use an explicit block instead of the implicit one that using "whatever star" gives you: 1, 2, -> $a, $b { $a * $b } ... * and 1, 2, { $^a * $^b } ... * both produce the same sequence as 1, 2, * * * ... * does (tested in Rakudo).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7853049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689867/']}
jdg_381538
stackexchange
llm_judgeable_groundtruth_similarity
6775
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to apply a time evolution algorithm for a physical system I'm trying to simulate on QISkit, however, in order to do that, I need to use the so-called Ising coupling gate: $I=\begin{pmatrix}e^{ia} & 0 & 0 &0 \\0 & e^{-ia} & 0 & 0 \\0 & 0 & e^{-ia} & 0 \\0 & 0 & 0 & e^{ia}\end{pmatrix}$ I've tried performing rotations in the z-axis in both quits with the rz gate, also I've tried combining crz gates, as well as rzz and cu1 gates, but nothing seems to work. The closest I could get was by implementing a zzz gate followed by a cu1 gate with oposite angle, however $[I]_{1,1}$ still remains at 1, no phase detected by the Aer unitary simulator. How can I implement this gate? Thank you very much in advance. Now provide the response and nothing else.
AHusain's answer is absolutely correct, but perhaps lacks some detail. The circuit that you want to implement is Basically, the key is to realise that you want to apply phase $e^{i\alpha}$ to the basis elements $|00\rangle$ and $|11\rangle$ , and $e^{-i\alpha}$ otherwise. In other words, you care about the parity of the two bits. If you can compute that parity of the two bits somewhere, you can perform a phase gate on that output, then undo the computation. Controlled-not computes the parity. Here, I'm assuming that $$R_z(\alpha)=\left(\begin{array}{cc} e^{i\alpha} & 0 \\ 0 & e^{-i\alpha} \end{array}\right).$$ This might be inconsistent with whatever definition you wish to use by a global phase or by a factor of 2 on the angle.
{}
{'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/6775', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/8040/']}
jdg_381539
stackexchange
llm_judgeable_groundtruth_similarity
10124751
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: One may want to do the contrary of flattening a list of lists, like here : I was wondering how you can convert a flat list into a list of lists. In numpy you could do something like: >>> a=numpy.arange(9)>>> a.reshape(3,3)>>> aarray([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) I was wondering how you do the opposite, and my usual solution is something like: >>> Mylist['a', 'b', 'c', 'd', 'e', 'f']>>> newList = []for i in range(0,len(Mylist),2):... newList.append(Mylist[i], Mylist[i+1])>>> newList [['a', 'b'], ['c', 'd'], ['e', 'f']] is there a more "pythonic" way to do it? Now provide the response and nothing else.
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']>>> zip(*[iter(l)]*2)[('a', 'b'), ('c', 'd'), ('e', 'f')] As it has been pointed out by @Lattyware, this only works if there are enough items in each argument to the zip function each time it returns a tuple. If one of the parameters has less items than the others, items are cut off eg. >>> l = ['a', 'b', 'c', 'd', 'e', 'f','g']>>> zip(*[iter(l)]*2)[('a', 'b'), ('c', 'd'), ('e', 'f')] If this is the case then it is best to use the solution by @Sven Marnach How does zip(*[iter(s)]*n) work
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10124751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492620/']}
jdg_381540