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
4931323
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 making a simple, very lightweight front-controller. I need to match request paths to different handlers (actions) in order to choose the correct one. On my local machine HttpServletRequest.getPathInfo() and HttpServletRequest.getRequestURI() return the same results. But I'm not sure what will they return in the production environment. So, what's the difference between these method and what should I choose? Now provide the response and nothing else.
I will put a small comparison table here (just to have it somewhere): Servlet is mapped as /test%3F/* and the application is deployed under /app . http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a Method URL-Decoded Result ----------------------------------------------------getContextPath() no /appgetLocalAddr() 127.0.0.1getLocalName() 30thh.locgetLocalPort() 8480getMethod() GETgetPathInfo() yes /a?+bgetProtocol() HTTP/1.1getQueryString() no p+1=c+d&p+2=e+fgetRequestedSessionId() no S%3F+IDgetRequestURI() no /app/test%3F/a%3F+b;jsessionid=S+IDgetRequestURL() no http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+IDgetScheme() httpgetServerName() 30thh.locgetServerPort() 8480getServletPath() yes /test?getParameterNames() yes [p 2, p 1]getParameter("p 1") yes c d In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file. Comments "+" is handled as space only in the query string Anchor "#a" is not transferred to the server. Only the browser can work with it. If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp ), getPathInfo() returns null . If Spring MVC is used Method getPathInfo() returns null . Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4931323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100516/']}
jdg_81241
stackexchange
llm_judgeable_groundtruth_similarity
9700115
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: matches : Will check if the complete string entered is equal to the value present in the string object. equalsIgnoreCase : Ignoring the case, it checks if the string entered is equal to the value present in the string object. equals : Case sensitive and it checks if the string entered is equal to the value present in the string object. This is what I know about the methods, present in String class. Are there any other differences(Am I missing any valuable differences)? If there are no differences, then why cant matches method be removed from String class, since the functionality it puts forth can be achieved using the other above mentioned methods, appropriately. Now provide the response and nothing else.
There is a big difference - matches checks the match of a String to a regular expression pattern, not the same string. Do not be mislead by the fact that it receives a String as an argument. For example: "hello".equals(".*e.*"); // false"hello".matches(".*e.*"); // true
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9700115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/818557/']}
jdg_81242
stackexchange
llm_judgeable_groundtruth_similarity
56334492
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 C++ , how do you create a simple fixed size queue ? I have done it multiple times in Java and Python but am looking for a C++ based way of doing so. I need a simple FIFO queue with only 2 elements in order to use the push and pop utilities: I am already aware of the fact that I could implement my own class to perform this kind of restriction but my question aims to know if there exist any already available solution to this. Or is it maybe possible to accomplish the same task with an array? That would work as well. Now provide the response and nothing else.
You could inherit from queue, and then reimplement the push method. Here is a basic example. #include <queue>#include <deque>#include <iostream>template <typename T, int MaxLen, typename Container=std::deque<T>>class FixedQueue : public std::queue<T, Container> {public: void push(const T& value) { if (this->size() == MaxLen) { this->c.pop_front(); } std::queue<T, Container>::push(value); }};int main() { FixedQueue<int, 3> q; q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); q.push(6); q.push(7); while (q.size() > 0) { std::cout << q.front() << std::endl; q.pop(); }} This will print $ g++ fixedqueue.cpp -std=c++17 -o fixedqueue && ./fixedqueue567
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56334492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5052566/']}
jdg_81243
stackexchange
llm_judgeable_groundtruth_similarity
1769828
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In metric space, we have the notion of distance, which enables us to have a general idea on the "size" of an open set, say, by measuring its diameter . If we now have 2 open sets $A,B$ in a topological space, we tends have the impression that $A$ is "smaller than" $B$ if $A\subset B$. But what if we are given 2 disjoint open set? Is there a general way for us to compare "size" of open set in a topological space? (Say, $A$ is smaller than $B$, or $A$ and $B$ have the similar size) How can we get the impression of the size of an open set in a topological space? Thanks. P.s. Cardinality does not count as a solution because it does not rely on the topology anyway. Now provide the response and nothing else.
The comments and answer here seem to be a little depressing - topology can still measure interesting properties of open sets! Michael Burr is probably right in that you can't hope for anything more than a poset, but let's at least construct an interesting one! Let's try the following: $$\text{Define }\;A \le B\text{ if there is an embedding }\;A \stackrel{f}\hookrightarrow B.$$ We can check that this gives us a partial ordering on topological spaces, hence also topological subspaces. In addition, if $A \subset B$ are subspaces of $X$ then $A \le B$. (Note that if $A \le B$ it may not be the case that $A \subset B$.) This is a purely topological characterization, and it turns out to be interesting, because we can use topological tools to study it! One immediate question that you might have is, "Can you produce two spaces $X, Y$ such that $X \lneq Y$?" It turns out this is pretty easy: take $X = \mathbb R^2$, and take $Y = \mathbb{RP}^2$. Or if we want spaces that are incomparable elements consider $\mathbb{RP}^2$ and $S^2$. All these results rely on interesting algebraic topology. So it seems this is an interesting way to characterize "size" in terms of topological complexity. A few fun exercises for interested readers, in roughly increasing order of difficulty: Given a space $X$, what subspace(s) is/are minimal in this order? What set is a maximal element? Construct a space $X$ and subsets $A_i \subset X$ such that $$A_1 \lneq A_2 \lneq \cdots \lneq X.$$ Give a version of the previous construction where $X$ and the $A_i$ are all connected. Prove that $\mathbb{RP}^2$ and $S^2$ are incomparable elements. Prove that $\mathbb{R}^2 \lneq \mathbb{RP}^2$. Construct a topological space $X$ and subspaces $\{A_r\}_{r \in \mathbb{R}_{\ge 0}}$ with $|X| = \mathfrak{c}$ (the cardinality of the continuum) and $A_r \lneq A_{r'}$ for all $r < r'$. (I'm not 100% sure my answer here is correct, or that this is possible.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1769828', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25841/']}
jdg_81244
stackexchange
llm_judgeable_groundtruth_similarity
100763
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: Specifically, I would like to know the general formula, in terms of $n$ and $l$, assuming the electron is in an orbital (i.e. simultaneous eigenstate of $H$, $L^2$, and $L_z$). I understand that it involves integrating an associated Laguerre polynomial, but I wasn't able to find the formula for the integral. I looked on Wikipedia and in Abramowitz & Stegun, but no luck. Now provide the response and nothing else.
There exists something called Kramers's recursion rule and I think it is what are you looking for. $$\frac{k+1}{n^2} \left\langle r^k \right\rangle - \frac{a_0}{Z} \left(2k+1\right)\left\langle r^{k-1} \right\rangle + \frac{k a_0^2}{4Z^2} \left( \left(2l+1\right)^2 - k^2 \right) \left\langle r^{k-2} \right\rangle,$$ where $k$ is integer and $a_0$ Bohr radius. For deriving $\left\langle r \right\rangle$ you have to calculate $\left\langle r^{-1} \right\rangle$ at first by setting $k=0$ and then you can set $k=1$ and calculate $\left\langle r \right\rangle$ . And of course you know $\left\langle r^{0} \right\rangle = 1$ . The result is $$\left\langle r \right\rangle = \frac{a_0}{2Z}\left(3n^2-l\left(l+1\right)\right).$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/100763', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/25572/']}
jdg_81245
stackexchange
llm_judgeable_groundtruth_similarity
42013822
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 fairly straightforward nested for loop that iterates over four arrays: for a in a_grid: for b in b_grid: for c in c_grid: for d in d_grid: do_some_stuff(a,b,c,d) # perform calculations and write to file Maybe this isn't the most efficient way to perform calculations over a 4D grid to begin with. I know joblib is capable of parallelizing two nested for loops like this , but I'm having trouble generalizing it to four nested loops. Any ideas? Now provide the response and nothing else.
I usually use code of this form: #!/usr/bin/env python3import itertoolsimport multiprocessing#Generate values for each parametera = range(10)b = range(10)c = range(10)d = range(10)#Generate a list of tuples where each tuple is a combination of parameters.#The list will contain all possible combinations of parameters.paramlist = list(itertools.product(a,b,c,d))#A function which will process a tuple of parametersdef func(params): a = params[0] b = params[1] c = params[2] d = params[3] return a*b*c*d#Generate processes equal to the number of corespool = multiprocessing.Pool()#Distribute the parameter sets evenly across the coresres = pool.map(func,paramlist)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42013822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1803782/']}
jdg_81246
stackexchange
llm_judgeable_groundtruth_similarity
500129
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'm running a paired t-test to compare before and after counts.Here's what my data looks like: before <- c(102,122,64,0)after <- c(38,39,23,16) Here's my results of the t.test: t.test(before, after, data = fence2016.data, paired = TRUE) Paired t-testdata: before and aftert = 2.0038, df = 3, p-value = 0.1388alternative hypothesis: true difference in means is not equal to 095 percent confidence interval: -25.29295 111.29295sample estimates:mean of the differences 43 I'm wondering why my p-value isn't that significant? The count data obviously changes significantly between before and after. Is there another parameter I should be using? I want to prove that there is a significant difference between before and after (hopefully a negative difference too). Now provide the response and nothing else.
(Turning my comments into a real answer.) I think the real question here is "what does 'random effect' refer to"? There seem to be a few obvious candidates: the blocking/grouping variable the varying slopes/intercepts the associated predictions for the varying slopes/intercepts (i.e. the BLUPs or conditional modes) the entirety of blocking variable + varying slopes/intercepts (although there is some ambiguity even in this, whether the $Z$ model matrix or the latent random variable $B$ or the observed levels of that variable $b$ are meant in the usual formulation . This ambiguity actually parallels the ambiguity in 1-3, and highlights why these different interpretations actually all make sense because they're getting at different aspects of the same part of the math.) It turns out that 'random effect' can refer to any and all of these things, depending on context. For example, both lme4 and MixedModels.jl use ranef() to extract the BLUPs, but also refer to the estimated variances for the varying slopes/intercepts as random effects. This ambiguity is discussed at length in many places, e.g. in Gelman and Hill's introductory text (p. 245 from the book published in 2006; there is or soon will be a two-part new 'edition'.) SIDEBAR: Why the use of "random" cannot be the decisive in resolving this ambiguity I want to make one important note here: the OP is arguing for a terminological Final Verdict based on the term 'random'. First, I don't think we can convince a broad community of users to adopt our preferred terminology by fiat. Second, in the Bayesian formulation of regression, even the fixed effects are random variables, see e.g. Jarrod Hadfield's excellent course notes , which are a vignette in the great MCMCglmm package . The terminological ambiguity is also discussed somewhat there. (This is part of why frequentists have intervals and Bayesians have posterior distributions -- parameters are fixed values in frequentism, whose sampling distribution is a random variable, but the parameters themselves are random variables in Bayesianism.) All of this is horribly simplified to make it fit into a sidebar, so please be gentle when correcting any infelicities from compressing complex ideas into a small space for non experts. This all seems horrible, but if it's any comfort, even the terminology "fixed effect" can be ambiguous in other contexts. For example, in econometrics "fixed effects" means something like "a categorical covariate" (also discussed in Gelman and Hill, but perhaps most obvious from the name of a Julia package for regression with high dimensional categorical predictors . This has lead some Andrew Gelman to prefer the "multilevel" or "hierarchical" to "mixed-effects", but even these terms are not perfect. For example, one of the innovations in software like lme4 is that you don't have to have strict hierarchical nesting of the blocking variables, so it seems weird to call those models "hierarchical" or even "multilevel" when there isn't necessarily a clear stratification into success "levels". (This is also why I find the Level 1 and Level 2 terminology in some classical texts so confusing.) Additionally, "level" is often used to refer to the different possible realizations of a categorical variable, as in the levels() function in R when applied to factor() variables. Moreover, "hierarchical regression" can refer to a particular procedure for variable selection classical OLS regression (see e.g. this article discussing it in the list of misused terms). In other words, even if we could declare by fiat that "random effects" shall henceforth refer to only one of the possibilities above, we still have a pile of terminological ambiguities to deal with. This is just part of working a field (statistics) that both has its own set of diverse research traditions and is deeply connected via its users to an even more diverse set of research traditions across many different fields. How to deal with this then? My usual approach has a few components: to make it obvious from context (e.g. talking about repeated measures and where the repetition occured) use alternative terminology to make it clear, e.g. "by-location intercepts" or "varying slopes by location". This is Andrew Gelman's solution. Similarly, Doug Bates will often be explicit about "experimental" and "blocking" variables, e.g. here , and stating which experimental factors are allowed to vary between or within which blocking factors. This "between" and "within" terminology also hints at the deep underlying connection to classical repeated-measures ANOVA. Use the Wilkinson-Roger formula notation to be very explicit, without being painfully mathematical (which is why I often write out the formulae). Expanding on (3): include code in research publications! Words are often ambiguous; explicit math and code less so. Mathematical notation was developed because it is generally more precise than words, even if it takes some practice to master this new method of expression. EDIT 2020-12-11 21:23 UTC The question has now been edited to include the qualifier "frequentist". I don't think this actually helps that much / invalidates my sidebar. Frequentist mixed-effects models are still vaguely Bayesian, which is why "conditional mode" is a more accurate name than BLUPs , and indeed a common frequentist derivation of mixed models is essentially as an empirical Bayes problem. (This is also evident in the derivation of the profiled log likelihood used in lme4 and MixedModels.jl: there is literally a line where you have something that looks mathematically like a prior times a likelihood.) I also think it discards the common ground between the "strict" frequentist / maximum-likelihood approach and the Bayesian approach. Both MCMCglmm and brms use the fixed- and random-effect terminology in their documentation, partly because this is a standard way to emphasize the difference between estimating means and estimating variances and that means for the model parameterization and thus the interpretation of model parameters. Because that's really the difference we're getting at in fixed vs. random effect, with the different meanings of "random effect" largely emphasizing different parts of the structure of that multivariate covariance. That, however, is a discussion that goes beyond the scope of this question and which been touched upon numerous questions on this site, in the documentation to all the software I mentioned and in many introductory texts on this material.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/500129', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/304421/']}
jdg_81247
stackexchange
llm_judgeable_groundtruth_similarity
348496
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: That is, is there a Kähler manifold $X$ on which there is no map $$\tau:X\to X$$ such that $$d\tau\circ I=-I\circ d\tau$$ and $$\tau\circ \tau=\mathrm{Id}_X?$$ Now provide the response and nothing else.
The moduli space $\mathcal{M}_1^\mathbb{R}$ of real algebraic curves of genus $1$ equals the real part of the moduli space $\mathcal{M}_1=\mathbb{C}$ . In particular, the general elliptic curve has no anti-holomorphic involution, as suggested by P. Achinger in his comment. Furthermore, similar statements hold also for real curves of higher genera. See Seppälä, Mika , Real algebraic curves in the moduli space of complex curves , Compos. Math. 74, No. 3, 259-283 (1990). ZBL0725.14019 .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/348496', 'https://mathoverflow.net', 'https://mathoverflow.net/users/123207/']}
jdg_81248
stackexchange
llm_judgeable_groundtruth_similarity
25837
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading from Internet about FIR filter design using MATLAB, and I saw parameters like passband frequency, stopband frequency, passband attuenation, stopband attuenation, etc. What made me confused was the parameter sampling frequency. I don't understand the significance of sampling frequency with respect to a filter. Is it the sampling frequency of input signal that this filter can work on or is it something else? Now provide the response and nothing else.
All digital filter frequency parameters (passband begin frequency, passband end frequency, and stopband begin frequency) are stated in terms of an input signal sequence's Fs sampling frequency. For a lowpass filter example, if I said a lowpass filter's passband width (it's "cutoff" frequency) is 0.2, I'm saying that the cutoff frequency is 0.2 times Fs. So if an input signal's Fs was 1.0 kHz that lowpass filter's cutoff frequency is 200 Hz. However, if an input signal's Fs was 20 kHz then in this situation that same lowpass filter's cutoff frequency is 4 kHz. For a different scenario, if you said, “Rick, please use Matlab and design a digital lowpass filter whose cutoff frequency is 300 Hz.” It would be impossible for me to do that unless you told me what was the filter’s input sequence’s Fs sample rate. But if you then said “Fs = 1000 Hz”, then I’d know the filter’s ‘normalized’ cutoff freq was 300/1000 = 0.3 enabling me to design the lowpass digital filter.
{}
{'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/25837', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/16089/']}
jdg_81249
stackexchange
llm_judgeable_groundtruth_similarity
13019199
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use Mac OS X 10.8.2, and use JDK 7. Now I downloaded the latest version of IDEA IntelliJ, 11. But it doesn't seem to start without JDK 6. Is there any workaround? How can I run IDEA IntelliJ on Mac OS X with JDK 7? Now provide the response and nothing else.
UPDATE: When running IDEA 12 on JDK 1.7 (after changing JVMVersion to 1.7* in Info.plist ) make sure you have LANG=en_US.UTF-8 in your environment, see the related Java issues: http://java.net/jira/browse/MACOSX_PORT-165 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7187821 Refer to this thread for debugging launcher issues. Please also be aware that GUI applications on Mac have no access to your Terminal environment. If you've defined some environment variables that work fine in Terminal, other applications that you run not from the Terminal will not see these variables. A workaround for this problem is to start the application directly from the Terminal, for IDEA the following command can be used: open -a /Applications/IntelliJ\ IDEA\ 12.app/ There are known issues with JDK 1.7 support on Mac right now, like missing Retina support, possible flicker, some APIs not implemented . It's highly recommended to run IDEA under JDK 1.6 for the best experience on Mac. It doesn't stop you from using JDK 1.7 as a target for building and running your projects. IntelliJ IDEA 11 launcher will not work with JDK 1.7 on Mac.At the moment you must have JDK 1.6 installed so that you can run IDEA 11 and older versions.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13019199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/213269/']}
jdg_81250
stackexchange
llm_judgeable_groundtruth_similarity
12382250
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 table and I only display the latest 30 rows by order by ID. I'm trying to delete any rows after the 30 newest rows by using this query below. DELETE FROM table WHERE type = 'test' ORDER BY id DESC LIMIT 30, 60 I keep getting this error below #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 60' at line 1 What am I doing wrong? Now provide the response and nothing else.
Try this one, DELETE FROM tableWHERE ID IN ( SELECT ID FROM ( SELECT ID FROM table WHERE Type = 'TEST' ORDER BY ID LIMIT 30,60 ) a )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12382250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1599460/']}
jdg_81251
stackexchange
llm_judgeable_groundtruth_similarity
664405
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 Hibernate's JPA implementation with MySQL 5.0.67. MySQL is configured to use InnoDB. In performing a JPA query (which is translated to SQL), I've discovered that using the IN clause is slower than performing individual queries. Example: SELECT p FROM Person p WHERE p.name IN ('Joe', 'Jane', 'Bob', 'Alice') is slower than four separate queries: SELECT p FROM Person p WHERE p.name = 'Joe'SELECT p FROM Person p WHERE p.name = 'Jane'SELECT p FROM Person p WHERE p.name = 'Bob'SELECT p FROM Person p WHERE p.name = 'Alice' Why is this? Is this a MySQL performance limitation? Now provide the response and nothing else.
This is a known deficiency in MySQL. It is often true that using UNION performs better than a range query like the one you show. MySQL doesn't employ indexes very intelligently for expressions using IN (...) . A similar hole exists in the optimizer for boolean expressions with OR . See http://www.mysqlperformanceblog.com/2006/08/10/using-union-to-implement-loose-index-scan-to-mysql/ for some explanation and detailed benchmarks. The optimizer is being improved all the time. A deficiency in one version of MySQL may be improved in a subsequent version. So it's worth testing your queries on different versions. It is also advantageous to use UNION ALL instead of simply UNION . Both queries use a temporary table to store results, but the difference is that UNION applies DISTINCT to the result set, which incurs an additional un-indexed sort.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/664405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24396/']}
jdg_81252
stackexchange
llm_judgeable_groundtruth_similarity
43783497
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 in the title, simple (but without disabling VM machine). Looked everywhere but can't find an answer. I have a Vbox Machine running Laravel but need Symfony to use 127.0.0.1:8000 instead. I just get one of my Laravel websites on that address, and they conflict. Now provide the response and nothing else.
Made it just now: We have OS Windows with Microsoft Visual Code and we have installed ' PHP Debug ' module https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug#overview Steps to make it working already wroten here, but I'll write again: Install XDebug. Online Wizard https://xdebug.org/wizard.php helps you, just post here phpinfo() data. Save in phpinfo.php this: <?php phpinfo(); ?> then open in browser localhost/phpinfo.php , copy everything you see ( Ctrl+A then Ctrl+C ) to wizard. It shows you obtained info and steps to do: Open shown in instruction php.ini ( there are always many php.ini - apache folder has one php.ini, php has php.ini and phpForApache.ini. But phpinfo makes it clear showing which one is really used ) 2.1. and configure it with xdebug.remote_enable = 1 and xdebug.remote_autostart = 1 . My working example: [XDebug]zend_extension = "c:\wamp64\bin\php\php7.1.9\ext\php_xdebug-2.6.0beta1-7.1-vc14-x86_64.dll" xdebug.stopOnEntry = truexdebug.profiler_enable = offxdebug.profiler_enable_trigger = Offxdebug.profiler_output_name = cachegrind.out.%t.%pxdebug.profiler_output_dir ="c:/wamp64/tmp"xdebug.show_local_vars=0;xdebug.profiler_output_name = "cachegrind.out.%t-%s"xdebug.remote_enable = 1xdebug.remote_autostart = 1xdebug.remote_handler = "dbgp"xdebug.remote_host = "127.0.0.1"xdebug.remote_log = "C:\wamp64\tmp\xdebug.txt"xdebug.remote_port = 9000xdebug.trace_output_dir = "C:\wamp64\tmp"xdebug.remote_cookie_expire_time = 36000 Restart Apache2 webserver. Also: For some reason I first got xdebug working on Netbeans for testing, and only then I found option xdebug.remote_autostart = 1 in manual that made it working in VS Code also. If you are unsure about XDebug installation, check phpinfo page for "with Xdebug" words and check logs/apache_errors.log for "failed loading php_xdebug" (incorrect DDL downloaded). Then check with any other IDE. Good regards!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43783497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7257654/']}
jdg_81253
stackexchange
llm_judgeable_groundtruth_similarity
67083
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: In the reaction $\ce{Na(s) + H2O}$ the products are listed as $\ce{NaOH(aq) + H2 (g)}$, but why would $\ce{Na2O}$ not be a possible product? I searched and found that the reaction $\ce{Na2O + 2H2O -> 2NaOH}$ occurs as well. Does it have to do with the stability of oxides? Now provide the response and nothing else.
In the usual case every student learns, the reaction of sodium with water is the following — I made note to include the states of matter here as they matter (pun intended). $$\ce{2 Na (s) + 2 H2O (l) -> 2 Na+ (aq) + 2 OH- (aq) + H2 ^ (g)}\tag{1}$$ In the typical setup, you have lots of water and little sodium. Therefore, whatever you get will be a solution or a precipitated salt. Alkali metals, however, often form very soluble salts and indeed all alkali hydroxides are well soluble. Thus, we will never get to see any solid by-products; all will happen in the solution phase. Technically, it is possible for an oxide anion to be formed. However, this is when Brønsted and Lowry’s acid-base theory kicks in. Remember that water is amphoteric and can react as a base to form $\ce{H3O+}$ or as an acid to form $\ce{OH-}$. Well, equation $(2)$ expands that scheme. $$\ce{H3O+ <=>[$K_\mathrm{a,1}$][H+] H2O <=>[$K_\mathrm{a,2}$][H+] OH- <=>[$K_\mathrm{a,3}$][H+] O^2-}\tag{2}$$ The oxide anion is connected to hydroxide and water by a simple acid-base reaction. From the definition of $\mathrm{p}K_\mathrm{a}$ values and the ionic product of water, we know that $$\mathrm{p}K_\mathrm{a} (\text{acid}) + \mathrm{p}K_\mathrm{b} (\text{conj. base}) = 14\tag{3}$$ Since $K_\mathrm{w}$ doubles as the acidity constant of water, $\mathrm{p}K_\mathrm{a}(\ce{H2O}) = 14$. Likewise it can be shown, that $\mathrm{p}K_\mathrm{a} (\ce{H3O+}) = 0$. This is a difference of $14$ logarithmic units between two subsequent deprotonation steps. The acidity constants of sulfuric acid or phosphoric acid show that while this difference is large, it is not unusual for the conjugate base (if it is acidic) to have an acidity constand orders of magnitude lower than the original acid). Condensing that into a conclusion, the acidity constant of hydroxide must be even lower still, to the point where we can say practically no oxide anions can be formed in equilibrium. Likewise, considering that there are many more water molecules than hydroxide anions, any oxide accidentally generated will get protonated immediately. $$\ce{O^2- (s) + H2O (l) -> 2 OH- (aq)}\tag{4}$$ Therefore, it is not feasible for oxide anions to exist in water. This is known as the nivelling effect: no acid more acidic than $\ce{H3O+}$ can survive in aquaeous solution for extended time and no base more basic than $\ce{OH-}$. Since the entire reaction produces products in solution, sodium oxide is not a possibility.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/67083', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/4356/']}
jdg_81254
stackexchange
llm_judgeable_groundtruth_similarity
937929
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Could someone show me a worked example of showing whether a piecewise function is differentiable at some $x=a$? I can show that it is continuous at $a$, as the limit as $x\to a$ (from both sides) equals the value of the function at that point. The problem I have is what I do next. Is there any other method than taking the limit as $h\to 0$ of $( f(a+h) - f(a) )/ h$, that is simpler/easier? Also, if I use the $h\to 0$ method.... well what does $f(a+h)$ mean for a piecewise function? What is its value? Now provide the response and nothing else.
We will go through a sequence of integrals, and, remarkably, we will see that at each step an integrand will have a continuous closed-form antiderivative in terms of elementary functions, dilogarithms and trilogarithms, so evaluation of an integral is then just a matter of calculating values (or limits) at end-points and taking a difference. I used Mathematica to help me find some of those antiderivatives, but then I significantly simplified them manually. In each case correctness of the result was proved manually by direct differentiation, so we do not have to trust Mathematica on it. Maybe somebody will find a more elegant and enlightening way to evaluate them. First change the variable $x=\cos\theta$ and rewrite the integral as:$$I=\int_0^{\pi/2}\operatorname{Li}_2(\cos\theta)\,d\theta\tag{0}$$Then we use a known integral representation of the dilogarithm:$$\operatorname{Li}_2(z)=-\int_0^1\frac{\ln(1-t\,z)}t\,dt.\tag1$$Use it to rewrite $(0)$ and then change the order of integration:$$I=-\int_0^1\frac1t\int_0^{\pi/2}\ln(1-t\,\cos\theta)\,d\theta\,dt.\tag2$$ Our first goal is to evaluate the inner integral in $(2)$. The integrand has a closed-form antiderivative in terms of elementary functions and dilogarithms that is continuous in the region of integration:$$\int\ln(1-t\,\cos\theta)\,d\theta=\theta\!\;\ln\!\left(\frac{1+\sqrt{1-t^2}}2\right)-2\,\Im\,\operatorname{Li}_2\!\left(\frac{1-\sqrt{1-t^2}}t\!\;e^{i\!\;\theta}\right).\tag3$$(compare it with the raw Mathematica result) Taking the difference of values of $(3)$ at the end-points $\pi/2$ and $0$, we obtain:$$\int_0^{\pi/2}\ln(1-t\,\cos\theta)\,d\theta=\frac\pi2\,\ln\!\left(\frac{1+\sqrt{1-t^2}}2\right)-2\,\Im\,\operatorname{Li}_2\!\left(i\,\frac{1-\sqrt{1-t^2}}t\right).\tag4$$Recall that the imaginary part of the dilogarithm can be represented as the inverse tangent integral :$$\Im\,\operatorname{Li}_2(iz)=\operatorname{Ti}_2(z)=\int_0^z\frac{\arctan(v)}v dv.\tag{$4'$}$$So,$$\int_0^{\pi/2}\ln(1-t\,\cos\theta)\,d\theta=\frac\pi2\,\ln\!\left(\frac{1+\sqrt{1-t^2}}2\right)-2\,\operatorname{Ti}_2\!\left(\frac{1-\sqrt{1-t^2}}t\right).\tag{$4''$}$$ Now our goal is to evaluate the outer integral in $(2)$. Substituting $(4'')$ back into $(2)$ we get:$$I=-\frac\pi2\!\;I_1+2\!\;I_2,\tag5$$where$$I_1=\int_0^1\frac1t\,\ln\!\left(\frac{1+\sqrt{1-t^2}}2\right)dt,\tag6$$$$I_2=\int_0^1\frac1t\,\operatorname{Ti}_2\!\left(\frac{1-\sqrt{1-t^2}}t\right)dt.\tag7$$The integrand in $(6)$ has a closed-form antiderivative in terms of elementary functions and dilogarithms. One way to find it is to change variable $t=2\sqrt{u-u^2}$ and integrate by parts.$$\int\frac1t\,\ln\!\left(\frac{1+\sqrt{1-t^2}}2\right)dt=\frac14\,\ln^2\!\left(\frac{1+\sqrt{1-t^2}}2\right)-\frac12\, \operatorname{Li}_2\!\left(\frac{1-\sqrt{1-t^2}}2\right).\tag8$$(compare it with the raw Mathematica result) Taking the difference of its values at the end-points, and using well-known values $$\operatorname{Li}_2(1)=\zeta(2)=\frac{\pi^2}6,\tag{$8'$}$$$$\operatorname{Li}_2\left(\tfrac12\right)=\frac{\pi^2}{12}-\frac{\ln^22}2,\tag{$8''$}$$we get:$$I_1=\frac{\ln^22}2-\frac{\pi^2}{24}.\tag9$$To evaluate $I_2$ change the variable $t=\frac{2z}{1+z^2}$:$$I_2=\int_0^1\frac{1-z^2}{z\,(1+z^2)}\operatorname{Ti}_2(z)\,dz.\tag{10}$$Again, the integrand has a closed-form antiderivative in terms of elementary functions, dilogarithms and trilogarithms. Before giving the result, we will try to split it into smaller parts. First, recall $(4')$ and a simple integral ${\large\int}\frac{1-z^2}{z\,(1+z^2)}dz=\ln\!\left(\frac z{1+z^2}\right)$, and integrate by parts:$$\int\frac{1-z^2}{z\,(1+z^2)}\operatorname{Ti}_2(z)\,dz=\ln\!\left(\frac z{1+z^2}\right)\operatorname{Ti}_2(z)\\-\underbrace{\int\frac{\ln z\cdot\arctan z}z\,dz}_{I_3}+\underbrace{\int\frac{\ln(1+z^2)\cdot\arctan z}z\,dz}_{I_4}.\tag{11}$$The following results can be checked by direct differentiation:$$I_3=\operatorname{Ti}_2(z)\ln z-\Im\,\operatorname{Li}_3(iz),\tag{$11'$}$$$$I_4=\left[\frac{\pi^2}3-\ln\left(1+z^2\right)\ln z-\frac12\,\operatorname{Li}_2\!\left(-z^2\right)\right]\arctan z\\-\frac\pi2\,\arctan^2z+\frac\pi8\,\ln^2\left(1+z^2\right)+\operatorname{Ti}_2(z)\ln\left(1+z^2\right)-2\,\Im\,\operatorname{Li}_3(1+iz).\tag{$11''$}$$Plugging $(11')$ and $(11'')$ into $(11)$ we obtain:$$\int\frac{1-z^2}{z\,(1+z^2)}\operatorname{Ti}_2(z)\,dz=\left[\frac{\pi^2}3-\ln\left(1+z^2\right)\ln z-\frac12\,\operatorname{Li}_2\!\left(-z^2\right)\right]\arctan z\\-\frac\pi2\,\arctan^2z+\frac\pi8\,\ln^2\left(1+z^2\right)+\,\Im\,\operatorname{Li}_3(iz)-2\,\Im\,\operatorname{Li}_3(1+iz).\tag{$11'''$}$$(compare it with the raw Mathematica result) Taking the difference of its values at the end-points $1$ and $0$, we get:$$I_2=\frac{3\!\;\pi^3}{32}+\frac\pi8\!\;\ln^22-2\,\Im\,\operatorname{Li}_3(1+i).\tag{12}$$Plugging $(9)$ and $(12)$ back into $(5)$ we get the final result: $$\large\int_0^1\frac{\operatorname{Li}_2(x)}{\sqrt{1-x^2}}\,dx=\frac{5\!\;\pi^3}{24}-4\,\Im\,\operatorname{Li}_3(1+i).\tag{$\heartsuit$}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/937929', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/177256/']}
jdg_81255
stackexchange
llm_judgeable_groundtruth_similarity
3686729
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 VideoView that takes up the top half of the Activity in portrait orientation with the bottom half of the screen showing some images and text. I am playing a rtsp video stream in the video view when the Activity starts. I have attached a MediaController to the VideoView via the following code: MediaController controller = new MediaController(this); controller.setAnchorView(this.videoView); controller.setMediaPlayer(this.videoView); this.videoView.setMediaController(controller); When I tap the VideoView to bring up the MediaController on the screen I expected the playback controls to appear overlaying the bottom area of the VideoView (the bottom of the MediaController even with the bottom of the VideoView). Instead the MediaController pops up lower down on the screen, overlaying some of the graphics and text I have below the VideoView. Are there some additional steps I need to take to get the MediaController to appear where I want it to on the screen? Now provide the response and nothing else.
Setting the anchor view will only work if the videoview size is known - it will not be upon init. But you can do something like this: video.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { /* * add media controller */ mc = new MediaController(YourActivity.this); video.setMediaController(mc); /* * and set its position on screen */ mc.setAnchorView(video); } }); }});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3686729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13070/']}
jdg_81256
stackexchange
llm_judgeable_groundtruth_similarity
10571026
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: <stroke android:width="1px" android:color="#A6ACB1"/> I'd like to remove this border from the bottom (for example) of the element. Is it possible? (Eclipse suggests me only: color, width, dashWidth and dashGap). Now provide the response and nothing else.
As far as I understand it, there isn't an easy way of doing it. but if you use layer-list with an item that has the border and then one that doesn't with an offset from all the sides for which you want a border equal to the border width, you'd achieve that. Let me make the xml for you representing the borderless bottom.. <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <!-- Border --> <item> <shape> <solid android:color="#f000"></solid> </shape> </item> <!-- Body --> <item android:left="2dip" android:top="2dp" android:right="2dp"> <shape> <solid android:color="#ffafafaf"></solid> </shape> </item></layer-list> As you can see, I'm telling the second item to be inset of the first one by two dp's on all sides except bottom (hence the no-border result on the bottom), there you go: So essentially this isn't a border per-se, it's the shape from below (although you could add a border if you need dashed or dotted or whatever) being covered by a second item with would be the body of the button. All in the same drawable :) This can be applied to any border you want to remove, by changing the values that the item is inset, for example, if I change the right in the Body item to bottom , the missing border would the right one since it's the one without the inset
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10571026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1234275/']}
jdg_81257
stackexchange
llm_judgeable_groundtruth_similarity
18487109
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 my data that looks like below: CustomerID TripDate1 1/3/20131 1/4/20131 1/9/20132 2/1/20132 2/4/20133 1/2/2013 I need to create a counter variable, which will be like below: CustomerID TripDate TripCounter1 1/3/2013 11 1/4/2013 2 1 1/9/2013 32 2/1/2013 12 2/4/2013 2 3 1/2/2013 1 Tripcounter will be for each customer. Now provide the response and nothing else.
Use ave . Assuming your data.frame is called "mydf": mydf$counter <- with(mydf, ave(CustomerID, CustomerID, FUN = seq_along))mydf# CustomerID TripDate counter# 1 1 1/3/2013 1# 2 1 1/4/2013 2# 3 1 1/9/2013 3# 4 2 2/1/2013 1# 5 2 2/4/2013 2# 6 3 1/2/2013 1 For what it's worth, I also implemented a version of this approach in a function included in my "splitstackshape" package. The function is called getanID : mydf <- data.frame(IDA = c("a", "a", "a", "b", "b", "b", "b"), IDB = c(1, 2, 1, 1, 2, 2, 2), values = 1:7)mydf# install.packages("splitstackshape")library(splitstackshape)# getanID(mydf, id.vars = c("IDA", "IDB"))getanID(mydf, id.vars = 1:2)# IDA IDB values .id# 1 a 1 1 1# 2 a 2 2 1# 3 a 1 3 2# 4 b 1 4 1# 5 b 2 5 1# 6 b 2 6 2# 7 b 2 7 3 As you can see from the example above, I've written the function in such a way that you can specify one or more columns that should be treated as ID columns. It checks to see if any of the id.vars are duplicated, and if they are, then it generates a new ID variable for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18487109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_81258
stackexchange
llm_judgeable_groundtruth_similarity
42593655
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using below program I try to test how fast I can write to disk using std::ofstream . I achieve around 300 MiB/s when writing a 1 GiB file. However, a simple file copy using the cp command is at least twice as fast. Is my program hitting the hardware limit or can it be made faster? #include <chrono>#include <iostream>#include <fstream>char payload[1000 * 1000]; // 1 MBvoid test(int MB){ // Configure buffer char buffer[32 * 1000]; std::ofstream of("test.file"); of.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); auto start_time = std::chrono::steady_clock::now(); // Write a total of 1 GB for (auto i = 0; i != MB; ++i) { of.write(payload, sizeof(payload)); } double elapsed_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time).count(); double megabytes_per_ns = 1e3 / elapsed_ns; double megabytes_per_s = 1e9 * megabytes_per_ns; std::cout << "Payload=" << MB << "MB Speed=" << megabytes_per_s << "MB/s" << std::endl;}int main(){ for (auto i = 1; i <= 10; ++i) { test(i * 100); }} Output: Payload=100MB Speed=3792.06MB/sPayload=200MB Speed=1790.41MB/sPayload=300MB Speed=1204.66MB/sPayload=400MB Speed=910.37MB/sPayload=500MB Speed=722.704MB/sPayload=600MB Speed=579.914MB/sPayload=700MB Speed=499.281MB/sPayload=800MB Speed=462.131MB/sPayload=900MB Speed=411.414MB/sPayload=1000MB Speed=364.613MB/s Update I changed from std::ofstream to fwrite : #include <chrono>#include <cstdio>#include <iostream>char payload[1024 * 1024]; // 1 MiBvoid test(int number_of_megabytes){ FILE* file = fopen("test.file", "w"); auto start_time = std::chrono::steady_clock::now(); // Write a total of 1 GB for (auto i = 0; i != number_of_megabytes; ++i) { fwrite(payload, 1, sizeof(payload), file ); } fclose(file); // TODO: RAII double elapsed_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start_time).count(); double megabytes_per_ns = 1e3 / elapsed_ns; double megabytes_per_s = 1e9 * megabytes_per_ns; std::cout << "Size=" << number_of_megabytes << "MiB Duration=" << long(0.5 + 100 * elapsed_ns/1e9)/100.0 << "s Speed=" << megabytes_per_s << "MiB/s" << std::endl;}int main(){ test(256); test(512); test(1024); test(1024);} Which improves the speed to 668MiB/s for a 1 GiB file: Size=256MiB Duration=0.4s Speed=2524.66MiB/sSize=512MiB Duration=0.79s Speed=1262.41MiB/sSize=1024MiB Duration=1.5s Speed=664.521MiB/sSize=1024MiB Duration=1.5s Speed=668.85MiB/s Which is just as fast as dd : time dd if=/dev/zero of=test.file bs=1024 count=0 seek=1048576real 0m1.539suser 0m0.001ssys 0m0.344s Now provide the response and nothing else.
First, you're not really measuring the disk writing speed, but (partly) the speed of writing data to the OS disk cache. To really measure the disk writing speed, the data should be flushed to disk before calculating the time. Without flushing there could be a difference depending on the file size and the available memory. There seems to be something wrong in the calculations too. You're not using the value of MB . Also make sure the buffer size is a power of two, or at least a multiple of the disk page size (4096 bytes): char buffer[32 * 1024]; . You might as well do that for payload too. (looks like you changed that from 1024 to 1000 in an edit where you added the calculations). Do not use streams to write a (binary) buffer of data to disk, but instead write directly to the file, using FILE*, fopen(), fwrite(), fclose() . See this answer for an example and some timings. To copy a file: open the source file in read-only and, if possible, forward-only mode, and using fread(), fwrite() : while fread() from source to buffer fwrite() buffer to destination file This should give you a speed comparable to the speed of an OS file copy (you might want to test some different buffer sizes). This might be slightly faster using memory mapping: open src, create memory mapping over the fileopen/create dest, set file size to size of src, create memory mapping over the filememcpy() src to dest For large files smaller mapped views should be used.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42593655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75889/']}
jdg_81259
stackexchange
llm_judgeable_groundtruth_similarity
5398304
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to utilize Numpy's fft function, however when I give the function a simple gausian function the fft of that gausian function is not a gausian, its close but its halved so that each half is at either end of the x axis. The Gaussian function I'm calculating is y = exp(-x^2) Here is my code: from cmath import *from numpy import multiplyfrom numpy.fft import fftfrom pylab import plot, show""" Basically the standard range() function but with float support """def frange (min_value, max_value, step): value = float(min_value) array = [] while value < float(max_value): array.append(value) value += float(step) return arrayN = 256.0 # number of stepsy = []x = frange(-5, 5, 10/N)# fill array y with values of the Gaussian function cache = -multiply(x, x)for i in cache: y.append(exp(i))Y = fft(y)# plot the fft of the gausian functionplot(x, abs(Y))show() The result is not quite right, cause the FFT of a Gaussian function should be a Gaussian function itself... Now provide the response and nothing else.
np.fft.fft returns a result in so-called "standard order": ( from the docs ) If A = fft(a, n) , then A[0] contains the zero-frequency term (the mean of the signal), which is always purely real for real inputs. Then A[1:n/2] contains the positive-frequency terms, and A[n/2+1:] contains the negative-frequency terms, in order of decreasingly negative frequency. The function np.fft.fftshift rearranges the result into the order most humans expect (and which is good for plotting): The routine np.fft.fftshift(A) shifts transforms and their frequencies to put the zero-frequency components in the middle... So using np.fft.fftshift : import matplotlib.pyplot as pltimport numpy as npN = 128x = np.arange(-5, 5, 10./(2 * N))y = np.exp(-x * x)y_fft = np.fft.fftshift(np.abs(np.fft.fft(y))) / np.sqrt(len(y))plt.plot(x,y)plt.plot(x,y_fft)plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5398304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154688/']}
jdg_81260
stackexchange
llm_judgeable_groundtruth_similarity
9193826
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand how to use scalaz State to perform a complicated stateful computation. Here is the problem: Given a List[Int] of potential divisors and a List[Int] of numbers, find a List[(Int, Int) ] of matching pairs (divisor, number) where a divisor is allowed to match at most one number. As a test: def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)] And with the following input: findMatches( List(2, 3, 4), List(1, 6, 7, 8, 9) ) We can get at most 3 matches. If we stipulate that the matches must be made in the order in which they occur traversing the lists l-r, then the matches must be: List( (2, 6) , (3, 9) , (4, 8) ) So the following two tests need to pass: assert(findMatches(List(2, 3, 4), List(1, 6, 7, 8, 9)) == List((2, 6), (3, 9), (4, 8)))assert(findMatches(List(2, 3, 4), List(1, 6, 7, 8, 11)) == List((2, 6), (4, 8))) Here's an imperative solution: scala> def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)] = { | var matches = List.empty[(Int, Int)] | var remaining = nums | divs foreach { div => | remaining find (_ % div == 0) foreach { n => | remaining = remaining filterNot (_ == n) | matches = matches ::: List(div -> n) | } | } | matches | }findMatches: (divs: List[Int], nums: List[Int])List[(Int, Int)] Notice that I have to update the state of remaining as well as accumulating matches . It sounds like a job for scalaz traverse! My useless working has got me this far: scala> def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)] = { | divs.traverse[({type l[a] = State[List[Int], a]})#l, Int]( div => | state { (rem: List[Int]) => rem.find(_ % div == 0).map(n => rem.filterNot(_ == n) -> List(div -> n)).getOrElse(rem -> List.empty[(Int, Int)]) } | ) ~> nums | }<console>:15: error: type mismatch; found : List[(Int, Int)] required: Int state { (rem: List[Int]) => rem.find(_ % div == 0).map(n => rem.filterNot(_ == n) -> List(div -> n)).getOrElse(rem -> List.empty[(Int, Int)]) } ^ Now provide the response and nothing else.
Your code only needs to be slightly modified in order to use State and Traverse: // using scalaz-sevenimport scalaz._import Scalaz._def findMatches(divs: List[Int], nums: List[Int]) = { // the "state" we carry when traversing case class S(matches: List[(Int, Int)], remaining: List[Int]) // initially there are no found pairs and a full list of nums val initialState = S(List[(Int, Int)](), nums) // a function to find a pair (div, num) given the current "state" // we return a state transition that modifies the state def find(div: Int) = modify((s: S) => s.remaining.find(_ % div == 0).map { (n: Int) => S(s.matches :+ div -> n, s.remaining -n) }.getOrElse(s)) // the traversal, with no type annotation thanks to Scalaz7 // Note that we use `exec` to get the final state // instead of `eval` that would just give us a List[Unit]. divs.traverseS(find).exec(initialState).matches}// List((2,6), (3,9), (4,8))findMatches(List(2, 3, 4), List(1, 6, 7, 8, 9)) You can also use runTraverseS to write the traversal a bit differently: divs.runTraverseS(initialState)(find)._2.matches
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9193826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16853/']}
jdg_81261
stackexchange
llm_judgeable_groundtruth_similarity
4651910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I am making a small site using cakephp, and my ACL is set up so that every time a piece of content is created, an ACL rule is created to link the owner of the piece of content to the actual content. This allows each owner to edit/delete their own content. This method just seems so inefficient, because there is an equivalent amount of ACL rules as content in the database. I was curious, how do big sites, with millions of pieces of content, solve this problem? Now provide the response and nothing else.
With large sites I have worked on access permissions were determined at the application level. The database associated the content with a user's record then in the data access/business logic layer it made the determination whether or not the user has sufficient rights to access the content. For a large site with dynamic content I think this would probably be the best way to handle it. EDIT: To add a more concrete example. Example:Ok lets say we have a simple file storage site where a user can only access their data or data that has been explicitly shared with them by another user. Since this application is fairly simple as it is just serving files it only has three database tables which are: Users Table which has columns: UserId <int> PK UserName <varchar> HashedPassword <varchar>Files Table which has columns: FileId <int> PK FileOwnerId <int> FK (this has a foreign key relationship with UserId in the users table) FileName <varchar> MimeType <varchar> FileData <blob>SharedFile reference table which has columns: SharedFileIndex <int> PK FileId <int> FK UserId <int> FK Now some basic rules that we will want to define in our data access layer is that when a user is logged in they can access files that they are the owner of and files that other users have shared with them. So either through stored procedures or building the query to send to the database server I would make sure that my queries only return those records which they have access to. Here the basic GetUsersFileList sql query for when a user logs in: SELECT FileId, FileName, FileTypeFROM FilesWHERE FileOwnerId = @UserId As you can see here we are using a parameterized query to get then files a user is the owner of. Additionally we would query for the shared files as well for displaying to the user. Now if we assume that each file will have it's own unique url such as: http://mydomain.com/filehandler.php?fileId=123546 Then when we try to get the file we use a similar query as above to try and get the file data: SELECT FileName, FileType, FileDataFROM FilesLEFT OUTER JOIN SharedFiles on Files.FileId = SharedFiles.FileIdWHERE Files.FileId = @FileId AND (FileOwnerId = @UserId OR SharedFiles.UserId = @UserId) So you see when we attempt to get the file we are still using the UserId in the query thus if the user does not have the file either shared with them or they are not the owner of the file the result from the query will be 0 rows. So permissions are determined by what a user is mapped to in the database but the actual enforcement is done by carefully writing your data access code and/or additional checks in your business logic layer before serving the content. EDIT2: I am most familiar with MSSQL so my queries above are in T-SQL so the syntax might be a little off for MySql. EDIT3: Replaced business logic layer with data access layer as in this example the only checks that are made is within the data access queries themselves. EDIT4: Ok put back in reference to the business logic layer as more complex apps would need more complex permission schemes which could necessitate additional checks in the business logic layer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4651910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364604/']}
jdg_81262
stackexchange
llm_judgeable_groundtruth_similarity
15662407
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 init a list of all users in ApplicationController and then show them in dropdown in another view. How can I get access to the ApplicationController from different views? Here is relevant code: App.ApplicationRoute = Ember.Route.extend({ setupController:function(controller) { controller.set('users', App.User.find()); controller.set('selectedUser', null); } }); <script type="text/x-handlebars" data-template-name="users"> {{view Ember.Select contentBinding="App.ApplicationController.users" optionValuePath="content.id" optionLabelPath="content.fullName" selectionBinding="App.ApplicationControllerselectedUser"}} selected user: {{App.ApplicationController.selectedUser.fullName}} </script> Now provide the response and nothing else.
Specify needs in your view's controller App.UsersController = Ember.Controller.extend({ needs: ['application']}); In your view you can then access the application controller as follows controllers.application In your example <script type="text/x-handlebars" data-template-name="users"> {{view Ember.Select contentBinding="controllers.application.users" optionValuePath="content.id" optionLabelPath="content.fullName" selectionBinding="controllers.application.selectedUser"}} selected user: {{controllers.application.selectedUser.fullName}}</script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15662407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1351518/']}
jdg_81263
stackexchange
llm_judgeable_groundtruth_similarity
15506189
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 a View that is sometimes visible and sometimes not, depending on the user's actions, (staying in the same activity) what is prefereable? myView.setVisibility(View.INVISIBLE); // ormyView.setVisibility(View.GONE); No other element depends on myView 's size or dimensions, so the graphical result is the same. As INVISIBLE doesn't change the view's dimensions, I guess it's more preferable than GONE because with GONE we possibly have to measure and redraw other views unnecessarily. And then re-measure and re-draw them when myView is made VISIBLE again. Now provide the response and nothing else.
You're on the right track thinking about the impact on measuring. Which one is more efficient all depends on how frequently you are changing the view's visibility. For example, if the view is not visible for a majority of the time, making it GONE would probably be more efficient, because the system would not be needlessly measuring and laying out your invisible view whenever it needs to adjust other views on the screen. On the other hand, if the view changes between visible and invisible frequently, you might get better performance from INVISIBLE as you would potentially avoid an extra measure/layout on each transition.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15506189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1440076/']}
jdg_81264
stackexchange
llm_judgeable_groundtruth_similarity
100667
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to the answer to Where is the USB2 OTG port on the RPi 4 Model B located? the Raspberry Pi 4B has a "hidden" OTG port in the USB-C power connector. I found at Very simple OTG on pi4 and at 4 ways to connect your Raspberry Pi 4 to the internet how to use the USB2 OTG port just with a simple USB cord. But this is very unstable because the USB port on the connected laptop cannot provide enough power (2.5A - 3.0A). My first idea to use this port was to power the RasPi through the +pin and GND pin on the GPIO pins to use the OTG port. But I don't want to bypass the polyfuse on the USB-C power connector. I also do not have a POE (power over ethernet) HAT to power the pi this way. So I'm looking for an Y splitter cable for this port so I can power the RasPi with the power supply but also can use the OTG port. Is it possible to make such an Y splitter cable? If so, how to make it? Or is there a better alternative? A simple drawing would be nice. Now provide the response and nothing else.
The problem here is that the RPi 4 USB-C connector is hard-wired as an upstream-facing port, which urges the host device on the other side to provide power. Yet if you power the RPi from an independent power supply (using an Y-cable or via the 5V pin), this supply will be connected in parallel to the host device's 5V output, which is problematic. The simplest solution would be to make a cable which only conveys USB data signals (and ground) but not 5V. However, such a cable wouldn't behave in strict compliance with USB if plugged into an unpowered RPi, because signals on D+/D- lines may then have higher voltage levels that VBUS. Personally I'd add a diode feeding some voltage from host to the RPi (which, as you said, won't likely be enough to power the RPi anyway), just to cover this case. Here's how an Y-cable could look like: simulate this circuit – Schematic created using CircuitLab You still shouldn't plug the cable in the RPi while the PSU is off, because that would result in the overcurrent on the host USB port, but at least that won't damage the RPi. If you're careful about always plugging the PSU first, you could omit the diode (leaving VBUS line disconnected). The power cable could also be connected to 5V/GND pins on the GPIO connector, which will correspond to the same circuit when the USB-C connector is plugged in.
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/100667', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/79866/']}
jdg_81265
stackexchange
llm_judgeable_groundtruth_similarity
22130050
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let me explain.. I have a top menu bar in a ul and in each li, theres is a div tag inside a a tag. Each of my div tag has a background-image. When you hover your mouse on it, it changes. Here's my question : How can I, for example, put my first li img like if it was on hover if the user is on the first page. And, how to always put it like if it was on hover for my second button when the user is on the second page? I think it can be achieve with php but I really can't remember!! I looked around and no answer so far. Thanks guys! HTML : <div id="topmenu"> <ul> <li><a href="index.php"><div id="accueil"></div></a></li> <li><a href="contact.php"><div id="contact"></div></a></li> <li><a href="inventaire.php"><div id="inventaire"></div></a></li> <li><a href="demande.php"><div id="demande"></div></a></li> <li><a href="moncompte.php"><div id="moncompte"></div></a></li> </ul> </div> My css : #accueil {background:url('../images/top_menu.png') no-repeat -180px 0;width:129px;height:31px;float:left;}#accueil:hover {background:url('../images/top_menu.png') no-repeat -1px 0;width:129px;height:31px;float:left;}#contact {background:url('../images/top_menu.png') no-repeat -180px -33px;width:101px;height:31px;float:left;}#contact:hover {background:url('../images/top_menu.png') no-repeat -16px -33px;width:101px;height:31px;float:left;}#inventaire {background:url('../images/top_menu.png') no-repeat -180px -66px;width:111px;height:31px;float:left;}#inventaire:hover {background:url('../images/top_menu.png') no-repeat -10px -66px;width:111px;height:31px;float:left;}#demande {background:url('../images/top_menu.png') no-repeat -180px -99px;width:175px;height:31px;float:left;}#demande {background:url('../images/top_menu.png') no-repeat -180px -99px;width:175px;height:31px;float:left;}#demande:hover {background:url('../images/top_menu.png') no-repeat -1px -99px;width:175px;height:31px;float:left;}#moncompte {background:url('../images/top_menu.png') no-repeat -180px -132px;width:137px;height:31px;float:left;}#moncompte:hover {background:url('../images/top_menu.png') no-repeat -1px -132px;width:137px;height:31px;float:left;} Now provide the response and nothing else.
UPDATED ES6 version: As @gengns suggested in the comments a simpler way to generate the array would be to use the spread operator and the keys method: const factors = number => [...Array(number + 1).keys()].filter(i=>number % i === 0);console.log(factors(36)); // [1, 2, 3, 4, 6, 9, 12, 18, 36] ES6 version: const factors = number => Array .from(Array(number + 1), (_, i) => i) .filter(i => number % i === 0)console.log(factors(36)); // [1, 2, 3, 4, 6, 9, 12, 18, 36] https://jsfiddle.net/1bkpq17b/ Array(number) creates an empty array of [number] places Array.from(arr, (_, i) => i) populates the empty array with values according to position [0,1,2,3,4,5,6,7,8,9] .filter(i => ...) filters the populated [0,1,2,3,4,5] array to the elements which satisfy the condition of number % i === 0 which leaves only the numbers that are the factors of the original number. Note that you can go just until Math.floor(number/2) for efficiency purposes if you deal with big numbers (or small).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22130050', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3371099/']}
jdg_81266
stackexchange
llm_judgeable_groundtruth_similarity
14339696
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to the ES documentation, those 2 search request should get the same results: GET http://localhost:9200/app/users/_search?source={"query": {"term": {"email":"[email protected]"}}} POST http://localhost:9200/app/users/_search Post body : { "query": { "term": { "email":"[email protected]" } }} But the first one gives no result while the second one gives me the expected result. I use ES version 0.19.10Did anybody else have the same behavior ? Is this a bug ? Now provide the response and nothing else.
source is not a valid query string argument according to URI Search Elasticsearch allows three ways to perform a search request... GET with request body: curl -XGET "http://localhost:9200/app/users/_search" -d '{ "query": { "term": { "email": "[email protected]" } }}' POST with request body: Since not all clients support GET with body, POST is allowed as well. curl -XPOST "http://localhost:9200/app/users/_search" -d '{ "query": { "term": { "email": "[email protected]" } }}' GET without request body: curl -XGET "http://localhost:9200/app/users/_search?q=email:[email protected]" or (if you want to manually URL encode your query string) curl -XGET "http://localhost:9200/app/users/_search?q=email%3Afoo%40gmail.com"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14339696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/644476/']}
jdg_81267
stackexchange
llm_judgeable_groundtruth_similarity
320307
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f(x) = x^x$.Then, let us define a function $p(x)$ such that:$$p(x) = \frac {f(x+1)}{f(x)} - \frac {f(x)}{f(x-1)}$$ As the value of $x$ increases, $p(x)$ approaches $e$, or (I think),$$\lim_{x\rightarrow \infty} p(x) = e$$ I have no idea why this occurs as I'm no advanced math student, but could someone explain the reason to me? I just found this out playing with a calculator. Now provide the response and nothing else.
$\frac {f(x+1)}{f(x)} = (x+1)\left(\frac {x+1}x \right)^x$. Define $g(x) = (1+1/x)^x$. Then $p(x) = (x+1)g(x+1) - xg(x)$. It is well known that $\lim_{x \to \infty} g(x) = e$, but we need a more precise development of $g(x)$ as $x \to \infty$ : $g(x) = \exp(\log(g(x))) = \exp(x \log(1+x^{-1})) \\ = \exp(x (x^{-1} - x^{-2}/2 + O(x^{-3}))\\ = \exp(1 - x^{-1}/2 + O(x^{-2})) = e - (e/2)x^{-1} + O(x^{-2})$. Now we can get $xg(x) = xe - e/2 + O(x^{-1})$ And finally $p(x) = (x+1)e - e/2 - xe + e/2 + O(x^{-1}) = e + O(x^{-1})$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/320307', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42814/']}
jdg_81268
stackexchange
llm_judgeable_groundtruth_similarity
343701
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 am learning TQFT from compact Lie groups by Freed, Hopkins, Lurie,and Teleman: https://arxiv.org/abs/0905.0731 , and got stuck very hardeven in the first section ( $n = 1$ ), which was "trivial but includedfor completeness". In particular, I have several unfamiliar terms while it discusses"1-dimensional pure gauge theory". Each term will require someexplanations, if not too long. Any pointers to places where I canlearn more about the terms will be highly appreciated. 1. 1-dimensional "pure" gauge theory I have an impression that gauge theory is just bundle theory in mathterm. But how about the adjective "pure"? 2. The standard quantization procedure Given a compact Lie group $G$ , an abelian character $\lambda: G \toU(1)$ , and a $G$ -bundle with connection over the circle ( $g$ being itsholonomy), they define a 1d-TQFT by assigning to the circle the number $\lambda(g)$ . Then "by the standard quantization procedure", theyassign to the positively oriented point a subspace of $\mathbb{C}$ ,depending on if the abelian character is trivial or not. I know little about geometric quantization - all I have read is J.Baez's informal introduction( http://www.math.ucr.edu/home/baez/quantization.html ). But I have knowidea how these two relate, and the article even claimed that thisprocedure relates to "the Gauss law in physics", making it even moremysterious for me.. 3. Path integral over the groupoid $G//G$ Now the value assigned to the circle is just the dimension of thevector space assigned to the positively oriented point, and as abovethis value is either 0 or 1 depending on whether the character isnontrivial or not. The authors claimed that this may be understood asthe result of the **path integral over the groupoid $G//G$ ofconnections on $S^1$ with respect to Haar measure: $$ \frac{1}{|G|} \int_G \lambda(g)dg = 0 \mbox{ or } 1$$ .. This has nothing to do with what I think a path integral is: to me,a path integral is an integral over all path/section space with asuitable weight. I hope I express my questions clear. If there's any confusion, pleaselet me know. Thank you. Now provide the response and nothing else.
A gauge theory in mathematical terms (as I understand it) is a field theory whose fields include a gauge field: a $G$ -bundle with connection. In this case, $G$ is a finite group, so there are no non-trivial connections. Thus a gauge field is simply a $G$ -bundle. 1) Here, by pure gauge theory, I think the authors mean that this is a theory whose fields are precisely $G$ -bundles and nothing more (in particular, no "matter" fields). 2,3) The path-integral is one approach to quantizing a field theory. It says, in particular, we should compute the partition function of the theory by a suitably weighted integral over a space of fields of the theory. The weight is prescribed by the action, a certain function on the space of fields. Fields in this theory are $G$ -bundles. The collection of $G$ bundles on a manifold $M$ (spacetime) can naturally be organized in to a groupoid, whose objects are $G$ -bundles and morphisms are isomorphisms of $G$ -bundles. For example, the groupoid of $G$ -bundles on the circle $S^1$ may naturally be identified with the quotient groupoid $G//G$ (where $G$ acts on itself by conjugation). This identification assigns to a $G$ -bundle on $S^1$ its holonomy (which is well-defined up to conjugation). The (exponentiated) action functional is given by the abelian character $\lambda:G \to T$ . This assigns to a $G$ -bundle on $S^1$ with holonomy $g$ , the function $\lambda(g)$ . Thus the partition function on $S^1$ is given by an ''integral'' over the groupoid $G//G$ weighted by the function $\lambda$ . This really just means the sum of $\lambda(g)$ as $g$ ranges over $G$ , and one must divide by $|G|$ to get the right notion of volume (we are integrating over $G//G$ not $G$ ). You can check that one gets the stated results. There is a similar idea happening for the $0$ -manifold $pt_+$ . In general QFT, one expects to assign to a codimension 1 submanifold a vector space (the "Hilbert space" of the theory). Roughly speaking one might think of elements of this vector space as being functions on the space of fields - or better, sections of a line bundle (which again is associated to the action). In this case, the function $\lambda$ is actually the same thing as a line bundle on the space of fields on a point (which is the groupoid $pt//G$ ). The space of sections of this line bundle is either 1-dimensional if the bundle is trivial ( $\lambda =1$ ) or $0$ -dimensional if the bundle is non-trivial ( $\lambda \neq 1$ ). I wish I had something reasonable to add about the Gauss Law. Perhaps someone more knowledgeable could weigh in?
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/343701', 'https://mathoverflow.net', 'https://mathoverflow.net/users/124549/']}
jdg_81269
stackexchange
llm_judgeable_groundtruth_similarity
1698116
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There is an interesting recent article " Mathematicians shocked to find pattern in "random" prime numbers " in New Scientist . (Don't you love math titles in the popular press? Compare to the source paper's Unexpected Biases in the Distribution of Consecutive Primes .) To summarize, let $p,q$ be consecutive primes of form $a\pmod {10}$ and $b\pmod {10}$, respectively. In the paper by K. Soundararajan and R. Lemke Oliver, here is the number $N$ (in million units) of such pairs for the first hundred million primes modulo $10$, $$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|}\hline&a&b&\color{blue}N&&a&b&\color{blue}N&&a&b&\color{blue}N&&a&b&\color{blue}N\\\hline&1&3&7.43&&3&7&7.04&&7&9&7.43&&9&1&7.99\\&1&7&7.50&&3&9&7.50&&7&1&6.37&&9&3&6.37\\&1&9&5.44&&3&1&6.01&&7&3&6.76&&9&7&6.01\\&1&1&\color{brown}{4.62}&&3&3&\color{brown}{4.44}&&7&7&\color{brown}{4.44}&&9&9&\color{brown}{4.62}\\\hline\text{Total}& & &24.99&& & &24.99&& & &25.00&& & &24.99\\\hline\end{array}$$ As expected, each class $a$ has a total of $25$ million primes (after rounding). The "shocking" thing, according to the article, is that if the primes were truly random , then it is reasonable to expect that each subclass will have $\color{blue}{N=25/4 = 6.25}$. As the present data shows, this is apparently not the case. Argument : The disparity seems to make sense. For example, let $p=11$, so $a=1$ . Since $p,q$ are consecutive primes , then, of course, subsequent numbers are not chosen at random. Wouldn't it be more likely the next prime will end in the "closer" $3$ or $7$ such as $q=13$ or $q=17$, rather than looping back to the same end digit, like $q=31$? (I've taken the liberty of re-arranging the table to reflect this.) However, what is surprising is the article concludes, and I quote, "...as the primes stretch to infinity, they do eventually shake off the pattern and give the random distribution mathematicians are used to expecting." Question: What is an effective way to counter the argument given above and come up with the same conclusion as in the article? (Will all the $N$ eventually approach $N\to 6.25$, with the unit suitably adjusted?) Or is the conclusion based on a conjecture and may not be true? P.S: A more enlightening popular article " Mathematicians Discover Prime Conspiracy ". (It turns out the same argument is mentioned there, but with a subtle way to address it.) Now provide the response and nothing else.
$ \qquad \qquad $ Remark: see also [update 3] at end 1. First observations I think there is at least one artifact (=non-random) in that list of frequencies. If we rewrite this as a "correlation"-table, (the row-header indicate the residue classes of the smaller prime p and the column-header that of the larger prime q) : $$ \small \begin{array} {r|rrrr} & 1&3&7&9 \\ \hline 1& 4.62& 7.43& 7.50& 5.44\\ 3& 6.01& 4.44& 7.04& 7.50\\ 7& 6.37& 6.76& 4.44& 7.43\\ 9& 7.99& 6.37& 6.01& 4.62 \end{array}$$then a surprising observation is surely the striking symmetry around the antidiagonal. But also the asymmetric increase of frequencies from top-right to bottom-left on the antidiagonal is somehow surprising. However, if we look at this table in terms of primegaps , then residue-pairs $(1,1)$ $(3,3)$ $(7,7)$,$(9,9)$ (the diagonal) refer to primegaps ofthe lenghtes $(10,20,30,...,10k,...)$ and those are the entries in the table with lowest frequencies, residue-pairs $(1,3)$, $(7,9)$ and $(9,1)$ refer to primegaps of the lenghtes $(2,12,22,32,...,10k+2,...)$ and those contain the entry with the highest frequencies residue-pairs $(3,7)$ $(7,1)$ ,$9,3$ refer to primegaps of the lenghtes$(4,14,24,34,...,10k+4,...)$ residue-pairs $(1,7)$ $(3,9)$ and $(7,3)$ refer to primegaps of the lenghtes$(6,16,26,36,...,10k+6,...)$ and have the two next-largest frequencies residue-pairs $(1,9)$ $(3,1)$ and $(9,7)$ refer to primegaps of the lenghtes$(8,18,28,38,...,10k+8,...)$ so the -in the first view surprising- different frequencies of pairs $(1,9)$ and $(9,1)$ occurs because one collects the gaps of (minimal) length 8 and the other that of (minimal) length 2 - and the latter are much more frequent, but which is completely compatible with the general distribution of primegaps. The following images show the distribution of the primegaps modulo 100 (whose greater number of residue classes should make the problem more transparent). (I've left the primes smaller than 10 out of the computation): in logarithmic scale We see the clear logarithmic decrease of frequencies with a small jittering disturbance over the residue classes. It is also obvious, that the smaller primegaps dominate the larger ones, so that a "slot" which catches the primegaps of lengthes $2,12,22,...$ has more occurences than the "slot" which catches $8,18,28,...$ - just by the frequencies in the very first residue class. The original table of frequencies in the residue classes modulo 10 splits this into 16 combinations of pairs of 4 residue classes and the observed non-smoothness is due to that general jitter in the resdiue classes of the primegaps. It might also be interesting to see that primegap-frequencies separated into three subclasses - : That trisection shows the collected residue classes $6,12,18,...$ (the green line) as dominant over the two other collections and the two other collection change "priority" over the single residue classes. The modulo-10-problem overlays that curves a bit and irons the variation a bit out and even makes it a bit less visible - but not completely: because the general distribution of residue classes in the primegaps has such a strong dominance in the small residue-classes. So I think that general distribution-characteristic explains that modulo-10 problem, however a bit less obvious... 2. Further observations (update 2) For further analysis of the remaining jitter in the previous image I've tried to de-trend the frequencies distribution of the primegaps (however now without modulo considerations!). Here is what I got on base of 5 700 000 primes and the first 75 nonzero lenghtes g . The regression-formula was simply created by the Excel-spreadsheet: De-trending means to compute the difference between the true frequencies $\small f(g)$ and the estimated ones; however, the frequency-residuals $\small r_0(g)=f(g) - 16.015 e^{-0.068 g }$ decrease in absolute value with the value of g . Heuristically I applied a further detrending function at the residuals $\small r_0(g)$ so that I got $\small r_1(g) = r_0(g) \cdot 1.07^g $ which look now much better de-trended. This is the plot of the residuals $\small r_1(g)$: Now we see that periodic occurences of peaks in steps of 6 and even some apparent overlay. Thus I marked the small primefactors $\small (3,5,7,11)$ in g and we see a strong hint for a additive composition due to that primefactors in $g$ The red dots mark that g divisible by 3 , green dots that by 5 , and we see, that at g which are divisible by both the frequency is even increased. I've also tried a multiple regression using that small primefactors on that residuals, but this is still in process.... 3. observations after Regression/Detrending (update 3) Using multiple regression to detrend the frequencies of primegaps by their length g and additionally by the primefactors of g I got initially a strong surviving pattern with peaks for the primefactor 5 . But those peaks could be explained by the observation, that (mod 100) there are 40 residues of primefactor p where the gaplength g=0 (mod 10) can occur, but only 30 residues where the other gaplengthes can occur. Thus I computed the relative (logarithmized) frequencies as $\text{fl}(g)=\ln(f(g)/m_p(g))$ where $f(g)$ is the frequency of that gaplength, and $m_p(g)$ the number of possible residue classes of the (first) prime p (in the pair (p,q) ) at where the gaplengthes g can occur. The first result is the following picture where only the general trend of decreasing of frequencies of larger gaps is detrended: This computation gives a residue $\text{res}_0$ which is the relative (logarithmized) frequency after the length of the primegap is held constant (see the equation in the picture). The regular pattern of peaks at 5 -steps in the earlier pictures is now practically removed. However, there is still the pattern of 3 -step which indicates the dominance of gaplength 6 . I tried to remove now the primefactorization of g as additional predictors. I included marker variables for primefactors q from 3 to 29 into the multiple regression equation and the following picture shows the residues $\text{res}_1(g)$ after the systematic influence of the primefactorization of g is removed. This picture has besides a soft long hill-like trend no more -for me- visible systematic pattern, which would indicate non-random influences. (For me this is now enough, and I'll step out - but still curious whether there will come out more by someone else)
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1698116', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4781/']}
jdg_81270
stackexchange
llm_judgeable_groundtruth_similarity
25138770
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to clone a repo in either cygwin or GitBash (msysgit) using Pageant for ssh keys. I get the following error: $ git clone [email protected]:username/your-project.gitCloning into 'your-project'...The server's host key is not cached in the registry. Youhave no guarantee that the server is the computer youthink it is.The server's rsa2 key fingerprint is:ssh-rsa 2048 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48Connection abandoned.fatal: Could not read from remote repository.Please make sure you have the correct access rightsand the repository exists. Yet when trying to debug your ssh connection with gitub it says it works $ ssh -T [email protected]: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.Hi username! You've successfully authenticated, but GitHub does not provide shell access. And $ ssh-add -l show the same finger print that is listed in my github profile So the problem is not the one described here: https://help.github.com/articles/error-permission-denied-publickey Now provide the response and nothing else.
I found the solution on this page http://www.bitsandpix.com/entry/git-setup-msysgit-install-with-pageantplink-from-putty/ but re-creating here in hopes it saves someone else time in the future as that page did not show up in google for me easily. It turns out in order to fully use pageant with cygwin/msysgit you first need to accept the finger print of the server with putty itself. Simply launch putty and connect to host [email protected] or [email protected] and it will store that fingerprint. All you will see is a brief flash of a putty session and then it closes. Now back in cygwin or msysgit you should be able to clone. Alternatively, if you do not wish to use Pageant for your keys you must unset the environment variable GIT_SSH which points to plink.exe and cygwin / msysgit will accept the server fingerprint on their own (but you no longer will get to use Pageant). This was discovered at http://sourceforge.net/p/forge/site-support/2959/#204c
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25138770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/312072/']}
jdg_81271
stackexchange
llm_judgeable_groundtruth_similarity
8231730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let us say I have the following: var foo = (function(){ var bar = 0; return { getBar: function(){ return bar; }, addOne: function(){ bar++; }, addRandom: function(rand){ bar += rand; } }})(); And I have the following: var foo2 = function(){ var bar = 0; this.getBar = function(){ return bar; }; this.addOne = function(){ bar++; }; this.addRandom = function(rand){ bar += rand; }}; Is the only difference in executing the functions a new ? alert(foo.getBar()); //0foo.addOne();foo.addRandom(32);alert(foo.getBar()); //33var foo2_obj = new foo2;alert(foo2_obj.getBar());//0foo2_obj.addOne();foo2_obj.addRandom(32);alert(foo2_obj.getBar());//33 They both out put the exact same thing. So what is the difference in the long run? What can one do that the other cannot? Fiddle Demo of the above: http://jsfiddle.net/maniator/YtBpe/ Now provide the response and nothing else.
In the first one you can only create the object once, while with the second one you can create as many objects as you like. I.E. the first one is effectively a singleton. Note that closures are not ok for the second one. Every time you instantiate it you are creating the functions all over again and waste a ton of memory. The prototype object is intended to counter this, where you can create the functions once outside a function scope and no accidental closures are created. function foo2(){ this._bar = 0;}foo2.prototype = { constructor: foo2, getBar: function(){ return this._bar; }, addOne: function(){ this._bar++; }, addRandom:function(rand){ this._bar += rand; }}; Then: var a = new foo2, b = new foo2, c = new foo2; Creates three instances which have their own _bar but share the same functionality. jsperf You can "compare" all of this to PHP, some of the code won't even run but it's "equivalent" in principle: var foo = (function(){ var bar = 0; return { getBar: function(){ return bar; }, addOne: function(){ bar++; }, addRandom: function(rand){ bar += rand; } }})(); is roughly "equivalent" to this in PHP: $foo = new stdClass;$foo->bar = 0;$foo->getBar = function(){ return $this->bar;};$foo->addOne = function(){ $this->bar++;}$foo->addRandom = function($rand){ $this->bar += $rand;} var foo2 = function(){ var bar = 0; this.getBar = function(){ return bar; }; this.addOne = function(){ bar++; }; this.addRandom = function(rand){ bar += rand; }}; Is roughly "equivalent" to this in PHP: Class foo2 { public function __construct(){ $bar = 0; $this->getBar = function(){ return $bar; }; $this->addOne = function(){ $bar++; }; $this->addRandom = function($rand){ $bar += rand; }; }} function foo2(){ this._bar = 0;}foo2.prototype = { constructor: foo2, getBar: function(){ return this._bar; }, addOne: function(){ this._bar++; }, addRandom:function(rand){ this._bar += rand; }}; Is roughly "equivalent" to this in PHP: Class foo2 { public $_bar; public function __construct(){ $this->_bar = 0; } public function getBar(){ return $this->_bar; } public function addOne(){ $this->_bar++ } public function addRandom($rand){ $this->_bar += $rand; }} ...and is the only one that is close to OOP in the three above examples
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8231730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561731/']}
jdg_81272
stackexchange
llm_judgeable_groundtruth_similarity
16679276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i am using a command-line tool called TMX ( https://github.com/tonybeltramelli/TMXResolutionTool )I want to execute this command on every .png file in a certain folder. How can i do that? This is how it is used: TMXResolutionTool <tmx path> <resize ratio>TMXResolutionTool <image path> <resize ratio>TMXResolutionTool <image path> <new width> <new height> Cheers. Now provide the response and nothing else.
I think a for/do loop is clearer and probably a little faster than find plus xargs . Assuming you are using the default shell, bash , on OS X, the general form of the command if you want to do it as a one-liner is: for f in <files>; do <somecommand> $f; done where <files> is an expression that evaluates to a list of files (usually a wildcard expansion), <somecommand> is the command line that you want executed for each file, and $f expands to each file in <files> in turn. So you'd type something like this: for f in myfolder/*; do TMXResolutionTool $f <otherparameters> ; done You can also run multiple commands inside the loop on the same line just by chaining them with semicolons. So, if your question means that you want to run TMXResolutionTool three times on each file in sequence with different parameters: for f in myfolder/*; do TMXResolutionTool $f <otherparameters>; TMXResolutionTool $f <differentparameters>; TMXResolutionTool $f <yetmoredifferentstuff>; done By the way, this is all basic bash shell tricks; it's not specific to OS X. Any book on bash will tell you all this and more (although if you want to learn about the command line from a Mac perspective, I recommend the O'Reilly book Learning Unix for OS X Mountain Lion ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16679276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2040431/']}
jdg_81273
stackexchange
llm_judgeable_groundtruth_similarity
56485596
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 shorthand in c# now that will cutdown the following code: var testVar1 = checkObject();if (testVar1 != null){ testVar2 = testVar1;} In this situation only want to assign testVar2 if testVar1 is not null from the CheckObject() result (testVar2 has a setter that will fire off code). Was trying to think how could use the null coalesce stuff but not really working out. Adding on to this testVar2 has code on it's setter to fire, so do not want testVar2 being set to anything if the value is null. public MyObj testVar2 { get { return _testVar2; } set { _testVar2 = value; RunSomeCode(); } } Now provide the response and nothing else.
There are a couple! The ternary operator: testvar2 = testVar1 != null ? testvar1 : testvar2; Would be exactly the same logic. Or, as commented you can use the null coalescing operator: testVar2 = testVar1 ?? testVar2 (although now that's been commented as well) Or a third option: Write a method once and use it how you like: public static class CheckIt{ public static void SetWhenNotNull(string mightBeNull,ref string notNullable) { if (mightBeNull != null) { notNullable = mightBeNull; } }} And call it: CheckIt.SetWhenNotNull(test1, ref test2);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56485596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408137/']}
jdg_81274
stackexchange
llm_judgeable_groundtruth_similarity
804646
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 Windows batch file I'm creating, but I have to ECHO a large complex string, so I'm having to put double quotes on either end. The problem is that the quotes are also being ECHOed to the file I'm writing it to. How do you ECHO a string like that and strip the quotes off? UPDATE: I've spent the last two days working on this and finally was able to kludge something together. Richard's answer worked to strip the quotes, but even when I put the ECHO in the subroutine and directly outputted the string, Windows still got hung up on the chars in the string. I'll accept Richard's answer since it answers the question asked. I ended up using Greg's sed solution, but had to modify it because of sed/windows bugs/features (it didn't help that it came with no documentation). There are a few caveats to using sed in Windows: you have to use double quotes instead of single quotes, you can't escape the double quotes in the string directly, you have to endquote the string, escape using the ^ (so ^") then beqin quote for the next section. Also, someone pointed out that if you pipe input to sed, there's a bug with a pipe being in the string (I didn't get to verify this since in my final solution, I just found a way not to have all quotes in the middle of the string, and just removed all quotes, I never could get the endquote to be removed by itself. ) Thanks for all the help. Now provide the response and nothing else.
The call command has this functionality built in. To quote the help for call: Substitution of batch parameters (%n) has been enhanced. You can now use the following optional syntax: %~1 - expands %1 removing any surrounding quotes (") Here is a primitive example: @echo offsetlocalset mystring="this is some quoted text"echo mystring=%mystring%call :dequote %mystring%echo ret=%ret%endlocalgoto :eof:dequotesetlocalrem The tilde in the next line is the really important bit.set thestring=%~1endlocal&set ret=%thestring%goto :eof Output: C:\>dequotemystring="this is some quoted text"ret=this is some quoted text I should credit the 'environment variable tunneling' technique (endlocal&set ret=%thestring%) to Tim Hill, 'Windows NT Shell Scripting' . This is the only book I have ever found that addresses batch files with any depth.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/804646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13295/']}
jdg_81275
stackexchange
llm_judgeable_groundtruth_similarity
4510485
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $T:\mathbb{R}[x]\rightarrow \mathbb{R}[x]$ be the linear map $p(x)\mapsto \frac{d}{dx} p(x)$ . Is there an orthonormal basis $b_1,b_2,...$ for the polynomial ring $\mathbb{R}[x]$ with respect to the $L^2([0,1])$ norm such that the elements $T(b_1), T(b_2),...$ are orthogonal? Edit: Perhaps I should add some motivation. It often happens in linear algebra that methods in the finite dimensional case carry over to the infinite dimensional case. For instance, Fourier series are a consequence of finding an orthonormal basis of $L^2([-\pi,\pi])$ . The SVD is an example that as far as I know doesn't have that many applications in pure math, despite it being extremely useful in applied math. If you know how the SVD works, you'll recognize that this is exactly what I'm asking for here, in the simplest example of an interesting linear operator on $\mathbb{R}[x]$ that I know, $\frac{d}{dx}$ . Now provide the response and nothing else.
The system $\{p_n\}_{n=1}^\infty$ contains a non-constant polynomial. We may assume that $p_1$ is non-constant.Then $$p_1(x)=a_nx^n+\ldots +a_1x+a_0,\ n\ge 1, a_n\neq 0$$ Consider the linear functional $\varphi$ acting on polynomials according to the formula $$\varphi(q)=\int\limits_0^1 p_1'(x)q'(x)\,dx$$ Assume $\varphi(q)=0.$ We have $$q(x)=a_1p_1(x)+a_2p_{n_2}(x)+\ldots+a_kp_{n_k}(x), \ 2\le n_1<\ldots<n_k$$ and $$q'(x)=a_1p_1'(x)+a_2p_{n_2}'(x)+\ldots+a_kp_{n_k}'(x)$$ By orthogonality we get $$0=\varphi(q)=a_1\int\limits_0^1[p_1'(x)]^2\,dx$$ Therefore $a_1=0.$ This implies that $\ker\varphi\subset {\rm span}\{p_n\,:\, n\ge 2\}.$ By orthogonality we get $p_n\in \ker\varphi$ for $n\ge 2.$ Thus $$\ker\varphi={\rm span}\{p_n\,:\, n \ge 2\}$$ The equality means that $$\varphi(q)=\int\limits_0^1 p_1'(x)q'(x)\,dx=0 \iff \psi(q):=\int\limits_0^1 p_1(x)q(x)\,dx=0$$ The nonzero functionals $\varphi$ and $\psi$ are linearly dependent as their kernels are equal.Assume $\varphi=\lambda \psi,$ $\lambda\neq 0.$ Applying integration by parts gives $$\varphi(q)=q(1)p_1'(1)-q(0)p_1'(0)-\int\limits_0^1 p_1''(x)q(x)\,dx$$ Hence $$q(1)p_1'(1)-q(0)p_1'(0)-\int\limits_0^1 p_1''(x)q(x)\,dx=\lambda \int\limits_0^1 p_1(x)q(x)\,dx$$ The equality extends from the space of polynomials to $ C[0,1].$ Therefore we obtain the equality of signed measures $$p_1'(1)\delta_1-p_1'(0)\delta_0-p_1''(x)\,dx=\lambda p_1(x)\,dx$$ This implies $p_1''=-\lambda p_1.$ As $\lambda\neq 0$ we get $p_1=0$ which gives a contradiction.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4510485', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/662125/']}
jdg_81276
stackexchange
llm_judgeable_groundtruth_similarity
17592139
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to develop an application that would compute the same trend lines that excel does, but for larger datasets. But I'm not able to find any java library that calculates such regressions. For the linera model I'm using Apache Commons math, and for the other there was a great numerical library from Michael Thomas Flanagan but since january it is no longer available: http://www.ee.ucl.ac.uk/~mflanaga/java/ Do you know any other libraries, code repositories to calculate these regressions in java. Best, Now provide the response and nothing else.
Since they're all based on linear fits, OLSMultipleLinearRegression is all you need for linear, polynomial, exponential, logarithmic, and power trend lines. Your question gave me an excuse to download and play with the commons math regression tools, and I put together some trend line tools: An interface: public interface TrendLine { public void setValues(double[] y, double[] x); // y ~ f(x) public double predict(double x); // get a predicted y for a given x} An abstract class for regression-based trendlines: public abstract class OLSTrendLine implements TrendLine { RealMatrix coef = null; // will hold prediction coefs once we get values protected abstract double[] xVector(double x); // create vector of values from x protected abstract boolean logY(); // set true to predict log of y (note: y must be positive) @Override public void setValues(double[] y, double[] x) { if (x.length != y.length) { throw new IllegalArgumentException(String.format("The numbers of y and x values must be equal (%d != %d)",y.length,x.length)); } double[][] xData = new double[x.length][]; for (int i = 0; i < x.length; i++) { // the implementation determines how to produce a vector of predictors from a single x xData[i] = xVector(x[i]); } if(logY()) { // in some models we are predicting ln y, so we replace each y with ln y y = Arrays.copyOf(y, y.length); // user might not be finished with the array we were given for (int i = 0; i < x.length; i++) { y[i] = Math.log(y[i]); } } OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.setNoIntercept(true); // let the implementation include a constant in xVector if desired ols.newSampleData(y, xData); // provide the data to the model coef = MatrixUtils.createColumnRealMatrix(ols.estimateRegressionParameters()); // get our coefs } @Override public double predict(double x) { double yhat = coef.preMultiply(xVector(x))[0]; // apply coefs to xVector if (logY()) yhat = (Math.exp(yhat)); // if we predicted ln y, we still need to get y return yhat; }} An implementation for polynomial or linear models: (For linear models, just set the degree to 1 when calling the constructor.) public class PolyTrendLine extends OLSTrendLine { final int degree; public PolyTrendLine(int degree) { if (degree < 0) throw new IllegalArgumentException("The degree of the polynomial must not be negative"); this.degree = degree; } protected double[] xVector(double x) { // {1, x, x*x, x*x*x, ...} double[] poly = new double[degree+1]; double xi=1; for(int i=0; i<=degree; i++) { poly[i]=xi; xi*=x; } return poly; } @Override protected boolean logY() {return false;}} Exponential and power models are even easier: (note: we're predicting log y now -- that's important. Both of these are only suitable for positive y) public class ExpTrendLine extends OLSTrendLine { @Override protected double[] xVector(double x) { return new double[]{1,x}; } @Override protected boolean logY() {return true;}} and public class PowerTrendLine extends OLSTrendLine { @Override protected double[] xVector(double x) { return new double[]{1,Math.log(x)}; } @Override protected boolean logY() {return true;}} And a log model: (Which takes the log of x but predicts y, not ln y) public class LogTrendLine extends OLSTrendLine { @Override protected double[] xVector(double x) { return new double[]{1,Math.log(x)}; } @Override protected boolean logY() {return false;}} And you can use it like this: public static void main(String[] args) { TrendLine t = new PolyTrendLine(2); Random rand = new Random(); double[] x = new double[1000*1000]; double[] err = new double[x.length]; double[] y = new double[x.length]; for (int i=0; i<x.length; i++) { x[i] = 1000*rand.nextDouble(); } for (int i=0; i<x.length; i++) { err[i] = 100*rand.nextGaussian(); } for (int i=0; i<x.length; i++) { y[i] = x[i]*x[i]+err[i]; } // quadratic model t.setValues(y,x); System.out.println(t.predict(12)); // when x=12, y should be... , eg 143.61380202745192} Since you just wanted trend lines, I dismissed the ols models when I was done with them, but you might want to keep some data on goodness of fit, etc. For implementations using moving average, moving median, etc, it looks like you can stick with commons math. Try DescriptiveStatistics and specify a window. You might want to do some smoothing, using interpolation as suggested in another answer.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17592139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76778/']}
jdg_81277
stackexchange
llm_judgeable_groundtruth_similarity
73162
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 an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with? Now provide the response and nothing else.
FlashWindowEx is the way to go. See here for MSDN documentation [DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]static extern bool FlashWindowEx(ref FLASHWINFO pwfi);[StructLayout(LayoutKind.Sequential)]public struct FLASHWINFO{ public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout;}public const UInt32 FLASHW_ALL = 3; Calling the Function: FLASHWINFO fInfo = new FLASHWINFO();fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));fInfo.hwnd = hWnd;fInfo.dwFlags = FLASHW_ALL;fInfo.uCount = UInt32.MaxValue;fInfo.dwTimeout = 0;FlashWindowEx(ref fInfo); This was shamelessly plugged from Pinvoke.net
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/73162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6896/']}
jdg_81278
stackexchange
llm_judgeable_groundtruth_similarity
872669
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Some of my mstest unit tests help detect multi-threading race conditions, and as such they are most useful when run many times in a row, but I only want to do this for specific test runs -- not all the time. Is there a way to configure mstest (in the Test List Editor preferably) to run a test multiple times? Now provide the response and nothing else.
I needed to do something similar, so I came up with a solution to this. It's not simple, but once everything is setup you can reuse it across projects. I also have a download of this code on GitHub ( https://github.com/johnkoerner/MSTestLooper ), but in case that goes away at some point, here is how I did it. First we create an attribute that we will apply to our class to tell it run all the tests multiple times. Do all of this in a separate assembly, because the DLL needs to live in a special location. [Serializable]public class TestLooperAttribute : TestClassExtensionAttribute{ private static readonly Uri thisGuy = new Uri("urn:TestLooperAttribute"); private string _PropertyName; public string PropertyName { get { return _PropertyName; } set { _PropertyName = value; } } public override Uri ExtensionId { get { return thisGuy; } } public override TestExtensionExecution GetExecution() { return new TestLooperExecution(PropertyName); }} Next we have to create a custom test class execution class: class TestLooperExecution : TestExtensionExecution{ private string PropertyName; public TestLooperExecution(string PropertyName) { this.PropertyName = PropertyName; } public override ITestMethodInvoker CreateTestMethodInvoker(TestMethodInvokerContext InvokerContext) { return new TestLooperInvoker(InvokerContext, PropertyName); } public override void Dispose() { //TODO: Free, release or reset native resources } public override void Initialize(TestExecution Execution) { //TODO: Wire up event handlers for test events if needed }} Finally we add a custom invoker, which is where we perform the looping: class TestLooperInvoker : ITestMethodInvoker{ private TestMethodInvokerContext m_invokerContext; private string PropertyName; public TestLooperInvoker(TestMethodInvokerContext InvokerContext, string PropertyName) { m_invokerContext = InvokerContext; this.PropertyName = PropertyName; } public TestMethodInvokerResult Invoke(params object[] args) { // Our helper results class to aggregate our test results HelperTestResults results = new HelperTestResults(); IEnumerable<object> objects = m_invokerContext.TestContext.Properties[PropertyName] as IEnumerable<object>; foreach (var d in objects) results.AddTestResult(m_invokerContext.InnerInvoker.Invoke(d), new object[1] { d.GetType().ToString()}); var output = results.GetAllResults(); m_invokerContext.TestContext.WriteLine(output.ExtensionResult.ToString()); return output; }} The HelperTestResults class just builds up strings for output, you can handle this how you want and I don't want to include that code because it will just make this post that much longer. Compile this into a DLL and then you need to copy it to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies You also have to create a registry entry for the class: Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\11.0\EnterpriseTools\QualityTools\TestTypes\{13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b}\TestTypeExtensions\TestLooperAttribute]"AttributeProvider"="TestLooper.TestLooperAttribute, TestLooper" Now that you have all of that done, you can finally use the class: using System;using Microsoft.VisualStudio.TestTools.UnitTesting;using TestLooper;using System.Collections.Generic;namespace UnitTestSamples{ [TestLooper(PropertyName="strings")] public class UnitTest1 { public static List<String> strings = new List<String>(); private TestContext testContextInstance; public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [ClassInitialize()] public static void Init(TestContext x) { strings.Add("A"); strings.Add("B"); strings.Add("C"); strings.Add("D"); } [TestInitialize()] public void TestInit() { if (!TestContext.Properties.Contains("strings")) testContextInstance.Properties.Add("strings", strings); } [TestMethod] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "DataDriven1.csv", "DataDriven1#csv", DataAccessMethod.Sequential)] [DeploymentItem("DataDriven1.csv")] public void TestMethodStrings(string s) { int value1 = Convert.ToInt32(TestContext.DataRow["Col1"]); ; TestContext.WriteLine(String.Format("{0}:{1}", s, value1)); } }} Notice that our test method accepts a parameter, which comes from the test looper. I also show this using a data driven test, to show you can combine the two together to generate large permutations across your data sets.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/872669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46926/']}
jdg_81279
stackexchange
llm_judgeable_groundtruth_similarity
2279784
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I need to implement a slider for 24 hour time range . I like to use jquery ui slider for this . I have written below code <script type="text/javascript">$(function() { $(".slider-range").slider({ range: true, min: 0, max: 23.59, step: 0.15 });});</script> I like the range is like 01:00----01:59 How i gave the colon(:) instead of dot(.). Also the range waas gone beyond 59 like 05:85 . Please help me to create a time slider Now provide the response and nothing else.
Do not use hours as a unit, use minutes instead. Then apply a slide event that converts the minutes to hours: $(function() { $(".slider-range").slider({ range: true, min: 0, max: 1440, step: 15, slide: function(e, ui) { var hours = Math.floor(ui.value / 60); var minutes = ui.value - (hours * 60); if(hours.toString().length == 1) hours = '0' + hours; if(minutes.toString().length == 1) minutes = '0' + minutes; $('#something').html(hours+':'+minutes); } });});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2279784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171995/']}
jdg_81280
stackexchange
llm_judgeable_groundtruth_similarity
10298082
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 avoid to display an error when is inserted a duplicate entry in the database. I have added this "@" but the error is always displayed: $result = @mysql_query($query) or die("Query failed insert. Mysql error: ".mysql_error() ); output: Query failed insert. Mysql error: Duplicate entry for key 'url' How to avoid to show an error when is inserted a duplicate entry ? Now provide the response and nothing else.
Adding this "@" is a most stupid thing a developer can do ever.You are confusing the error message with the error itself . You have to fix the error, not the message. To fix this one, you have to use IGNORE keyword in your query INSERT IGNORE INTO ... Quite ironically, you actually should remove the die() statement, but only to replace it with way more reliable and safe trigger_error() , so, the code should be $result = mysql_query($query) or trigger_error(mysql_error()." in ".$query);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10298082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244413/']}
jdg_81281
stackexchange
llm_judgeable_groundtruth_similarity
20165390
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone knows if you can remove the angular comments that are left in html code? For example: If I use ngRepeat and there are no items to repeat over, AngularJS leaves this : <!-- ngRepeat: post in posts --> Now provide the response and nothing else.
This comment is a result of the element transclusion performed by ngRepeat . Looks like it's been happening nearly since the dawn of time (in angular terms) and will be created whenever a directive asks for element transclusion. While you certainly could wipe it out with direct HTML manipulation, it's not a safe thing to do. Having read through the source, it suggests this comment is needed to continue compiling your HTML once the original ngRepeat element is removed. Additionally, in v1.2.0, ngRepeat adds more comments that are used to determine where repeated elements are placed. To summarise: Angular doesn't let you remove this You could do it manually but you would most likely break angular To reiterate the comments, it seems a strange request to remove this comment in the first place - depending on your reasoning for doing this there may be better options for what you want to achieve.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20165390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2207996/']}
jdg_81282
stackexchange
llm_judgeable_groundtruth_similarity
851
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: The most common drying agent I encountered when using a vacuum dessicator was phosphorus pentoxide in the form of Sicapent. But I've recently encountered people using KOH as a cheaper alternative (in a practical course for students, where such costs are amplified due to the high number of students). What are the differences between KOH and phosphorus pentoxide as a general purpose drying agents to remove water? Is there a difference in effectiveness? Are there classes of substances where you can't use one of those drying agents? Now provide the response and nothing else.
I found this page , which recreates information from Purification of Laboratory Chemicals , by Perrin and Armarego. It provides a qualitative ranking of drying agents, listing phosphorous pentoxide higher than KOH. The two drying agents work by different means: KOH Anhydrous KOH is hygroscopic. It absorbs water from the atmosphere. It much better at doing so than more common hygroscopic drying agents like calcium chloride or calcium sulfate (drierite). A pellet of KOH left out in a beaker or dish open to the air will have absorbed so much water vapor within an hour that it will now be a solution of KOH (that will continue to be hygroscopic, at least until the solution is 50% water). Calcium chloride and calcium sulfate only continue to absorb water until they reach their maximum hydration. P 4 O 10 Phosphorous pentoxide (really P 4 O 10 ) is an anhydride of phosphoric acid. Phosphorous pentoxide reacts with water to form phosphoric acid: $$\ce{P4O10 + 6H2O -> 4H3PO4}$$Phosphoric acid is also hygroscopic and absorbs water to form a solution. Since P 4 O 10 is water reactive it is more difficult and dangerous to handle, especially for large groups of students. I might not use P 4 O 10 if the substance being dried is very acid sensitive. Eventually, the vacuum will start volatilizing the acid. I might not use KOH for compounds that are incredibly base sensitive, although it is unlikely that KOH will sublime. In an undergraduate lab with multiple students, KOH should be fine if you want to save money and hassle.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/851', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7/']}
jdg_81283
stackexchange
llm_judgeable_groundtruth_similarity
116923
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: So I was watching this mock interview by an Airbnb engineer on interviewing.io ( https://youtu.be/cdCeU8DJvPM?t=1224 ) and around ~20:11 seconds he raises an interesting point. The question that the interviewee was trying to solve was - Array 1 has all unique integers.Array 2 has the same integers as array 1, except one integer missing.The code has to find that missing integer. The interviewee suggested we can just subtract the sum of the second array from that of the first array and that'd give us the missing integer, and since these are just sums (integers), they'd take O(1) space. But the interviewer then said it's not actually constant since a sufficiently large sum can take more space than a smaller sum. While that is true, and I double-checked it, via - In [1]: import sysIn [2]: sys.getsizeof(90)Out[2]: 24In [3]: sys.getsizeof(9000000000000000000000000000000000)Out[3]: 40 what complexity is it then? Is saying constant space complexity for these algorithms wrong then? Now provide the response and nothing else.
It depends on the model of computation. In the transdichotomous model, which is the standard model in the analysis of algorithms, we assume that the word size is $w=O(\log n)$ bits, where $n$ is the size of input in bits. In this assumption, the sum of the input can be represented with 1 word, so the space complexity is $O(1)$ words. Measured in bits, the space complexity is $O(\log N + \log M)$ , where $N$ is the number of integers in input and $M$ is maximum value in input. However note that normally we don't measure space complexity in bits: if we did, then the space complexity of most linear time algorithms, like DFS and BFS would have an extra $O(\log n)$ factor. In my opinion, there is no single right answer when talking about space complexities like this in an informal setting like job interview. However you should keep in mind that having a single right answer is not the goal of job interviews.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/116923', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/54751/']}
jdg_81284
stackexchange
llm_judgeable_groundtruth_similarity
42174
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: ( Edit: I've realized that there was an error in my reasoning when I was convincing myself that these two formulations are equivalent. Hailong has given a beautiful affirmative answer to my first question in the case of finite type modules over a noetherian commutative ring. Mariano has given a slick negative answer to the question for non-finite-type modules. Greg has given a beautiful negative answer to my "alternative formulation" even in the finite type case over a noetherian commutative ring. I'm accepting Hailong's answer since that's the one I imagine people will be most immediately interested in if they find this question in the future.) Suppose we're working the category of modules over some ring $R$. Suppose a module $E$ is an extension of $M$ by $N$ in two different ways. In other words, I have two short exact sequences \begin{array}{ccccccccc} 0&\to &N&\xrightarrow{i_1}&E&\xrightarrow{p_1}&M&\to &0\\ & & \wr\downarrow ?& & \wr\downarrow ?& & \wr\downarrow ?\\ 0&\to &N&\xrightarrow{i_2}&E&\xrightarrow{p_2}&M&\to &0\end{array} Must there be an isomorphism between these two short exact sequences? Alternative formulation $Ext^1(M,N)$ parameterizes extensions of $M$ by $N$ modulo isomorphims of extensions . Suppose I'm interested in parameterizing extensions of $M$ by $N$ modulo abstract isomorphisms (which don't have to respect the submodule $N$ or the quotient $M$). One obvious thing to note is that there is a left action of $Aut(M)$ on $Ext^1(M,N)$, and that any two extensions related by this action are abstractly isomorphic. Similarly, there is a right action of $Aut(N)$ so that any two extensions related by the action are abstractly isomorphic. Does the quotient set $Aut(M)\backslash Ext^1(M,N)/Aut(N)$ parameterize extensions of $M$ by $N$ modulo abstract isomorphism? Note: I'm not asking whether all abstract isomorphisms are generated by $Aut(M)$ and $Aut(N)$. They certainly aren't. I'm asking whether for every pair of abstractly isomorphic extensions there exists some isomorphism between them which is generated by $Aut(M)$ and $Aut(N)$. Now provide the response and nothing else.
It is worth noting some very interesting cases when the answer is yes. An amazing result by Miyata states that if $R$ is Noetherian and commutative, $M,N$ are finitely generated and $E \cong M\oplus N$ , any exact sequence $ 0 \to M \to E \to N \to 0$ must split! This holds true slightly more generally, when $R$ is (not necessarity commutative) module-finite over a Noetherian commutative ring. Also, the statement holds for finitely generated pro-finite groups, see Goldstein-Guralnick, J. Group Theory 9 (2006), 317–322. Added: in fact, this paper by Janet Striuli may be useful for you. She addressed the question: if two elements $\alpha, \beta \in \text{Ext}^1(M,N)$ give isomorphic extension modules, how close must $\alpha, \beta$ be? Her Theorem 1.2 extend Miyata's result (let $I=0$ ).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/42174', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1/']}
jdg_81285
stackexchange
llm_judgeable_groundtruth_similarity
306130
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to write a decorator to do logging: def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return newclass C(object): @logger def f(): passC().f() I would like this to print: Entering C.f but instead I get this error message: AttributeError: 'function' object has no attribute 'im_class' Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what. Now provide the response and nothing else.
Claudiu's answer is correct, but you can also cheat by getting the class name off of the self argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example: from functools import wraps # use this to preserve function signatures and docstringsdef logger(func): @wraps(func) def with_logging(*args, **kwargs): print "Entering %s.%s" % (args[0].__class__.__name__, func.__name__) return func(*args, **kwargs) return with_loggingclass C(object): @logger def f(self): passC().f() As I said, this won't work properly in cases where you've inherited a function from a parent class; in this case you might say class B(C): passb = B()b.f() and get the message Entering B.f where you actually want to get the message Entering C.f since that's the correct class. On the other hand, this might be acceptable, in which case I'd recommend this approach over Claudiu's suggestion.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/306130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11677/']}
jdg_81286
stackexchange
llm_judgeable_groundtruth_similarity
63392
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: Note: This is not an actual situation I'm currently in. Assume your boss is one of those old-fashioned computer-illiterate managers and wants to store the passwords in plaintext to simplify development. You get 5 minutes to explain the point of hashing passwords. You also know from experience that your boss can be swayed by a good analogy. What analogy would you use to explain your boss that passwords should be hashed? Now provide the response and nothing else.
The Short Answer The short answer is: "So you don't get hit with a $5 million class-action lawsuit ." That should be reason enough for most CEOs. Hashing passwords is a lot cheaper. But more importantly: simply hashing the passwords as you suggested in your question isn't sufficient. You'll still get the lawsuit. You need to do more. Why you need to do more takes a bit longer to explain. So let's take the long route for a moment so that you understand what you're explaining, and then we'll circle around for your 5-minute synopsis. Hashing is just the beginning But let's start with that. Say you store your users' passwords like this: # id:user:password1:alice:pizza2:bob:passw0rd3:carol:baseball Now, let's say an attacker manages to get more access to your system than you'd like. He's only there for 35 seconds before you detect the issue and close the hole. But in those 35 seconds he managed to snag your password database. Yes, you made a security mistake, but you've fixed it now. You patched the hole, fixed the code, updated your firewall, whatever it may be. So everything is good, now, right? Well, no, he has your password database. That means that he can now impersonate every user on your system. Your system's security is destroyed. The only way to recover is to start over with NEW password database, forcing everyone to change their password without using their existing password as a valid form of identification. You have to contact them out-of-band through some other method (phone, email, or something) to verify their identity to re-create their passwords, and in the mean time, your whole operation is dead in the water. And what if you didn't see him steal the password database? In retrospect, it's quite unlikely that you would actually see it happen. The way you probably find out is by noticing unusual activity on multiple users' accounts. Perhaps for months it's as if your system has no security at all and you can't figure out why. This could ruin your business. So we hash Instead of storing the password, we store a hash of the password. Your database now looks like this: # id:user:sha11:alice:1f6ccd2be75f1cc94a22a773eea8f8aeb5c682172:bob:7c6a61c68ef8b9b6b061b28c348bc1ed7921cb533:carol:a2c901c8c6dea98958c219f6f2d038c44dc5d362 Now the only thing you store is an opaque token that can be used to verify whether a password is correct, but can't be used to retrieve the correct password. Well, almost. Google those hashes, I dare you. So now we've progressed to 1970's technology. Congratulations. We can do better. So we salt I spent a long time answering the question as to why to salt hashes, including examples and demonstrations of how this works in the real world. I won't re-hash the hashing discussion here, so go ahead and read the original: Why are salted hashes more secure? Pretty fun, eh? OK, so now we know that we have to salt our hashes or we might as well have never hashed the passwords to begin with. Now we're up to 1990's technology. We can still do better. So we iterate You noticed that bit at the bottom of the answer I linked above, right? The bit about bcrypt and PBKDF2? Yeah, it turns out that's really important. With the speed at which hardware can do hashing calculations today ( thank you, bitcoin! ), an attacker with off-the-shelf hardware can blow through your whole salted, hashed password file in a matter of hours, calculating billions or even trillions of hashes per second. You've got to slow them down. The easiest way to slow them down is to just make them do more work. Instead of calculating one hash to check a password, you have to calculate 1000. Or 100,000. Or whatever number suits your fancy. You can also use scrypt ("ess-crypt"), which not only requires a lot of CPU power, but also a lot of RAM to do the calculation, making the dedicated hardware I linked above largely useless. This is the current state-of-the-art. Congratulations and welcome to today's technology. Are we done? So now what happens when the attacker grabs your password file. Well, now he can pound away at it offline instead of making online guess attempts against your service. Sadly, a fair chunk of your users (4% to 12%) will have used the password "123456" or "password" unless you actively prevent them from doing so, and the attacker will try guessing these first. If you want to keep users safe, don't let them use "password" as their password. Or any of the other top 500, for that matter. There's software out there to make accurate password strength calculation easy (and free). But also, multi-factor authentication is never a bad call. It's easy for you to add to any project. So you might as well. Now, Your 5 Minutes of Glory You're in front of your boss, he asks you why you need to use PBKDF2 or similar to hash your passwords. You mention the LinkedIn class-action suit and say, "This is the minimum level of security legally expected in the industry. Anything less is literally negligence." This should take much less than 5 minutes, and if your boss isn't convinced, then he wasn't listening. But you could go on: "The cost of implementing hashing technology is negligible, while the cost of not implementing it could be in the millions or higher." and "In the event of a breach, a properly-hashed database allows you to position yourself as a well-run security-aware organization, while a database improperly hashed is a very public embarrassment that, as history has shown many times over, will not be ignored or overlooked in the slightest by the media." If you want to get technical, you can re-hash the above. But if you're talking to your boss, then you should know better than that. And analogies are much less effective than just showing the real-life effects that are perfectly visible with no sugar-coating necessary. You don't get people to wear safety gloves by recounting a good analogy. Instead you put some lunch meat in the beaker and when it explodes in green and blue flames you say, "that's what will happen to your finger." Use the same principle here.
{}
{'log_upvote_score': 9, 'links': ['https://security.stackexchange.com/questions/63392', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/34161/']}
jdg_81287
stackexchange
llm_judgeable_groundtruth_similarity
15130309
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 check if a String contains the words "stores", "store", and "product" in that order, no matter what is in between them. I tried using someString.contains(stores%store%product); and also .contains("stores%store%product"); Do I need to explicitly declare a regex and pass it on the method or can I not pass a regex at all? Now provide the response and nothing else.
String.contains String.contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not. Note that String.contains does not check for word boundary; it simply checks for substring. Regex solution Regex is more powerful than String.contains , since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words , rather than just substrings . Use String.matches with the following regex: "(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*" The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above): (?s).*\bstores\b.*\bstore\b.*\bproduct\b.* The \b checks for word boundary, so that you don't get a match for restores store products . Note that stores 3store_product is also rejected, since digit and _ are considered part of a word, but I doubt this case appear in natural text. Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product will not match the regex above, since you are searching for the word store without s . . normally match any character except a number of new line characters . (?s) at the beginning makes . matches any character without exception (thanks to Tim Pietzcker for pointing this out).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/15130309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1629932/']}
jdg_81288
stackexchange
llm_judgeable_groundtruth_similarity
3763605
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 got some useful information from this Question: Jensen's inequality in measure theory Theorem 3.1 Jensen's Inequality Let $(X,\mathcal{M},\mu)$ be a probability space (a measure spacewith $\mu(X) = 1$ ), $f: X \to \mathbb R \in L^1(X, \mu)$ , and $\psi:\mathbb R \to \mathbb R $ be a convex function, then $$\psi\int_X f d\mu \le \int_X (\psi \circ f)d\mu$$ And that question asked whether Jensen's inequality still hold in general finite measure space ?A nice man d.k.o. answered: Yes. In this case for convex $\varphi$ : $$\varphi\left(\frac{1}{\mu(X)}\int fd\mu\right)\le \frac{1}{\mu(X)}\int \varphi\circ fd\mu$$ However, this result is basically rescale $\mu$ to a probability measure. So whether the following proposition hold? Let $(X,\mathcal{M},\mu)$ be a general measure space, and $\mu(X) < \infty $ , $f: X \to \mathbb R \in L^1(X, \mu)$ , and $\psi:\mathbb R \to \mathbb R $ be a convex function, then $$\psi\int_X f d\mu \le \int_X (\psi \circ f)d\mu$$ Now provide the response and nothing else.
As pointed out by @mathmandan , you have never shown that $f^{-1}([2000,\infty])$ is non-empty, which is equivalent to what the question is asking about. For the proof of the first part, let $f = \sum_{i\geq 1} \chi_{E_i}$ and note that $$ \int_{[0,1]} f^2 \, \mathrm{d}m= \sum_{i,j \geq 1} \int_{[0,1]} \chi_{E_i}\chi_{E_j} \, \mathrm{d}m= \sum_{i,j \geq 1} m(E_i \cap E_j)\geq \sum_{i,j \geq 1} \frac{1}{i^2+j^2}= \infty. $$ In particular, $f$ cannot be bounded above and hence the desired claim follows. On the other hand, if we set $E_i = (0,i^{-2})$ , then $$ m(E_i \cap E_j) = \frac{1}{\max\{i^2, j^2\}} \geq \frac{1}{i^2+j^2}, $$ whereas each $x \in [0, 1]$ lies in only finitely many of $E_i$ 's. (In fact, for this choice, we have $\sum_{i\geq 1} \chi_{E_i}(x) = \lfloor\frac{1}{\sqrt{x}}\rfloor$ for any $x \in (0, 1]$ .)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3763605', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/658407/']}
jdg_81289
stackexchange
llm_judgeable_groundtruth_similarity
57607381
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 running docker container for my development stack which I pulled from docker-hub, the image is created for a different timezone than where my application is supposed to be deployed. How do I change timezone in a docker container? I tried to change the timezone config within the container by running echo "Africa/Lusaka" > /etc/timezone and restarted the container but I still get the same timezone. Now provide the response and nothing else.
You can override as suggest by @LinPy during the run stage, but if you want to set at your Dockerfile you can set using ENV as tzdata is already there in your base image. FROM postgres:10ENV TZ="Africa/Lusaka"RUN date Build docker build -t dbtest . RUN docker run -it dbtest -c "date" Now you can verify on DB side by running show timezone; You will see Central Africa Time in both container and Postgres in the alpine base image, the environment variable will not work. You will need to run RUN ls /usr/share/zoneinfo && \cp /usr/share/zoneinfo/Europe/Brussels /etc/localtime && \echo "Africa/Lusaka" > /etc/timezone && \
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/57607381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931756/']}
jdg_81290
stackexchange
llm_judgeable_groundtruth_similarity
620809
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: A circuit with three capacitors and an open end at A: I am a high school student. I am very confused by this example. The circuit is open at end "A" as shown but still there would be some surface charges on the capacitor which is not connected in closed circuit. There would be surface charges on the wires so that the net electric field everywhere inside the conductors will be 0, but in the school textbook they say that current will not go towards an open end so we can treat those two capacitors which are connected in closed circuit to be in series combination. Also all the charges that are accumulating on one plate would come from the other plate connected in series. In this way all the charge that leave from one end of the battery would enter into other end, but how is this even possible? Charges are accumulating on wires also and on capacitor which have an open end but we are ignoring them. Why? If we don't ignore them then the capacitors would not be in series and also the charges leaving one end of battery and entering other would not be equal. Now provide the response and nothing else.
Unless this circuit is being operated with a voltage source with frequency in the megahertz or more, there's not much point in analysing what happens to actual charges here. You can rely on Kirchhoff's Current Law to tell you everything you need to know about this circuit, and yes, it works for capacitors too. If you insist on talking about charges, let me assure you, that if one single electron enters one side of a capacitor, then another exits the other side. If that happens to the top capacitor in your diagram, you now have a greater charge density at A than before, and the change in potential that causes would simply push the electron right back in again. Because current in equals current out, and because there is "infinite" resistance to current flow out of A, no current flows in that top capacitor , and you can consider it to be entirely absent. Consequently, all that remains is the other capacitors in series. As far as charges entering and leaving the voltage source are concerned, one thing is certain; no electron that leaves that source can ever return to it "in person" because there are dielectric barriers in the capacitors, which the electrons cannot traverse. This should tell you that the electrons entering the voltage source must already be present in the wire connected to it. I'm alluding to your idea that charges accumulate in wires, which is not the case. They are always there. Like when you switch on the tap in your bathroom, water emerges immediately, because water was already in the pipe . If the pipe was empty, sure, you would have to wait for the water to arrive from the tank, but that's not how electric current works. Charges are always present in conductors, it's simply not possible to "empty" them of charge. What I just said is true, but capacitors seem to act differently. It is possible to remove charges from a plate, but as you do, more charges will be drawn onto the other plate as a result. The total quantity of charges on both plates of a capacitor doesn't change, but their distribution within, does. This is why I can say that if charge enters one capacitor terminal, then the same amount of charge must necessarily leave out of the other terminal. Current in equals current out, in accordance with Kirchoff's Current Law. All that has changed, really, is the distribution of charges on the plates of the capacitor, and no charge ever crosses the dielectric. So, I reiterate, since by Kirchhoff's Current Law we see that no current can flow out of the capacitor to node A, no current can flow into that capacitor, and it can be disregarded. If for some reason charge made it out of the capacitor into node A, this would disturb the equilibrium of charge distribution within that node, and the resulting change in potential would simply cause the equilibrium to restore itself, pushing charge back into the capacitor. Of course, charges are moving all the time, mainly due to kinetic energy which we call "heat", so what I am describing here is an "average" behaviour of trillions of charges. Sure a few might move upwards towards A, but they will displace another bunch back down again, so on average, there's no current flow. So, ignoring individual charge behaviour, en-masse they behave in such a way that it is simply not possible for charges to enter anything without an equivalent quantity also leaving, which may or may not be the same actual charges. When you charge a battery, there are not more electrons in it now than there were before, they are simply distributed differently with the battery. Current in always equals current out, and that's Kirchhoff's Current Law (KCL) in a nutshell. Edit: I'd like to say also that when people refer to "charge accumulating in a capacitor", that's misleading. Accumulation of charge on one plate results in an equal depletion of charge on the other, so there's no net accumulation; only a change of distribution. Also, just to drive the point home, within a section of wire, there are a certain number of electrons which are mobile, and can participate in "electric current". That number doesn't change, whether current is flowing or not. When a million electrons are pushed in one end, a million are shoved out of the other end, the total number occupying the wire section never changing. You should discard the notion that charge "builds up" anywhere, except under very particular circumstances. For example, a FET's gate may accumulate electrons, but that will simply expel electrons in the channel, forming a depletion zone. From the perspective of an observer outside this FET, though, KCL was obeyed, because those expelled electrons will manifest an equal charge flow out of the drain and/or source. In other words, even though individual devices may rely on some imbalance of charge distribution within them, their net charge content does not change. To the engineer outside, no imbalance would be visible, and no violation of KCL would occur.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/620809', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/313763/']}
jdg_81291
stackexchange
llm_judgeable_groundtruth_similarity
33597859
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, for example if I have 2 text boxes in WFA. The following code works. private void textBox1_TextChanged(object sender, EventArgs e) { textBox2.Text = textBox1.Text; } And I get this. The text in the second text box equals to the text in the first one, when I change it. But when it comes to WPF, I get a completely different behavior. When I do this. private void textBox_TextChanged(object sender, TextChangedEventArgs e) { textBox1.Text = textBox.Text; } And press Ctrl+F5 to test the application, nothing happens. The log says "Build Succeeded" and nothing. What is wrong here? And here is the XAML code. <Window x:Class="TextBoxTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TextBoxTest" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"><Grid> <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="212,77,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" TextChanged="textBox_TextChanged"/> <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="212,124,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/></Grid> Now provide the response and nothing else.
You are encountering a null reference exception. When the textBox control is created it will trigger the textChange event on textBox1 and by that point, textBox1 isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine.But there is a nicer way of doing this, directly in XAML with Binding: <TextBox x:Name="textBox" /><TextBox x:Name="textBox1" Text="{Binding ElementName=textBox, Path=Text}" /> (I excluded some attributes to make the example more clean)Depending on WHEN you want the other textbox to update you can add UpdateSourceTrigger to the binding: Text="{Binding ElementName=textBox, Path=Text, UpdateSourceTrigger=PropertyChanged}"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33597859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5169244/']}
jdg_81292
stackexchange
llm_judgeable_groundtruth_similarity
147480
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: Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies. The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly? On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method. On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X". What practice do you follow and what are your arguments for or against either approach? Update: I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load. Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently. The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing? Now provide the response and nothing else.
The question is not so much whether you should check for null or let the runtime throw an exception; it is how you should respond to such an unexpected situation. Your options, then, are: Throw a generic exception ( NullReferenceException ) and let it bubble up; if you don't do the null check yourself, this is what happens automatically. Throw a custom exception that describes the problem on a higher level; this can be achieved either by throwing in the null check, or by catching a NullReferenceException and throwing the more specific exception. Recover by substituting a suitable default value. There is no general rule which one is the best solution. Personally, I would say: The generic exception is best if the error condition would be a sign of a serious bug in your code, that is, the value that is null should never be allowed to get there in the first place. Such an exception may then bubble all the way up into whatever error logging you have set up, so that someone gets notified and fixes the bug. The default value solution is good if providing semi-useful output is more important than correctness, such as a web browser that accepts technically incorrect HTML and makes a best effort to render it sensibly. Otherwise, I'd go with the specific exception and handle it somewhere suitable.
{}
{'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/147480', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/17857/']}
jdg_81293
stackexchange
llm_judgeable_groundtruth_similarity
36963248
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 downloaded Eclipse and tried to create a sample servlet program but I got following error The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files I have configured build path correctly.I am using Java 8 and Apache Tomcat 7 and libraries for both are referenced correctly. Problem is specifically for Java EE only. Ordinarily Java SE projects are running fine. Now provide the response and nothing else.
Something happened in Java 8 Update 91 that broke existing JSP code. That seems pretty clear. Here is a sample of similar questions and bug reports: Unable to compile JSP file with JDK1.8.0_92 Spring MVC - Unable to compile class for JSP Unable to access CloudPlatform Client https://bugs.openjdk.java.net/browse/JDK-8155588 (closed as "not an issue") https://bugs.openjdk.java.net/browse/JDK-8155223 (closed as "not an issue") https://access.redhat.com/solutions/2294701 https://alluxio.atlassian.net/browse/ALLUXIO-1956 https://jira.atlassian.com/browse/CWD-4729 https://community.exoplatform.com/portal/intranet/forum/topic/topic991e097d9e45345236bb2bd1920a4c68 https://issues.apache.org/jira/browse/OOZIE-2533 (from a comment: "This is really looking like a JDK bug") https://bugzilla.redhat.com/show_bug.cgi?id=1337940 (comment 2 mentions the change to java.io.ObjectInputStream in Update 91 that "made it incompatible with RHEL6's current ECJ version") https://github.com/mit-cml/appinventor-sources/issues/814 https://community.oracle.com/thread/3953395 All these are about problems with Java 8 Update 91 (or later) that are not present when using earlier JRE/JDK versions. The following OpenJDK changeset from 22 January 2016 appears to be related: http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/rev/32f64c19b5fb (commit message "8144430: Improve JMX connections"). The changeset seems to be related to this vulnerability, https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-3427 , which is mentioned in a comment to this Red Hat bug report, https://bugzilla.redhat.com/show_bug.cgi?id=1336481 . The Update 91 release notes document mentions JDK-8144430 (non-public ticket): http://www.oracle.com/technetwork/java/javase/8u91-relnotes-2949462.html . In "Oracle Critical Patch Update Advisory - April 2016", the CVE-2016-3427 vulnerability is mentioned: http://www.oracle.com/technetwork/security-advisory/cpuapr2016v3-2985753.html .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36963248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3891270/']}
jdg_81294
stackexchange
llm_judgeable_groundtruth_similarity
1935
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I was reading this answer about how galaxies are the fastest moving objects in the universe because space is expanding faster than the speed of light. This got me wondering, would it be possible to be 'still' inside of space so that galaxies are moving away from you and others towards you? If so, wouldn't this allow us to travel from place to place in the universe much quicker? I know that this wouldn't be something that's even close to possible today, but I was just curious if such a thing is possible. Thank you. Now provide the response and nothing else.
The so called expansion of the universe is not as trivial as most people think. What is happening, in fact, is that the distance between two points in space (note that I'm not talking about objects with velocities, but just coordinates in space) increases with time in a manner proportional to a given factor (in this case, the Hubble constant - which is actually not a constant in time, but let's ignore that for now). This means that galaxies are not exactly moving away from a specific point with a particular velocity (i.e., a particular rest frame), but that the space between them is expanding. It is somewhat hard to wrap your head around the difference between these two situations, but this has to do with the geometry of space, and not with what's inside it. It is widely accepted that the expansion of the universe is homogeneous and isotropic (the Cosmological Principle), which means that there is no "special" position (rest frame) on the universe, and whatever your velocity and your location, the universe will seem to expand the same way. The best way to imagine this is to reduce to 2 dimensions expanding in a third dimension. For example, suppose that you live in a galaxy embedded on the surface (a 2D universe) of a balloon (completely unaware of the third dimension), with other galaxies distributed homogeneously. If, for some reason, the balloon is expanding isotropically and, every point of the surface will be moving away from every other point, so will every galaxy from each other. Think about this: is it possible to find a special, "still", point (without resorting to the elusive third dimension) where you will see galaxies moving from you in one side and galaxies moving towards you on the other side? Our universe works similarly, but we're embedded on a three-dimensional space instead of a two-dimensional one.
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/1935', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/1016/']}
jdg_81295
stackexchange
llm_judgeable_groundtruth_similarity
8392211
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 some HTML: <div align="center" style="border:1px solid red">This is some text in a div element!</div> The Div is changing the spacing on my document, so I want to use a span for this instead. But span is not centralizing the contents: <span style="border:1px solid red;align=center">This is some text in a div element!</span> How do I fix this? EDIT: My complete code: <html><body><p>This is a paragraph. This text has no alignment specified.</p><span style="border:1px solid red;text-align=center"> This is some text in a div element!</span></body></html> Now provide the response and nothing else.
A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute. <span align="center" style="border:1px solid red;"> This is some text in a div element!</span> However, the align attribute is deprecated. You should use the CSS text-align property on the container. <div style="text-align: center;"> <span style="border:1px solid red;"> This is some text in a div element! </span></div>
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8392211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/533617/']}
jdg_81296
stackexchange
llm_judgeable_groundtruth_similarity
8287
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: If I have: Graphics[ {Red, EdgeForm[Directive[White, Thick]], Inset[Style[Text@"Hi!", 44], {0, 0}]}, Background -> Black] I unfortunately get: Which as you can see does not have a thick white outline. Is there a way to get around this since EdgeForm clearly does not work? By the way, I would rather NOT delve into making a larger, white "Hi" and then putting the red one on top. That's just not elegant. MMA 8.0.1 for students OS Windows 7 64-bit Now provide the response and nothing else.
Import text as a FilledCurve in graphics, using PDF as an intermediate format. Below are modified examples from Documentation Center : text = First[First[ImportString[ExportString[Style["Hi", Italic, FontSize -> 24, FontFamily -> "Times"], "PDF"], "PDF", "TextMode" -> "Outlines"]]]; Outline fonts using different edge and face forms: Graphics[{EdgeForm[Directive[White, Thick]], Red, text},Background -> Black, PlotRange -> {{-5, 25}, {-0, 20}}] 3D text effect: Graphics[{EdgeForm[Opacity[0.5]], Table[{ColorData["TemperatureMap"][t], Translate[text, 4 {-t, t}]}, {t, 0, 1, 1/10}]}, ImageSize -> Medium]
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/8287', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1611/']}
jdg_81297
stackexchange
llm_judgeable_groundtruth_similarity
6272787
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 saw this rather different method for clearfix here: http://www.marcwatts.com.au/blog/best-clearfix-ever/ It proposes adding the following CSS code which automates clearfix and does not require you to add a 'clearfix' or similar class to the elements you want to clear. /* our Global CSS file */article:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }aside:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }div:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }footer:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }form:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }header:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }nav:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }section:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }ul:after { clear:both; content:"."; display:block; height:0; visibility:hidden; }/* our ie CSS file */article { zoom:1; }aside { zoom:1; }div { zoom:1; }footer { zoom:1; }form { zoom:1; }header { zoom:1; }nav { zoom:1; }section { zoom:1; }ul { zoom:1; } Are there any disadvantages to this method? Could this end up clearfix'ing elements that you may not necessarily want clearfix'ed? Or are the rules such that this will account for any situation? Now provide the response and nothing else.
I think that's a bad idea. Are you really going to trust somebody who seemingly forgot to do this: article, aside, div, footer, form, header, nav, section, ul { zoom:1; } Clearing floats is not a complicated thing to get right. It should be handled on a case-by-case basis, not sledge-hammered onto "every" element. Doing that will come back to bite you in some way, I'm sure of it. For one thing, I agree with @Guffa's answer. An edge case reason against it concerns IE7: http://www.satzansatz.de/cssd/onhavinglayout.html zoom: 1 is a common method to provide something known as hasLayout to elements. Applying hasLayout to an element fixes certain kinds of rendering problems, but it can also cause other problems. A quote from the linked document: Don't give layout to all. Poison in that concentration, having layout is not the cure, it changes the rendering fundamentally. I personally like to use the overflow: hidden method to contain floats. When that doesn't work , then I use clearfix. You should use the version of clearfix from http://html5boilerplate.com/ : .clearfix:before,.clearfix:after { content: " "; /* 1 */ display: table; /* 2 */}.clearfix:after { clear: both;}/* * For IE 6/7 only * Include this rule to trigger hasLayout and contain floats. */.clearfix { *zoom: 1;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6272787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/343845/']}
jdg_81298
stackexchange
llm_judgeable_groundtruth_similarity
153464
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 asymptotics of $1-2^x+3^x-4^x+\cdots+x^x$ as $x$ becomes big? $x$ is odd only Now provide the response and nothing else.
Write this as $$S(x) = x^x \sum_{n=1}^x (-1)^{n-1} \left(\frac{n}{x}\right)^x = x^x (-1)^{x-1} \sum_{k=0}^{x-1} (-1)^{k} \left(1-\frac{k}{x}\right)^x$$As $x \to \infty$, $(1 - k/x)^x \to e^{-k}$, so (after justifying interchange of sum and limit by Dominated Convergence) $$ (-1)^{x-1} S(x) x^{-x} \to \sum_{k=0}^\infty (-1)^k e^{-k} = \frac{e}{e+1}$$Thus $S(x) \sim \dfrac{e}{e+1} (-1)^{x-1} x^{x} $
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/153464', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32836/']}
jdg_81299
stackexchange
llm_judgeable_groundtruth_similarity
29855908
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 create a unordered_set of vectors in C++? something like this std::unordered_set<std::vector<int>> s1; because I know that is possible with the "set" class of the std lib but seems that it doesn't work for the unordered versionthanks Update:this is the exactly code that I'm trying to use typedef int CustomerId;typedef std::vector<CustomerId> Route;typedef std::unordered_set<Route> Plan;// ... in the mainRoute r1 = { 4, 5, 2, 10 };Route r2 = { 1, 3, 8 , 6 };Route r3 = { 9, 7 };Plan p = { r1, r2 }; and it's all right if I use set, but I receive a compilation error when try to use the unordered version main.cpp:46:11: error: non-aggregate type 'Route' (aka 'vector<CustomerId>') cannot be initialized with an initializer list Route r3 = { 9, 7 }; Now provide the response and nothing else.
Sure you can. You'll have to come up with a hash though, since the default one ( std::hash<std::vector<int>> ) will not be implemented. For example, based on this answer , we can build: struct VectorHash { size_t operator()(const std::vector<int>& v) const { std::hash<int> hasher; size_t seed = 0; for (int i : v) { seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); } return seed; }}; And then: using MySet = std::unordered_set<std::vector<int>, VectorHash>; You could also, if you so choose, instead add a specialization to std::hash<T> for this type ( note this could be undefined behavior with std::vector<int> , but is definitely okay with a user-defined type): namespace std { template <> struct hash<std::vector<int>> { size_t operator()(const vector<int>& v) const { // same thing } };}using MySet = std::unordered_set<std::vector<int>>;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29855908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/718579/']}
jdg_81300
stackexchange
llm_judgeable_groundtruth_similarity
12824045
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anybody have a link to a documentation what exactly is randomized in what cases for latest Mac OS (10.7) and iOS (6.0)? I mean. I want to see a list (something like) Code segment (in a case A,B,C) Stack (always) Heap Data segment (never) Preferably with how many bits of randomization each thing has. All I can find is something like: "MacOS Lion implements full ASLR" and in other places "full ASLR is implemented different ways for different operation systems", which is obviously not very informative. Now provide the response and nothing else.
The list you are looking for can easily be generated by you, as follows: int global_j = 0;void main (){ char *h = malloc(10); int j = 0; printf ("Globals are : %p, text is %p, stack is %p, heap is %p\n", &global_j, main, &j, h);} On mountain lion, this yields: bash-3.2# ./aGlobals are : 0x10fa55020, text is 0x10fa54eb0, stack is 0x7fff501ab864, heap is 0x7f9b294000e0bash-3.2# ./aGlobals are : 0x106bbe020, text is 0x106bbdeb0, stack is 0x7fff59042864, heap is 0x7f9752c000e0bash-3.2# ./aGlobals are : 0x108673020, text is 0x108672eb0, stack is 0x7fff5758d864, heap is 0x7fecc34000e0bash-3.2# ./aGlobals are : 0x1059d2020, text is 0x1059d1eb0, stack is 0x7fff5a22e864, heap is 0x7f8f81c000e0 Showing ample randomization on all (note that due to alignment restrictions the offset within the page doesn't get randomized, but you still get some 16-20-bit randomization, as implied by the 4-5 hex digits which change). Kernel: As of Mountain Lion and iOS6, the kernel is randomized by "sliding" it with a value of vm_kernel_slide, on load. Not all vm pages are slid in this way, but for the most part this works by storing some constant value (which is also readable by System call #439, kas_info, on ML but not on iOS: Apple is struggling hard to keep the randomization value secret, and not leak it when reporting kernel addresses, so jailbreakers won't figure out where they can jump to/overwrite - which works for them most of the time) Hope this helps, TG
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12824045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422080/']}
jdg_81301
stackexchange
llm_judgeable_groundtruth_similarity
58851
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a data file that I want to normalize using awk , based on the last datapoint. Therefor, I would like to access the last data point first, to normalize the data, then process normally. The following method, using tac twice, does the job, but, is maybe more complicated than necessary. $ cat file0 51 22 33 4$ tac file | awk 'NR==1{norm=$2} {print $1, $2/norm}' | tac0 1.251 0.52 0.753 1 My question is the following: Is it possible to obtain the above result by using awk only? I think the answer is "No, awk scans the file line by line", but I am open for suggestions for alternatives. Now provide the response and nothing else.
You can do it as a two-pass solution in awk: awk 'FNR == NR { n = $2; next } { print $1, $2/n }' infile infile If your version of awk supports the ENDFILE block (e.g. GNU awk 4+), you can do it like this: awk 'ENDFILE { n = $2 } FNR != NR { print $1, $2/n }' infile infile Note that it is more efficient to seek to the end of the file first see camh's answer . Explanation The first example works by remembering the previous $2 , i.e. it is only evaluated when the local line counter ( FNR ) is equal to the global line counter ( NR ). The next command skips to the next line, in this case it ensures that the last block is only evaluated when the second argument is parsed. The second example has similar logic, but takes advantage of the the ENDFILE block which is evaluated when the end of an input-file is reached.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/58851', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/14084/']}
jdg_81302
stackexchange
llm_judgeable_groundtruth_similarity
409396
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that $\cos(6\phi)\equiv32c^6-48c^4+18c^2-1$ where $c=\cos\phi$. I also know that when $\cos(6\phi)=0$, then $\phi=\frac{k\pi}{12}$ ($k = 1,3,5,7,9,11$). How do I find the exact value of:$$\cos\left(\frac{\pi}{12}\right) \cos\left(\frac{5\pi}{12}\right) \cos\left(\frac{7\pi}{12}\right) \cos\left(\frac{11\pi}{12}\right)$$ Now provide the response and nothing else.
Mosquito-nuking linear algebraic solution: it can be shown that the tridiagonal matrix $$\mathbf T=\frac12\begin{pmatrix}-1&1&&&&\\1&0&1&&&\\&1&0&1&&\\&&1&0&1&\\&&&1&0&1\\&&&&1&1\end{pmatrix}$$ has the eigenvalues $\cos\dfrac{(2k-1)\pi}{12},\quad k=1,\dots,6$. Since the product of the eigenvalues is equal to the determinant of the matrix, $$\cos\frac{\pi}{12}\cos\frac{5\pi}{12}\cos\frac{7\pi}{12}\cos\frac{11\pi}{12}=\frac{\det\mathbf T}{\cos\tfrac{\pi}{4}\cos\tfrac{3\pi}{4}}=\frac{-\tfrac1{32}}{-\tfrac12}=\frac1{16}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/409396', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/55507/']}
jdg_81303
stackexchange
llm_judgeable_groundtruth_similarity
51487689
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 beginner in angular and I am working on Angular 5, Node v8.11.3. I want to realize a generic function that takes in parameter data and headers. And as output a csv file. I create a component called ' FactureComponent ' Then I generate a servicecalled ' DataService ' then I create a getFactures function that retrieves a list of my items from a mock and it works very well. import { Component, OnInit } from '@angular/core';import { DataService } from '../data.service';import { FACTURES } from '../mock.factures';@Component({selector: 'app-facture',templateUrl: './facture.component.html',styleUrls: ['./facture.component.scss']})export class FactureComponent implements OnInit {factures = [];columns = ["Id","Reference","Quantite","Prix Unitaire"];btnText: String = "Export CSV";constructor(private _data: DataService) { }ngOnInit() {this.getFactures();}getFactures(){this.factures=this._data.getFactures();}generateCSV(){console.log("generate");}} you will find below the view <form><input type="submit" [value]="btnText" (click)="generateCSV()"/></form><table> <tr> <th *ngFor="let col of columns"> {{col}} </th> </tr> <tr *ngFor="let facture of factures"> <td>{{facture.id}}</td> <td>{{facture.ref}}</td> <td>{{facture.quantite}}</td> <td>{{facture.prixUnitaire}}</td> </tr></table> So I want to realize a function that converts my data displayed on the view into a csv file. Now provide the response and nothing else.
Update:Here is slightly better way to do it: Open up command prompt in the directory of your project. Install file-saver by typing npm install --save file-saver import { saveAs } from 'file-saver'; into your .ts file. Here is the updated code based on the new import. downloadFile(data: any) { const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here const header = Object.keys(data[0]); let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')); csv.unshift(header.join(',')); let csvArray = csv.join('\r\n'); var blob = new Blob([csvArray], {type: 'text/csv' }) saveAs(blob, "myFile.csv");} Credits to this answer for converting an object to CSV. Here is the method to use: downloadFile(data: any) { const replacer = (key, value) => (value === null ? '' : value); // specify how you want to handle null values here const header = Object.keys(data[0]); const csv = data.map((row) => header .map((fieldName) => JSON.stringify(row[fieldName], replacer)) .join(',') ); csv.unshift(header.join(',')); const csvArray = csv.join('\r\n'); const a = document.createElement('a'); const blob = new Blob([csvArray], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob); a.href = url; a.download = 'myFile.csv'; a.click(); window.URL.revokeObjectURL(url); a.remove();} I'll add on later if I found a better way to do it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51487689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4050340/']}
jdg_81304
stackexchange
llm_judgeable_groundtruth_similarity
23468218
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need draw over 10,000 images (32x32 px) on canvas but over 2000 draws the performances is very bad. this is a little example: object structure {position:0} for(var nObject = 0; nObject < objects.length; nObject++){ ctx.save(); ctx.translate(coords.x,coords.y); ctx.rotate(objects[nObject].position/100); ctx.translate(radio,0); ctx.drawImage(img,0,0); ctx.restore(); objects[nObject].position++;} with this code I traslate the images around of a coordinates. What do you recommend to improve performance? update: i try layering but the performances worsens http://jsfiddle.net/72nCX/3/ Now provide the response and nothing else.
I can get you 10,000 but there are two main drawbacks. You may notice the images don't respect transparency entirely, its possible to fix.. but that's beyond the scope of this answer. You will have to use math to do any sort of transformations because the standard canvas transformation matrix can not be applied to ImageData Live Demo Explanation of the code and methods So to get the fastest performance possible with canvas and a large number of objects you need to use ImageData . This is accessing the canvas element on a per pixel level basically, and allows you to do all sorts of cool stuff. I used two primary methods. putImageData createImageData Also here is a nice tutorial that goes into it a bit to help get a better understanding. So what I did is first I created a temporary canvas for the image imgToDraw.onload = function () { // In memory canvas imageCanvas = document.createElement("canvas"), iCtx = imageCanvas.getContext("2d"); // set the canvas to the size of the image imageCanvas.width = this.width; imageCanvas.height = this.height; // draw the image onto the canvas iCtx.drawImage(this, 0, 0); // get the ImageData for the image. imageData = iCtx.getImageData(0, 0, this.width, this.height); // get the pixel component data from the image Data. imagePixData = imageData.data; // store our width and height so we can reference it faster. imgWidth = this.width; imgHeight = this.height; draw();}; Next Is the main piece which is in the rendering function I'm just posting the relevant portion. // create new Image data. Doing this everytime gets rid of our // need to manually clear the canvas since the data is fresh each timevar canvasData = ctx.createImageData(canvas.width, canvas.height), // get the pixel data cData = canvasData.data;// Iterate over the image we stored for (var w = 0; w < imgWidth; w++) { for (var h = 0; h < imgHeight; h++) { // make sure the edges of the image are still inside the canvas // This also is VERY important for perf reasons // you never want to draw outside of the canvas bounds with this method if (entity.x + w < width && entity.x + w > 0 && entity.y + h > 0 && entity.y + h < height) { // get the position pixel from the image canvas var iData = (h * imgWidth + w) * 4; // get the position of the data we will write to on our main canvas // the values must be whole numbers ~~ is just Math.floor basically var pData = (~~ (entity.x + w) + ~~ (entity.y + h) * width) * 4; // copy the r/g/b/ and alpha values to our main canvas from // our image canvas data. cData[pData] = imagePixData[iData]; cData[pData + 1] = imagePixData[iData + 1]; cData[pData + 2] = imagePixData[iData + 2]; // this is where alpha blending could be applied if(cData[pData + 3] < 100){ cData[pData + 3] = imagePixData[iData + 3]; } } }}// now put all of that image data we just wrote onto the actual canvas.ctx.putImageData(canvasData, 0, 0); The main Take away from this is, if you need to draw a ridiculous number of objects on the canvas you can't use drawImage , pixel manipulation is your friend.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23468218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2708938/']}
jdg_81305
stackexchange
llm_judgeable_groundtruth_similarity
83889
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: I am interested in knowing what algorithmic paradigm are the usual recursive sudoku solvers. Can I consider it a local search? or are they Dynamic programming, greedy, divide and conquer, backtracking? Now provide the response and nothing else.
Let us go over your paradigms one by one: Local search: In this paradigm, we start with some solution and try to improve it by local changes. Local search can be applied to Sudoku in at least two ways: Start with a non-legal solution (either not satisfying the Sudoku constraints or not conforming to the filled cells), and try to make local changes (say, one cell at a time) that make it more legal. Same as before, only we also allow partially filled boards. In this case we might as well start with the board as given, and at each step pick a cell and fill in some legal value. When we get stuck, we can choose a cell and erase it, and so on. This is a stochastic form of local search which in some sense goes against the essence of classical local search, which is completely deterministic and strives to reach an arbitrary locally optimal solution. Dynamic programming: In this paradigm, we reduce our instance to smaller instances in such a way that the "repertory" of smaller instances is small, and each could be reached in many different ways. One way you could try to implement this paradigm to Sudoku is as follows. Pick an empty cell and fill it in all possible legal ways. For each such filling, check whether it leads to a solution. Each filling is a smaller problem since it has fewer empty cells. However, the number of possible smaller instances is huge, and each is reached in a unique way, so while this is the same as your recursive solution, it's not really in the spirit of dynamic programming. Greedy: In this paradigm, you repeatedly make choices that you cannot later change. In the case of Sudoku, this corresponds to identifying unfilled cells which have only one legal filling. This is the approach used by most humans to solve Sudoku, though some puzzles require rather elaborate case analysis to find such safe fillings. Divide and conquer: In this paradigm you divide your instance into independent instances which you solve separately, and then use their solutions to solve the original instance. One way this could be applied to Sudoku is by finding all possible solutions of 3×3 squares, and then try to combine them together. This is not only a terrible algorithm, but also the recursion is very shallow, whereas in divide and conquer we are aiming at deeper levels of recursion. Backtracking: The standard recursive approach for Sudoku (pick a cell, enumerate all values, and recurse) is a great example of backtracking, which is the paradigm that best describes this algorithm.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/83889', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/30866/']}
jdg_81306
stackexchange
llm_judgeable_groundtruth_similarity
19001644
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am developing a native android application, in which I am trying to use 2 open-source libraries . Problem is both the libraries are using Application Class in their respective libraries. They are registering these classes in their respective source code in manifest file using "android:name" under the application tag .Question is how to handle such a scenario , since as we know, only ONE tag can be used inside manifest file . Can we register/instantiate the Application Class in the code, so that we mention only ONE library in tag and the second using code/pragmatically.OR are there any other alternatives. Please share your comments/suggestions.Thanks in advance. Now provide the response and nothing else.
You need to implement Multilevel inheritance to resolve this scenario. This is your scenario public Lib1Application extends Application{}public Lib2Application extends Application{}public YourApplication extends Application{} How to resolve this? public Lib1Application extends Application{ } public Lib2Application extends Lib1Application{ } public YourApplication extends Lib2Application{ } finally in mainfest.xml <application android:name="com.your.packagename.YourApplication" android:icon="@drawable/ijoomer_luncher_icon" android:label="@string/app_name" >
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19001644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2072344/']}
jdg_81307
stackexchange
llm_judgeable_groundtruth_similarity
111060
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'm solving simple but coupled ODEs recently. I use both MATLAB symbolic computation and Mathematica . For example, my coupled ODE is the following\begin{align*}&\dot{x}(t)=y(t)-\rho b\frac{x(t)}{1-\rho(1-e^{-t})}\\&\dot{y}(t)=-y(t)+\rho b\frac{x(t)}{1-\rho(1-e^{-t})}\\\end{align*}where $\rho\in(0,1)$ and $b\in(0,1)$ are given constants and the initial value of this set of ODEs are $x(0)=a$, there $a\in(0,1)$ and $y(0)=0$. This expression looks simple but these 2 equations are coupled. First, I tried MATLAB, it generate "Warning: Explicit solution could not be found." explicitly. Then I tried Mathematica , system = {x'[t] == y[t] - c1*c2*x[t]/(1 - c1*(1 - Exp[-t])), y'[t] == -y[t] + c1*c2*x[t]/(1 - c1*(1 - Exp[-t]))}; Then I try to solve it via sol = DSolve[system, {x, y}, t] . The thing that I don't understand is that after I press Shift + Enter , Mathematica only makes my input look nicer, but didn't produce any result or generating any warning message like MATLAB. So I couldn't tell whether it is because Mathematica also couldn't find the analytical solution like MATLAB, or it just does not even try to solve the problem since I input something wrong? This simple coupled ODE drives me crazy these days. Any suggestion, input is deeply appreciated. If math software couldn't find analytical solution, then is it still possible to analyze the monotonicity of the solution? For example, in this case, it's easy to analyze the case when $t=\infty$ by setting $\dot{x}=0=\dot{y}$ and solve the equations. I can also numerically plot the solution to see the trend, e.g., $x(t)$ is decreasing. But without the explicit functional form of $x(t)$, how can we prove the monotonicity, stuff like that? In general, if the math software fails to find analytical solution, what should we do next? Now provide the response and nothing else.
Here, we take advantage of the observation mentioned in a comment that the sum of x and y is conserved. If we define s[t] == x[t] + y[t]d[t] == x[t] - y[t] your differential equations become eqns = {s'[t] == 0, d'[t] == -(1 + (r b)/(1 - (1 - E^-t) r)) d[t] + (1 - (r b)/(1 - (1 - E^-t) r)) s[t]} Mathematica knows how to solve this: First@DSolve[eqns, {s[t], d[t]}, t]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/111060', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/38887/']}
jdg_81308
stackexchange
llm_judgeable_groundtruth_similarity
305886
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: The C++ Core Guidelines have the rule ES.20: Always initialize an object . Avoid used-before-set errors and their associated undefined behavior. Avoid problems with comprehension of complex initialization. Simplify refactoring. But this rule doesn't help to find bugs, it only hides them. Let's suppose that a program has an execution path where it uses an uninitialized variable. It is a bug. Undefined behavior aside, it also means that something went wrong, and the program probably doesn't meet its product requirements. When it will be deployed to production, there can be a money loss, or even worse. How do we screen bugs? We write tests. But tests don't cover 100% of execution paths, and tests never cover 100% of program inputs. More than that, even a test covers a faulty execution path - it still can pass. It's undefined behavior after all, an uninitialized variable can have a somewhat valid value. But in addition to our tests, we have the compilers which can write something like 0xCDCDCDCD to uninitialized variables. This slightly improves detection rate of the tests. Even better - there are tools like Address Sanitizer, which will catch all the reads of uninitialized memory bytes. And finally there are static analyzers, which can look at the program and tell that there is a read-before-set on that execution path. So we have many powerful tools, but if we initialize the variable - sanitizers find nothing . int bytes_read = 0;my_read(buffer, &bytes_read); // err_t my_read(buffer_t, int*);// bytes_read is not changed on read error.// It's a bug of "my_read", but detection is suppressed by initialization.buffer.shrink(bytes_read); // Uninitialized bytes_read could be detected here.// Another bug: use empty buffer after read error.use(buffer); There is another rule - if program execution encounters a bug, program should die as soon as possible. No need to keep it alive, just crash, write a crashdump, give it to the engineers for investigation. Initializing variables unnecessarily does the opposite - program is being kept alive, when it would already get a segmentation fault otherwise. Now provide the response and nothing else.
Your reasoning goes wrong on several accounts: Segmentation faults are far from certain to occur. Using an uninitialized variable results in undefined behaviour . Segmentation faults are one way that such behaviour can manifest itself, but appearing to run normal is just as likely. Compilers never fill the uninitialized memory with a defined pattern (like 0xCD). This is something that some debuggers do to assist you in finding places where uninitialized variables get used. If you run such a program outside a debugger, then the variable will contain completely random garbage. It is equally likely that a counter like the bytes_read has the value 10 as that it has the value 0xcdcdcdcd . Even if you are running in a debugger that sets the uninitialized memory to a fixed pattern, they only do so at startup. This means that this mechanism only works reliably for static (and possibly heap-allocated) variables. For automatic variables, which get allocated on the stack or live only in a register, the chances are high that the variable is stored in a location that was used before, so the tell-tale memory pattern has already been overwritten. The idea behind the guidance to always initialize variables is to enable these two situations The variable contains a useful value right from the very beginning of its existence. If you combine that with the guidance to declare a variable only once you need it, you can avoid future maintenance programmers falling in the trap of starting to use a variable between its declaration and the first assignment, where the variable would exist but be uninitialized. The variable contains a defined value that you can test for later, to tell if a function like my_read has updated the value. Without initialization, you can't tell if bytes_read actually has a valid value, because you can't know what value it started with.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/305886', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/7270/']}
jdg_81309
stackexchange
llm_judgeable_groundtruth_similarity
2351951
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: My Algebra $2$ teacher stressed the fact that when you find the inverse $g$ of a function $f$, you must not only check that$$f \circ g=\operatorname{id}$$but you must also check that$$g \circ f=\operatorname{id}$$For example, if $$f(x)=x^2$$then$$g(x)=\sqrt{x}$$is not its inverse, because$$f(g(x))=\sqrt{x^2}=|x|\ne x$$However, I feel that this is minor... $|x|$ is equal to $x$ half of the time (if $x$ is real) and the other half of the time, it is just $-x$. Can anyone think of an example of two functions $f$ and $g$ such that$$f \circ g=\operatorname{id}$$but, when composed in the other order, the result is something totally wacky that is almost never equal to $\operatorname{id}$? Now provide the response and nothing else.
Consider $f:\Bbb R \times \Bbb R \to \Bbb R$ and $g:\Bbb R \to \Bbb R \times \Bbb R $ to be defined by$$f(x,y) = x \qquad g(x) = (x,0)$$Surely, we have $f \circ g = \operatorname{id}_{\Bbb R}$. However, we have $$[g \circ f](x,y) = (x,0)$$which is certainly not the identity on $\Bbb R \times \Bbb R$. I would say it is "almost never" the identity function in the sense that the $x$-axis is an "infinitely small fraction" of the entire $xy$-plane. It is notable that if $f \circ g = \operatorname{id}$, then $g \circ f$ will always be equal to the identity over the range of $g$. In particular: for any $y$ in the range of $g$, we can write $y = g(x)$ for some $x$ in the domain of $g$, and so we have$$[g \circ f](y) = [g \circ f](g(x)) = g([f \circ g](x)) = g(\operatorname{id}(x)) = g(x) = y$$You may want to verify that $f$ will have a "left-inverse" in this sense if and only if it is injective (one-to-one), just as $g$ will have a "right-inverse" in this sense if and only if it is surjective (onto). We can conclude from all this that if $f,g: \Bbb R \to \Bbb R$ are such that $f \circ g = \operatorname{id}$, then we will have $g \circ f = \operatorname{id}$ on at least some uncountable subset of $\Bbb R$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2351951', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/438055/']}
jdg_81310
stackexchange
llm_judgeable_groundtruth_similarity
29074184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code: var studentClassAttendancesGrouped = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id).GroupBy(x => new { x.Lecture, x.Teacher }); I am trying to return studentClassAttendancesGrouped from a method.But I can not determine the return type of the method. Now provide the response and nothing else.
This overload of the GroupBy will return IEnumerable<IGrouping<TKey, TSource>> as seen from the source code . You just need to project your enumerable with the Select() and of course you must call ToList() at the end to execute the query and create a list: var res = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id) .GroupBy(x => new { x.Lecture, x.Teacher }) .Select(x => new {x.Key.Lecture, x.Key.Teacher}) .ToList(); But, the above code creates a list of the anonymous types. If you are going to return the above statement from the method, then you need to use or to create a custom object and return the list of this: public class LectureTeacher{ public string Lecture { get; set; } public string Teacher { get; set; }}public List<LectureTeacher> GetDogsWithBreedNames(){ var res = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id) .GroupBy(x => new { x.Lecture, x.Teacher }) .Select(x => new LectureTeacher {Lecture = x.Key.Lecture, Teacher = x.Key.Teacher}) .ToList(); return res;} By the way, GroupBy has several other overloads which you can specify result selector and it will return IEnumerable to you: myList.OrderBy(x => x.Lecture.Id) .GroupBy(x => new { x.Lecture, x.Teacher } //key selector key => new LectureTeacher // result selector { Lecture = key.Lecture, Teacher = key.Teacher }) .ToList();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29074184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3801163/']}
jdg_81311
stackexchange
llm_judgeable_groundtruth_similarity
5702610
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an application that has to load XML document and output nodes depending on XPath. Suppose I start with a document like this: <aaa> ...[many nodes here]... <bbb>text</bbb> ...[many nodes here]... <bbb>text</bbb> ...[many nodes here]...</aaa> With XPath //bbb So far everything is nice. And selection doc.SelectNodes("//bbb"); returns the list of required nodes. Then someone uploads a document with one node like <myfancynamespace:foo/> and extra namespace in the root tag, and everything breaks. Why? //bbb does not give a damn about myfancynamespace , theoretically it should even be good with //myfancynamespace:foo , as there is no ambiguity, but the expression returns 0 results and that's it. Is there a workaround for this behavior? I do have a namespace manager for the document, and I am passing it to the Xpath query. But the namespaces and the prefixes are unknown to me, so I can't add them before the query. Do I have to pre-parse the document to fill the namespace manager before I do any selections? Why on earth such behavior, it just doesn't make sense. EDIT: I'm using: XmlDocument and XmlNamespaceManager EDIT2: XmlDocument doc = new XmlDocument();doc.XmlResolver = null;XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);//I wish I could://nsmgr.AddNamespace("magic", "http://magicnamespaceuri///...doc.LoadXML(usersuppliedxml);XmlNodeList nodes = doc.SelectNodes(usersuppliedxpath, nsmgr);//usersuppliedxpath -> "//bbb"//nodes.Count should be > 0, but with namespaced document they are 0 EDIT3: Found an article which describes the actual scenario of the issue with one workaround, but not very pretty workaround: http://codeclimber.net.nz/archive/2008/01/09/How-to-query-a-XPath-doc-that-has-a-default.aspx Almost seems that stripping the xmlns is the way to go... Now provide the response and nothing else.
You're missing the whole point of XML namespaces. But if you really need to perform XPath on documents that will use an unknown namespace, and you really don't care about it, you will need to strip it out and reload the document. XPath will not work in a namespace-agnostic way, unless you want to use the local-name() function at every point in your selectors. private XmlDocument StripNamespace(XmlDocument doc){ if (doc.DocumentElement.NamespaceURI.Length > 0) { doc.DocumentElement.SetAttribute("xmlns", ""); // must serialize and reload for this to take effect XmlDocument newDoc = new XmlDocument(); newDoc.LoadXml(doc.OuterXml); return newDoc; } else { return doc; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5702610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459930/']}
jdg_81312
stackexchange
llm_judgeable_groundtruth_similarity
26587659
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to import an excel sheet into r. I used the following code: x <- loadWorkbook("x.xlsx")b <- readWorksheet(x, sheet="b") The first line works fine, however, running the second gives the following error: Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘readWorksheet’ for signature ‘"jobjRef", "character"’ I have no missing values in that sheet. For the purpose of reproducing, download trial.xlsx from https://github.com/ahmedfsalhin/1stpaper . system info: Yosemite operating system. Now provide the response and nothing else.
It appears the "root cause" is that you should add code to specify both the function and the package it belongs to. Type XLConnect::loadWorkbook to select the one you want in this case. There's no 'confusion,' or random selection of duplicated function names in R . The choice depends on the load order of all loaded packages. Use search() to see the order in which packages are checked for the command you've entered. E.g., at present I get search() [1] ".GlobalEnv" "package:caTools" [3] "package:XLConnect" "package:XLConnectJars" [5] "package:stats" "package:graphics" [7] "package:datasets" "package:vecsets" [9] "package:cgwtools" "package:grDevices" [11] "package:utils" "package:methods" [13] "Autoloads" "package:base" You'll notice that anything in your environment ( .GlobalEnv ) is selected first, and that all loaded libraries override the base package, for example.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26587659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3590384/']}
jdg_81313
stackexchange
llm_judgeable_groundtruth_similarity
281581
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am investigating the vulnerability to Slowloris and I think I understand how and why this sort of attack works. What I don't understand is why Lighttpd and NginX are not affected (according to the same article as linked above). What do they make so different? Now provide the response and nothing else.
Apache has a theory of 'Maximum Clients' That is the number of simultaneous connections it can handle. I.E. if an apache server has a 'max clients' limit of 100, and each request takes 1 second to complete, it can handle a maximum of 100 requests per second. An application like SlowLoris will flood a server with connections, in our example if SlowLoris sends 200 connections per second, and Apache can only handle 100 connections per second the connection queue will keep getting bigger and use up all the memory on the machine bringing it to a hault. This is similar to the way Anonymous' LOIC works. NGINX and Lighttpd (Among others) don't have a maximum connections, they use worker threads instead so, theoretically, there's no limit to the number of connections they can handle. If you monitor your Apache connections, you'll see that the majority of the active connections are 'Sending' or 'Receiving' data from the client. In NGINX/Lighttpd they just ignore these requests and let them run on in the background, not using up system resources, and it only has to process connections with something going on (Parsing responses, reading data from backend servers etc.) I actually answered a similar question this afternoon, so the information in there might also be interesting to you Reducing Apache request queuing
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/281581', 'https://serverfault.com', 'https://serverfault.com/users/53998/']}
jdg_81314
stackexchange
llm_judgeable_groundtruth_similarity
14466498
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From what I've read: Table or Views data access mode commits each row at a time as a transaction. Thus, making a package transferring 5 million rows take long (30+ minutes). Fast-load data access mode allows one to specify the batch rows and the commit size when inserting to destination. For example, inserting 5 million records would take just over 2 minutes. Now the question arises where one of the SSIS packages that loads to the DW uses Table or View data access mode in the OLE DB destination. From my understanding, this is in order to pick up the error rows which it inserts (error constraint) into an error records table. Thus, we have a process that takes over 30 minutes. In turn, Fast-Load would take less than 2 minutes for the same action. If I understand correctly, fast-load would be unable to differentiate which row caused the error in the batch which in turn fails the batch completely? If so, is there an alternative method to this situation where the batch with the error row is redirected by the error constraint and then worked into the destination in a way where the good records in the batch are sent to the correct destination while still sending the error record into the error log table? Is it a good idea to even do so? Is it better to bite the bullet sort of speak in regards to the amount of time it takes? Thank you in advance. Now provide the response and nothing else.
What I've seen done in that situation is a cascading failure approach. Attempt to insert into the OLE DB Destination in successively smaller batches to try and get as much in via batch mode before you start the singleton inserts. Assume you have a commit size of 10k rows (arbitrary number, test for your situation, etc). Redirect failing rows to an OLE DB Destination, still in Fast Load mode but with a commit size of 2.5k rows. Add yet another ole db destination, with a commit size of maybe 100 and then have a final destination that is in RBAR mode. You can then identify the failing rows and do whatever needs to be done with them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14466498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1485709/']}
jdg_81315
stackexchange
llm_judgeable_groundtruth_similarity
2931640
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: While reading the proof of Cauchy-schwarz inequality, I didn't get one step. The step is as below, by positivity axiom, for any real number $t$ $0≤⟨tu+v,tu+v⟩=⟨u,u⟩t^2+ 2⟨u,v⟩t+⟨v,v⟩$ This imply $$0≤at^2 + bt+c$$ where $a=⟨u,u⟩$ , $b=2⟨u,v⟩$ and $c=⟨v,v⟩$ After this they had written, this inequality implies that the quadratic polynomial has either no real roots or repeated real roots! I didn't get this! How the quadratic polynomial $at^2 + bt+c$ has either no real roots or repeated real root? Now provide the response and nothing else.
We need that $at^2 + bt+c\ge 0,\, a\ge 0$ and this is true if and only if $$b^2-4ac \le 0$$ indeed recall that by quadratic formula $$t=\frac{-b\pm \sqrt{b^2-4ac}}{2a}$$ and the cases $b^2-4ac=0$ corresponds to repeated roots and the parabola $y=at^2+bt+c$ is tangent to $x$ axis $b^2-4ac<0$ corresponds to no real roots and the parabola $y=at^2+bt+c$ is above to $x$ axis Refer also to the related: Quadratic Equation with imaginary roots.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2931640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/168676/']}
jdg_81316
stackexchange
llm_judgeable_groundtruth_similarity
52150
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: Given a series, how does one calculate that limit below? I noticed the numerator is an arithmetic progression and the denominator is a geometric progression — if that's of any relevance —, but I still don't know how to solve it. $$\lim_{n\to\infty} \sum^n_{k=0} \frac{k+1}{3^k}$$ I did it "by hand" and the result should be $\frac{9}{4}.$ Now provide the response and nothing else.
Let $X$ be a geometric random variable with probability of success $p=2/3$, so that$${\rm P}(X=k)=(1-p)^{k-1}p = \frac{2}{{3^k }}, \;\; k=1,2,3,\ldots.$$From the easy-to-remember fact that ${\rm E}(X)=1/p$, it follows that$$\frac{3}{2} + 1 = {\rm E}(X) + 1 = {\rm E}(X + 1) = \sum\limits_{k = 1}^\infty {(k + 1){\rm P}(X = k) = 2\sum\limits_{k = 1}^\infty {\frac{{k + 1}}{{3^k }}} } .$$Hence$$\sum\limits_{k = 1}^\infty {\frac{{k + 1}}{{3^k }}} = \frac{5}{4}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/52150', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9094/']}
jdg_81317
stackexchange
llm_judgeable_groundtruth_similarity
25965023
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 read this to understand more the difference between top down and bottom up parsing, can anyone explain the problems associated with left recursion in a top down parser? Now provide the response and nothing else.
In a top-down parser, the parser begins with the start symbol and tries to guess which productions to apply to reach the input string. To do so, top-down parsers need to use contextual clues from the input string to guide its guesswork. Most top-down parsers are directional parsers, which scan the input in some direction (typically, left to right) when trying to determine which productions to guess. The LL(k) family of parsers is one example of this - these parsers use information about the next k symbols of input to determine which productions to use. Typically, the parser uses the next few tokens of input to guess productions by looking at which productions can ultimately lead to strings that start with the upcoming tokens. For example, if you had the production A → bC you wouldn't choose to use this production unless the next character to match was b. Otherwise, you'd be guaranteed there was a mismatch. Similarly, if the next input character was b, you might want to choose this production. So where does left recursion come in? Well, suppose that you have these two productions: A → Ab | b This grammar generates all strings of one or more copies of the character b. If you see a b in the input as your next character, which production should you pick? If you choose Ab, then you're assuming there are multiple b's ahead of you even though you're not sure this is the case. If you choose b, you're assuming there's only one b ahead of you, which might be wrong. In other words, if you have to pick one of the two productions, you can't always choose correctly. The issue with left recursion is that if you have a nonterminal that's left-recursive and find a string that might match it, you can't necessarily know whether to use the recursion to generate a longer string or avoid the recursion and generate a shorter string. Most top-down parsers will either fail to work for this reason (they'll report that there's some uncertainty about how to proceed and refuse to parse), or they'll potentially use extra memory to track each possible branch, running out of space. In short, top-down parsers usually try to guess what to do from limited information about the string. Because of this, they get confused by left recursion because they can't always accurately predict which productions to use. Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25965023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2547848/']}
jdg_81318
stackexchange
llm_judgeable_groundtruth_similarity
32685819
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 spring boot (I use Thymeleaf for templating) project where I want to use some jQuery libraries. Unfortunately, the webjars aren't loading at all. I have tried many configuration but all of them failed. Here is the code snippet of my HTML page: <!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head lang="en"><title>JAC</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.js" th:src="@{/webjars/jquery/2.1.4/jquery.min.js}" type="text/javascript"></script><script src="http://cdn.jsdelivr.net/webjars/jquery-file-upload/9.10.1/jquery.fileupload.js" type="text/javascript" th:src="@{/webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js}"></script><link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.5/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}" rel="stylesheet" media="screen" /><link href="http://cdn.jsdelivr.net/webjars/jquery-file-upload/9.10.1/jquery.fileupload.css" rel="stylesheet" media="screen" /></head> I have added them in the pom file: <dependency> <groupId>org.webjars.npm</groupId> <artifactId>jquery</artifactId> <version>2.1.4</version></dependency><dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.5</version></dependency><dependency> <groupId>org.webjars</groupId> <artifactId>jquery-file-upload</artifactId> <version>9.10.1</version></dependency> But when calling the page I got a 404 on jquery.min.js and jquery.fileupload.min.js. GET http://localhost:8888/webjars/jquery-file-upload/9.10.1/jquery.fileupload.min.js 2015-09-21 02:02:04.059 home:9 GET http://localhost:8888/webjars/jquery/2.1.4/jquery.min.js 404 (Not Found) Now provide the response and nothing else.
You are referencing jquery library correctly. Maybe you are missing resource handler configuration. <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/> Or if you use JavaConfig @Configurationpublic class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); }} Webjars documentation If this will not work, please check if you have webjars on classpath (open your application JAR in 7Zip and check if webjars resources are inside it.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32685819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4726477/']}
jdg_81319
stackexchange
llm_judgeable_groundtruth_similarity
1059674
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 very large listSuppose I do that (yeah, I know the code is very unpythonic, but for the example's sake..): n = (2**32)**2for i in xrange(10**7) li[i] = n works fine. however: for i in xrange(10**7) li[i] = i**2 consumes a significantly larger amount of memory. I don't understand why that is - storing the big number takes more bits, and in Java, the the second option is indeed more memory-efficient... Does anyone have an explanation for this? Now provide the response and nothing else.
Java special-cases a few value types (including integers) so that they're stored by value (instead of, by object reference like everything else). Python doesn't special-case such types, so that assigning n to many entries in a list (or other normal Python container) doesn't have to make copies. Edit: note that the references are always to objects , not "to variables" -- there's no such thing as "a reference to a variable" in Python (or Java). For example: >>> n = 23>>> a = [n,n]>>> print id(n), id(a[0]), id(a[1])8402048 8402048 8402048>>> n = 45>>> print id(n), id(a[0]), id(a[1])8401784 8402048 8402048 We see from the first print that both entries in list a refer to exactly the same object as n refers to -- but when n is reassigned, it now refers to a different object, while both entries in a still refer to the previous one. An array.array (from the Python standard library module array ) is very different from a list: it keeps compact copies of a homogeneous type, taking as few bits per item as are needed to store copies of values of that type. All normal containers keep references (internally implemented in the C-coded Python runtime as pointers to PyObject structures: each pointer, on a 32-bit build, takes 4 bytes, each PyObject at least 16 or so [including pointer to type, reference count, actual value, and malloc rounding up]), arrays don't (so they can't be heterogeneous, can't have items except from a few basic types, etc). For example, a 1000-items container, with all items being different small integers (ones whose values can fit in 2 bytes each), would take about 2,000 bytes of data as an array.array('h') , but about 20,000 as a list . But if all items were the same number, the array would still take 2,000 bytes of data, the list would take only 20 or so [[in every one of these cases you have to add about another 16 or 32 bytes for the container-object proper, in addition to the memory for the data]]. However, although the question says "array" (even in a tag), I doubt its arr is actually an array -- if it were, it could not store (2**32)*2 (largest int values in an array are 32 bits) and the memory behavior reported in the question would not actually be observed. So, the question is probably in fact about a list, not an array. Edit : a comment by @ooboo asks lots of reasonable followup questions, and rather than trying to squish the detailed explanation in a comment I'm moving it here. It's weird, though - after all, how is the reference to the integer stored? id(variable) gives an integer, the reference is an integer itself, isn't it cheaper to use the integer? CPython stores references as pointers to PyObject (Jython and IronPython, written in Java and C#, use those language's implicit references; PyPy, written in Python, has a very flexible back-end and can use lots of different strategies) id(v) gives (on CPython only) the numeric value of the pointer (just as a handy way to uniquely identify the object). A list can be heterogeneous (some items may be integers, others objects of different types) so it's just not a sensible option to store some items as pointers to PyObject and others differently (each object also needs a type indication and, in CPython, a reference count, at least) -- array.array is homogeneous and limited so it can (and does) indeed store a copy of the items' values rather than references (this is often cheaper, but not for collections where the same item appears a LOT, such as a sparse array where the vast majority of items are 0). A Python implementation would be fully allowed by the language specs to try subtler tricks for optimization, as long as it preserves semantics untouched, but as far as I know none currently does for this specific issue (you could try hacking a PyPy backend, but don't be surprised if the overhead of checking for int vs non-int overwhelms the hoped-for gains). Also, would it make a difference if I assigned 2**64 to every slot instead of assigning n, when n holds a reference to 2**64 ? What happens when I just write 1? These are examples of implementation choices that every implementation is fully allowed to make, as it's not hard to preserve the semantics (so hypothetically even, say, 3.1 and 3.2 could behave differently in this regard). When you use an int literal (or any other literal of an immutable type), or other expression producing a result of such a type, it's up to the implementation to decide whether to make a new object of that type unconditionally, or spend some time checking among such objects to see if there's an existing one it can reuse. In practice, CPython (and I believe the other implementations, but I'm less familiar with their internals) uses a single copy of sufficiently small integers (keeps a predefined C array of a few small integer values in PyObject form, ready to use or reuse at need) but doesn't go out of its way in general to look for other existing reusable objects. But for example identical literal constants within the same function are easily and readily compiled as references to a single constant object in the function's table of constants, so that's an optimization that's very easily done, and I believe every current Python implementation does perform it. It can sometimes be hard to remember than Python is a language and it has several implementations that may (legitimately and correctly) differ in a lot of such details -- everybody, including pedants like me, tends to say just "Python" rather than "CPython" when talking about the popular C-coded implementation (excepts in contexts like this one where drawing the distinction between language and implementation is paramount;-). Nevertheless, the distinction is quite important, and well worth repeating once in a while.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1059674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115579/']}
jdg_81320
stackexchange
llm_judgeable_groundtruth_similarity
255241
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 tutor students studying for an exam where they are likely to be asked to recognise a circuit, with a single transistor, as one of: a) a common base amplifier; b) a common emitter amplifier: c) a common collector amplifier. Is there a mnemonic or other easily remembered way to distinguish them? Now provide the response and nothing else.
CE does not use E as the direct input CB does not use B as the direct input CC does not use C as the output The word "common" means that the pin-name following cannot be either a direct input or an output. For all three types you can always say B is never an output and C is never an input. Thus CE (for instance) implies the input is at B and the output is at C.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/255241', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6361/']}
jdg_81321
stackexchange
llm_judgeable_groundtruth_similarity
24716
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: Im a total beginner. I bought an arduino starter kit and this is the first sample program - it makes an LED blink. The accompanying text gives no theory about what is happening in the sample programs so I have a couple of questions. What is the function of the resistor here? Why is it a 560 ohm resistor (as opposed to 2 ohms or 20000 ohms)? The circuit starts from arduino pin 13 that I understand puts out a voltage of 5 Volts. But the circuit then ends at gnd. I thought circuits were supposed to loop around so that the currently will keep flowing non-stop? What is the reason for the circuit terminating at gnd? Here is the circuit - Now provide the response and nothing else.
In brief: The resistor in this circuit is a "Current Limiting Resistor" The resistance is dependent on the forward voltage drop and current requirements of the LED. Ground forms part of the circuit. The microcontroller is also connected to ground. It is a reference point that all other voltages in the circuit are measured against. In more detail: The LED requires a certain amount of current to light up. It also has a certain voltage that it operates. These are never the same as the 5v Arduino puts out through its IO pins. So, if the LED has a forward voltage of 2.2V and a maximum current rating of 25mA, and the Arduino puts out 5V, then we need to lose some of that voltage to get it down to 2.2V. The resistor does this for us. We calculate the value of the resistor by using Ohm's Law, which states that: \$R=\frac{V}{I}\$ Or, the resistance is the voltage divided by the current. So, for our LED of 2.2V we will need to lose 2.8V using the resistor. The LED can draw 25mA (max without burning up), as noted above. So, we can put those values into our Ohm's Law formula: \$R=\frac{2.8}{0.025}\$ Which gives us the answer 112Ω For the LED I picked at random above, you'd use a 112Ω resistor to stop it from going pop . As they don't make 112Ω resistors commonly (you can get any value made, but they cost shed loads), the next value up is chosen - typically 120Ω. Without knowing the exact specs of your LED it's impossible to know exactly what resistor should be used, but a higher value resistor is safer than a lower value one (it just may not light up as bright) and around the 500Ω area is a reasonable value to cover most LEDs. As for the ground connection - that is just another wire - the "return" connection that keeps the current in a loop. Just because it's called "ground" it doesn't make it special - it's just a reference point. The 5V in the circuit is actually "5V With Reference to Ground". All parts of the circuit marked with the ground symbol are all connected together - it just saves drawing in the wires.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/24716', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7398/']}
jdg_81322
stackexchange
llm_judgeable_groundtruth_similarity
294299
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 created an Ajax website in Visual Studio, added a simple page with a textbox and button, when I click the button once everything works, when I click it twice I get the error Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500 Here is my page <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <div> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </ContentTemplate> </asp:UpdatePanel> </div></form> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) TextBox1.Text = "aaa" End Sub Edit ~ I added a second button to the page, outside of the update panel and when I clicked the one inside the update panel and then the one outside of the panel I got the error Cannot open database "ASPState" requested by the login. The login failed.Login failed for user 'server\user'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Cannot open database "ASPState" requested by the login. The login failed.Login failed for user 'server\user'. Why is this? Edit ~ To resolve my issue I did <sessionState mode="StateServer"stateConnectionString="tcpip=localhost:42424"cookieless="false"timeout="20"/> Now provide the response and nothing else.
Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments). I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL . // LZW-compress a stringfunction lzw_encode(s) { var dict = {}; var data = (s + "").split(""); var out = []; var currChar; var phrase = data[0]; var code = 256; for (var i=1; i<data.length; i++) { currChar=data[i]; if (dict[phrase + currChar] != null) { phrase += currChar; } else { out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0)); dict[phrase + currChar] = code; code++; phrase=currChar; } } out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0)); for (var i=0; i<out.length; i++) { out[i] = String.fromCharCode(out[i]); } return out.join("");}// Decompress an LZW-encoded stringfunction lzw_decode(s) { var dict = {}; var data = (s + "").split(""); var currChar = data[0]; var oldPhrase = currChar; var out = [currChar]; var code = 256; var phrase; for (var i=1; i<data.length; i++) { var currCode = data[i].charCodeAt(0); if (currCode < 256) { phrase = data[i]; } else { phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar); } out.push(phrase); currChar = phrase.charAt(0); dict[code] = oldPhrase + currChar; code++; oldPhrase = phrase; } return out.join("");}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/294299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23667/']}
jdg_81323
stackexchange
llm_judgeable_groundtruth_similarity
4722935
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created view page in MVC like <%using (Html.BeginForm()){ %> <%=LabelHelpers.Label("firstname", "FirstName:")%> <br/> <%=Html.TextBox("firstname")%> <br/><br/> <%=LabelHelpers.Label("lastname", "Lastname:")%> <br/> <%=Html.TextBox("lastname")%> <br/><br/> <input type="Button" value="Register"/><%} %> Here I want to write Buttonclick Event ...How and Where should i write? Now provide the response and nothing else.
Your input is of type button - these don't do anything without additional client side code. If you want to handle the 'event' on the server in a similar way that you would have in ASP.NET, you should convert it to a submit button. Assuming your controller is called 'Account' and your action is called 'Register' your current code would look something like this: public ViewResult Register(){ return View();} You want to start by passing a model to the view: public ViewResult Register(){ var registerModel = new RegisterModel(); return View(registerModel);} Your current view is using loosely typed inputs. Since you're passing it a model you can use strongly typed views. Your model should look something like this: public class RegisterMode{ public string Firstname { get; set; } public string Surname { get; set; }} To use strongly typed views, change your view to look like this: <%using (Html.BeginForm()){ %> <%=Html.LabelFor(x => x.Firstname)%> <br/> <%=Html.TextBoxFor(x => x.Firstname)%> <br/><br/> <%=Html.LabelFor(x => x.Surname)%> <br/> <%=Html.TextBoxFor(x => x.Surname)%> <br/><br/> <input type="submit" value="Register"/><%} %> What we've done is told the view to build labels and text boxes for your RegisterModel type. This will allow the model values to be automatically mapped when you POST the form to the controller. Do accept the post, we need to add a new Action to the controller, with the same name, but accepting a parameter of type RegisterModel: public ActionResult Register(RegisterModel model){ // do something with the model, such as inserting it into the database. // model.Firstname will contain the value of the firstname textbox // model.Surname will contain the value of the surnaem textbox return RedirectToAction("Success");} One last thing to do, to be safe, is to add the [HttpGet] and [HttpPost] attributes to your controller actions to control the methods they accept: [HttpGet]public ViewResult Register() and [HttpPost]public ActionResult Register(RegisterModel model) I suggest you read up on MVC at http://www.asp.net/mvc and read the NerdDinner tutorial chapter in Professional MVC (available for free online in PDF format).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4722935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/579688/']}
jdg_81324
stackexchange
llm_judgeable_groundtruth_similarity
2715198
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Why would you ever want to allocate memory on the heap rather than the stack? Test2 *t2 = new Test2();t2->test();Test2 t3;t3.test(); Why would I want to create a pointer object of type Test2? Why not just do non pointer version of Test2? Why would I want to do pointer objects? Found answer here: Why would you ever want to allocate memory on the heap rather than the stack? When is it best to use a stack instead of a heap and vice versa? When to use "new" and when not to in C++? When should I use the new keyword in C++? Proper stack and heap usage in C++ Stack, Static and Heap in C++ Now provide the response and nothing else.
The reasons to use dynamic storage include (but probably not limited to) Manual control of the objects lifetime - the object will live until you explicitly destroy it Creating as many objects as necessary, when the final number of objects is only known at run-time (like number of nodes in a tree or number of elements in an array). Run-time control of the object's type (like actual type of polymorphic object). When it makes no difference, it is always better to create the object using your t3 method. Don't use dynamic memory unless you have to. But sometimes you really have to (see the reasons above).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2715198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_81325
stackexchange
llm_judgeable_groundtruth_similarity
573356
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Not as stupid as it sounds ;) I have a third party app that I have no source for. Official support is for XP and higher - but higher only with UAC off. Which I do not want. Now, I know the programmers and they are willing to make a change if it is not too much work and I can tell them WHAT Needs to be done. I know that the app, which starts multiple executables, does not get network connection when I start it without elevated priviledges - but it seems no port that is open is in the loer range (as per netstat -b Is there any guideline on trying to find out WHY an app needs elevated priviledges? THe applicaiton is business critical - and this currently subverts secutiry as users must be local admins. If anyone has an idea - once I find the reason I am sure I can get the vendor implement a change. Now provide the response and nothing else.
As per one of the comments, your best bet is likely to be using Sysinternals' Process Monitor to see what is being tried and failing due UAC. Download Process Monitor from http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx Run process monitor, run your borked, obsolete, badly coded app, go to process monitor > filter > if Process Name is <borkedapp> then Include and if Result is Success then Exclude which should give you a mere few thousand entries to scan for the bit that is failing. Alternatively there is a tool linked below (I have not tried it) that will help you compare process monitor traces so you can take a trace running as standard user and another running elevated and compare them. http://forum.sysinternals.com/tool-for-comparing-procmon-traces_topic28870.html https://github.com/patraulea/LogDiff
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/573356', 'https://serverfault.com', 'https://serverfault.com/users/37059/']}
jdg_81326
stackexchange
llm_judgeable_groundtruth_similarity
55380193
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 a weird error while trying to navigate to different routes from a specific component. If I navigate to different routes from other components I am not seeing this error.I am attaching the screenshot of the error I have searched for this issue and seems to be the problem with RxJS or empty routes. But I added pathMatch:'full' to empty routes and my RxJS version is 6.3.3 . Any idea or anyone out here resolved the same issue could be of great help. Now provide the response and nothing else.
EmptyError is thrown by the first pipe if the source observable is closed before it could emit any notification. Your stack trace shows that TextblockComponent triggers a takeUntil pipe in its ngOnDestroy function, which usually closes an Observable. It can be assumed that this closes the Observable that has the first pipe and thus causes an EmptyError . The error can be circumvented by using take(1) instead of first() .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55380193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2617509/']}
jdg_81327
stackexchange
llm_judgeable_groundtruth_similarity
16654094
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Preface I'm trying to create a responsive website with a navigation menu that satisfies the following two requirements: Navigation is fully visible in a normal browser window, laid out horizontally. Navigation becomes a toggleable vertical menu for mobile devices and small screens, which animates between its "opened" and "closed" state. I want performance to be good on mobile devices — especially on iOS — which means that the animation should use a GPU-accelerated translate3d transform CSS transition. My Problem Setting this up was a piece of cake, and for the most part it works great. I used z-index: 1 and transform: translate3d(0,-100%,0) to hide the menu behind a header with z-index: 2 in its default closed state, and then transform: translate3d(0,0,0) to animate the menu to its opened state. But I'm just having one problem: When I resize my Chrome browser window and the mobile media query kicks in, the menu animates from an opened to closed state. Resize your browser window to less than 600px wide to see the problem in action: Fullscreen jsfiddle: http://fiddle.jshell.net/ymDYG/1/show/ Original jsfiddle: http://jsfiddle.net/ymDYG/1/ I think I know why this is happening: when the mobile media query kicks in, the browser sees that .nav is not currently active, so it animates it to the default closed state. I've tried experimenting with using display:none and display:block for the different media query states, but that seems to completely break the animation. How can I prevent the nav menu's "closing" animation from firing as the browser window is resized? Now provide the response and nothing else.
Nice job, very clean. Can i steal it? :-) Anyway, here's your solution with a demo . I just moved the transition to another class: .nav { /* stuff */ z-index: 1; transform: translate3d(0,-100%,0); -webkit-transform: translate3d(0,-100%,0);}.nav.active { transform: translate3d(0,0,0); -webkit-transform: translate3d(0,0,0);}.nav.activated { transition: transform 400ms linear; -webkit-transition: -webkit-transform 400ms linear;} Which you can add to the element at first "Toggle": function toggle(){ $(".nav").addClass("activated").toggleClass("active");} P.S. If you don't want the transition to happen even after the user has opened the menu and then resized the window again, you could use Modernizr's mq method : $(window).on('resize',function(){ if(Modernizr.mq('(min-width:600px)')) $(".nav").removeClass("activated");});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16654094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136590/']}
jdg_81328
stackexchange
llm_judgeable_groundtruth_similarity
906702
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: Consider the set of all even numbers larger than $2$. Goldbach's conjecture states that every element is the sum of a pair of prime numbers. It has not been proved that all elements abide to that rule. But it is trivial to show that there are infinitely many elements that do. My question is as follows: Are there infinitely many even numbers that are the sum of at most one pair of prime numbers? If no, what is the largest known even number which is the sum of only one pair of prime numbers? The general motivation behind this question is this: Among all even numbers, some can be represented by only $1$ pair of prime numbers, some can be represented by $2$ different pairs of prime numbers, and so forth. So we can split the infinite set of even numbers into disjoint subsets. There are three options with regards to the cardinality of these subsets: All of them are finite All of them are infinite Some are finite and some are infinite My intuition tells me that either one of the first two options is correct. Now provide the response and nothing else.
Heuristic reasoning (as well as numerical evidence) suggests that all of them are finite. Here is a discussion, with a couple of nice graphs. Here is a more focused article. It looks like 12 is the largest even integer that can be expressed in only one way as a sum of two primes. Checking this up to some largish number (say, 1000000), and finding the corresponding maxima of your other subsets over that range, would make a nice programming exercise, which I might try when I have time.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/906702', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131263/']}
jdg_81329
stackexchange
llm_judgeable_groundtruth_similarity
34324415
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 TFS project at $/src/main/MyProject/MyProject.csproj It has a reference to a DLL at $/dependencies/dependency.dll. The way I want things to work is that when my colleagues get MyProject, or open it in Visual Studio, I want TFS to go get the latest dependency.dll as well. (In a similar way, I've actually bound MyProject to my solution in $/src/main/MySolution/MySolution.sln. So if a user gets MySolution and opens MySolution.sln then Visual Studio will go get MyProject as well. I just want to extend this to the next level, that of binding a file to a project.) Now provide the response and nothing else.
The first problem is a simple typo. Java is case sensitive, so cube and Cube mean different things. Solution: 1) be consistent, and 2) use names starting with lowercase letters for method names ... as per the Java style guides. The second problem is due to the method signature for Math.pow ; see the javadoc . It returns the result as a double . You then attempte to return the double as an int , and that is a lossy conversion. The solutions include: return b * b * b; // i.e. don't use `pow`. or return (int) Math.pow(b, 3); The second one directly addresses your compilation error by casting the double return to an int . This is the way you tell the compiler that the lossy conversion is actually OK. The lossy conversion error message you are seeing refers to that fact for large enough values of b , the result of Math.pow(b, 3) will be too large to be represented as an int 1 . With the type cast in place, Java will convert a floating point number that is "too large" into Integer.MAX_VALUE . The first solution is faster and simpler code, but if b is too large, the calculations will silently overflow and you will get a nonsense answer. UPDATE - If you wanted overflow to always be treated as an error then: return Math.multiplyExact(b, Math.multiplyExact(b, b)); or return Math.toIntExact((long) Math.pow(b, 3)); or variations on the above. 1 - Actually, the compiler doesn't know about the semantics of pow , so it doesn't know about "... for large enough values of b ..." . But it does know that if the method call did return a large enough value, then the conversion would be lossy. That's why the message says " possible lossy conversion" .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34324415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3038796/']}
jdg_81330
stackexchange
llm_judgeable_groundtruth_similarity
3290162
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The question is Find the number of real roots of the equation $(x-1)x(x+1)(x+2)-1=0$ I simply tried to simplify the equation but it transforms into biquadratic which becomes really tough to conclude anything from it.My second approach was :- $y=(x^2-1) ;$ $y=\frac{1}{(x^2+3x+2)}$ Then i tried to find their intersection but i failed Please help to solve the question without using any tools (like wolfram) other than pure mathematics since it is subjective mathematical paper's question which needs a proper solution. Now provide the response and nothing else.
The function is symmetric about $x = -{1 \over 2}$ since the zeroes of $(x+2)(x+1)x(x-1)$ are at $-2,-1,0,$ and $1$ . So letting $y = x + {1 \over 2}$ the polynomial is $$(y-{1 \over 2})(y + {1 \over 2})(y - {3 \over 2})(y + {3 \over 2}) - 1$$ $$ = y^4 - {5 \over 2}y^2 - {7 \over 16}$$ This is a quadratic equation in $y^2$ , so you can find all possible $y$ easily, and from that the number of solutions $x$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3290162', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/663538/']}
jdg_81331
stackexchange
llm_judgeable_groundtruth_similarity
26287130
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 convert a list into JSON array. I'm looking at jq for this but the examples are mostly about parsing JSON (not creating it). It would be nice to know proper escaping will occur. My list is single line elements so the new line will probably be the best delimiter. Now provide the response and nothing else.
I was also trying to convert a bunch of lines into a JSON array, and was at a standstill until I realized that -s was the only way I could handle more than one line at a time in the jq expression, even if that meant I'd have to parse the newlines manually. jq -R -s -c 'split("\n")' < just_lines.txt -R to read raw input -s to read all input as a single string -c to not pretty print the output Easy peasy. Edit: I'm on jq ≥ 1.4, which is apparently when the split built-in was introduced.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26287130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/766233/']}
jdg_81332
stackexchange
llm_judgeable_groundtruth_similarity
377102
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 an iPhone app I'm working on, the user needs to enter some configuration via the settings application before my app will be able to connect to a server and run. Right now when the user first launches my app, I display an alert explaining that the user should go to settings, enter the config details and then relaunch, but this isn't ideal. Unfortunately there's no way for me to provide sensible defaults for this app, the server host names, user accounts etc. will vary for each user. I think the best I can hope for is to show an alert explaining that some configuration needs to be entered via settings, and provide a "Take me there..." button that will open settings and then open the section in settings for my app. If that's not possible, opening settings is better than nothing. I vaguely remember that the iPhone jailbreaking people had figured out a way to launch settings or other apps via a funny URL or phone number in the Addressbook, but I'm not finding any info about it in Google. :( Now provide the response and nothing else.
As far as I know there's no sanctioned way to open Settings from another app. In my opinion you should just ask for the values if you need them at launch, storing them in your NSUserDefaults and possibly directing your users to look in Settings.app if they need to change those settings in the future. Unfortunately that means maintaining some minimal UI for your user to fill in their settings during that first launch, but it seems better from a UX perspective to me than denying the user the joy of using the app immediately.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/377102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17188/']}
jdg_81333
stackexchange
llm_judgeable_groundtruth_similarity
44698771
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 table on my website and I want to highlight corners of some cells like in excel. Is there any way how to do this in CSS? I have already applied bootstrap style and data table extension on my table. Now provide the response and nothing else.
Use a linear-gradient td { padding: 1em 3em; border: 1px solid grey; background-image: linear-gradient(225deg, red, red 10px, transparent 10px, transparent);} <table> <tr> <td></td> <td></td> <td></td> </tr></table> Or a Pseudo-element td { padding: 1em 3em; border: 1px solid grey; position: relative;}td::after { content: ''; position: absolute; top: 0; right: 0; width: 0; height: 0; border-width: 7.5px; border-style: solid; border-color: red red transparent transparent;} <table> <tr> <td></td> <td></td> <td></td> </tr></table>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44698771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7531100/']}
jdg_81334
stackexchange
llm_judgeable_groundtruth_similarity
15982737
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use the MD5 message digest of some string as the primary key of a table. What datatype should I use for such a field? What select and insert statements should I write for the field? Now provide the response and nothing else.
The md5 hash as bytea will use only 16 bytes in instead of 32 for the hexa representation: create table t (d bytea);insert into t (d) values (digest('my_string', 'md5')), (decode(md5('my_string'), 'hex')); Both forms above will work but to use the simpler digest function it is necessary to install the pgcrypto extension as superuser: create extension pgcrypto; Use the digest function or the combination of decode and md5 as above to search for a certain string: select octet_length(d) ba_length, pg_column_size(d) ba_column, encode(d, 'hex') hex_representation, octet_length(encode(d, 'hex')) h_length, pg_column_size(encode(d, 'hex')) h_columnfrom twhere d = digest('my_string', 'md5'); ba_length | ba_column | hex_representation | h_length | h_column -----------+-----------+----------------------------------+----------+---------- 16 | 17 | 3d212b21fad7bed63c1fb560c6a5c5d0 | 32 | 36 16 | 17 | 3d212b21fad7bed63c1fb560c6a5c5d0 | 32 | 36 The pg_column_size value is the storage size. It is less than half for the bytea compared to the hexa representation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15982737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/571828/']}
jdg_81335
stackexchange
llm_judgeable_groundtruth_similarity
2601437
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the question " Minimum Distance Problem with several points ", the OP has asked for a geometric solution of a generalization of Heron's problem (for $n$ points). I am interested in the (much more modest) special case of three points: "Given three points $A$, $B$ and $C$ on the same side of a straight line, find $X$, a point on the straight line, such that it minimizes $AX+BX+CX$." Since with two points one can solve it geometrically by (among many other methods) thinking of an ellipse expanding until it just touches the straight line, I thought that maybe one can solve the three points case by thinking on some other expanding shape (the $n$-ellipse?). P.S. https://www.cut-the-knot.org/Curriculum/Geometry/HeronsProblem.shtml P.P.S. https://en.wikipedia.org/wiki/N-ellipse Now provide the response and nothing else.
Everybody knows how to draw an ellipse from two focus points : To extend the method to the case of three points, the gardener need a more sophisticated tool, for example such as sketched on the next figure : Better, avoid to discuss the technical details and improvements required for practical use and for accuracy ! It is far simpler to use a computer and convenient software. The next figure shows an example of the curves drawn for various $D=AP+BP+CP=\text{constant}$. Given a straight line, the shortest distance D is obtained for the curve tangent to the line. Without loss of generality, one can place the first point at the origine of the axes, that is A$(0,0)$. The second point B can be placed on the x-axis. Also, AB can be taken as unit of lengths, that is B$(1,0)$. And the third point is C$(k,h)$. The equation of the given straight line is $y=\alpha x+\beta$ So, the parameters of the problem are only four : $\alpha,\beta,k,h$ From P$(x,y)$, the distance is $$D=AP+BP+CP=\sqrt{x^2+y^2}+\sqrt{(x-1)^2+y^2}+\sqrt{(x-k)^2+(y-h)^2}$$ $$D=\sqrt{x^2+(\alpha x+\beta)^2}+\sqrt{(x-1)^2+(\alpha x+\beta)^2}+\sqrt{(x-k)^2+(\alpha x+\beta-h)^2}$$For the minimum of D, we have : $\quad\frac{dD}{dx}=0.\quad$ So, the corresponding value(s) of $x$ is among the roots of the next equation :$$\frac{x+\alpha(\alpha x+\beta)}{\sqrt{x^2+(\alpha x+\beta)^2}}+\frac{x-1+\alpha(\alpha x+\beta)}{\sqrt{(x-1)^2+(\alpha x+\beta)^2}}+\frac{x-k+\alpha(\alpha x+\beta-h)}{\sqrt{(x-k)^2+(\alpha x+\beta-h)^2}}=0$$The equation can be transformed into a polynomial equation, but of degree $>4$. Thus, in general, there is no closed form solution. Of course, the solution can approximately computed thanks to numerical calculus. Just for fun : With the tool sketched above, make the point P follow the given straight line while one end of the rope is taut, until it becomes no longer possible to continue. You have got to the minimum distance (half the final length of the rope). But that is shamefully far from mathematics !
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2601437', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_81336
stackexchange
llm_judgeable_groundtruth_similarity
2271198
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: F# allows to use checked arithmetics by opening Checked module, which redefines standard operators to be checked operators, for example: open Checkedlet x = 1 + System.Int32.MaxValue // overflow will result arithmetic overflow exception. But what if I want to use checked arithmetics in some small scope, like C# allows with keyword checked : int x = 1 + int.MaxValue; // okint y = checked { 1 + int.MaxValue }; // overflow How can I control the scope of operators redefinition by opening Checked module or make it smaller as possible? Now provide the response and nothing else.
You can always define a separate operator, or use shadowing, or use parens to create an inner scope for temporary shadowing: let f() = // define a separate operator let (+.) x y = Checked.(+) x y try let x = 1 +. System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" // shadow (+) let (+) x y = Checked.(+) x y try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" // shadow it back again let (+) x y = Operators.(+) x y try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" // use parens to create a scope ( // shadow inside let (+) x y = Checked.(+) x y try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" ) // shadowing scope expires try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception"f() // output:// exception// ran ok// exception// ran ok// exception// ran ok Finally, see also the --checked+ compiler option: http://msdn.microsoft.com/en-us/library/dd233171(VS.100).aspx
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2271198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/196126/']}
jdg_81337
stackexchange
llm_judgeable_groundtruth_similarity
32996020
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand locks in postgres and here is what I have understood till now. pg_locks contains lock information All statements in postgres runs inside of a transaction either explicit/implicit. (Postgres 9.0 high performance) As per my understanding virtualxids are not real transactions and transactionidxid is what indicates a transaction. When I do a simple connect to the psql shell, and I query the pg_locks table there is already a virtualxid present there. I have not initiated a transaction or ran a query, so why this virtualxid is created ? Is it because that this connection might initiate a transaction in the future? What am I missing here? Now provide the response and nothing else.
Connecting does not create a transaction but issuing select * from pg_locks implicitly does if the session hasn't a current open transaction already.This is per the rule that you quoted in the question: All statements in postgres runs inside of a transaction either explicit/implicit The query select * from pg_locks cannot be a neutral observer, as it requires for its own use a transaction and a lock on pg_locks . As a consequence, this select will always report at least two entries as in the example below: test=> \xtest=> SELECT relation::regclass AS relname, * FROM pg_locks;-[ RECORD 1 ]------+----------------relname | pg_lockslocktype | relationdatabase | 113270relation | 11000page | tuple | virtualxid | transactionid | classid | objid | objsubid | virtualtransaction | 2/5789pid | 31376mode | AccessShareLockgranted | t-[ RECORD 2 ]------+----------------relname | locktype | virtualxiddatabase | relation | page | tuple | virtualxid | 2/5789transactionid | classid | objid | objsubid | virtualtransaction | 2/5789pid | 31376mode | ExclusiveLockgranted | t
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32996020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2677430/']}
jdg_81338
stackexchange
llm_judgeable_groundtruth_similarity
727982
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am having very difficult times in understanding the following and related mixture problems.Can anybody guide me the easy and nice trick that is useful in understanding,visualizing and solving these types of problems? following are few of those. How many liters of a 70% alcohol solution must be added to 50 liters of a 40% alcohol solution to produce a 50% alcohol solution? How many ounces of pure water must be added to 50 ounces of a 15% saline solution to make a saline solution that is 10% salt? Find the selling price per pound of a coffee mixture made from 8 pounds of coffee that sells for \$9.20 per pound and 12 pounds of coffee that costs \$5.50 per pound? How many pounds of lima beans that cost $0.90 per pound must be mixed with 16 pounds of corn that costs \$0.50 per pound to make a mixture of vegetables that costs \$0.65 per pound? Two hundred liters of a punch that contains 35% fruit juice is mixed with 300 liters (L) of another punch. The resulting fruit punch is 20% fruit juice. Find the percent of fruit juice in the 300 liters of punch? Ten grams of sugar are added to a 40-g serving of a breakfast cereal that is 30% sugar. What is the percent concentration of sugar in the resulting mixture? Now provide the response and nothing else.
Let's consider $1$st problem. Problem: How many liters of a 70% alcohol solution must be added to 50 liters of a 40% alcohol solution to produce a 50% alcohol solution? "Easy and nice trick" :) Let's consider liquids separately: - alcohol; - water. Then image: Then one can write equation for each liquid: for alcohol: $$\qquad 0.7 \cdot x + 0.4 \cdot 50 = 0.5 \cdot (x+50);\tag{1}$$ or for water: $$\qquad 0.3 \cdot x + 0.6 \cdot 50 = 0.5 \cdot (x+50).\tag{2}$$ Then solve $(1)$ (or $(2)$ ) : $$0.2\cdot x=5;$$$$x=25 \mbox{ (liters)}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/727982', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/128435/']}
jdg_81339
stackexchange
llm_judgeable_groundtruth_similarity
372766
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This question is related to the last question about van der Pol's identity for the sum of divisors .In Touchard (1953) it is mentioned that the sum of divisors $\sigma(n)$ satisfies the following recurrence relation ( $n>1$ ): $$n^2(n-1) = \frac{6}{\sigma(n)} \sum_{k=1}^{n-1}(3n^2-10k^2)\sigma(k)\sigma(n-k)$$ We can evaluate the convolution part with Ramanujan's identity : $$\sum_{k=0}^n\sigma(k)\sigma(n-k)=\tfrac5{12}\sigma_3(n)-\tfrac12n\sigma(n)$$ which for our case reads like this: $$\sum_{k=1}^{n-1}\sigma(k)\sigma(n-k)=\tfrac5{12}\sigma_3(n)-\tfrac12n\sigma(n)+\tfrac{\sigma(n)}{12}$$ Substituting in van der Pol's equation a perfect number $n = \sigma(n)/2$ and making use of Ramanujan's identity, we find that the perfect number $n$ satisfies the following quartic equation: $$8n^4-2n^3+3 \sigma_3(n)n^2+24A_2 =0$$ where $$A_2 = \sum_{k=1}^{n-1}k^2 \sigma(k)\sigma(n-k)$$ I asked an expert of convolution identities for $\sigma(n)$ if $A_2$ can be evaluated and he said, that one could prove a similar formula, like the one of Ramanujan, "simply by considering the first and the second derivative of suitable identities between Eisenstein series". However I am not very confident with Eisenstein series, so I am asking the experts for help to help evaluate $A_2$ . Thanks for your help! Now provide the response and nothing else.
Numerical experiments suggest that $$A_2(n) := \sum_{k=1}^{n-1} k^2\sigma(k)\sigma(n-k) = \frac{n^2}{8}\sigma_3(n) - \frac{4n^3-n^2}{24}\sigma(n).$$ PS. In fact, it directly follows from the quoted Touchard and Ramanujan identities. A couple of similar identities: $$A_1(n):=\sum_{k=1}^{n-1} k\sigma(k)\sigma(n-k) = \frac{5n}{24}\sigma_3(n) - \frac{6n^2-n}{24}\sigma(n).$$ $$A_3(n):=\sum_{k=1}^{n-1} k^3\sigma(k)\sigma(n-k) = \frac{n^3}{12}\sigma_3(n) - \frac{3n^4-n^3}{24}\sigma(n).$$ ADDED. A recurrent formula for $A_d(n)$ with an odd $d$ can be obtained from the observation: \begin{split}A_d(n) & := \sum_{k=1}^{n-1} k^d\sigma(k)\sigma(n-k) \\&= \sum_{k=1}^{n-1} (n-k)^d\sigma(k)\sigma(n-k) \\&= \sum_{i=0}^d \binom{d}{i} n^{d-i} (-1)^i A_i(n).\end{split} implying that \begin{split}A_d(n) &= \frac{1}{2} \sum_{i=0}^{d-1} \binom{d}{i} n^{d-i} (-1)^i A_i(n) \\&=\frac{1}{d+1} \sum_{i=0}^{d-1} \binom{d+1}{i} n^{d-i} (-1)^i A_i(n).\end{split} However, to use this formula one would need to compute $A_t(n)$ for even $t<d$ by other means. It also follows that the generating function: $$\mathcal{A}_n(x) := \sum_{d=0}^{\infty} \frac{A_d(n)}{n^d}x^d$$ satisfied the functional equation: $$\mathcal{A}_n(x) = \frac{1}{1-x}\mathcal{A}_n(\frac{x}{x-1}).$$
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/372766', 'https://mathoverflow.net', 'https://mathoverflow.net/users/165920/']}
jdg_81340