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
558914
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'd love some other opinions on what's more efficient in this code. Basically in the following code, there's a setInterval loop and I need 4 requirements to be true before the code runs in the loop. So in v.1 I wrote an if statement checking all 4. Worked fine. Then I switched to just using try/catch, with the code I want to execute sitting in try{}. The logic was that during each loop, an exception would be generated but suppressed for each invalid condition. On the final loop where all conditions are true, the code executes and clears the interval. Either works. I like the try/catch method because there's less conditional code that I need to write and worry about breaking. But I'm worried that try/catch is really inefficient, especially in a setInterval() loop hitting at 100ms. What are some opinions of other bright minds here on SO? Try/Catch var intvar = setInterval(function(){try{ clearInterval(intvar); jQuery('#'+nav[pageid].t1+'>a').replaceWith(jQuery('<span>'+jQuery('#'+nav[pageid].t1+'>a').text()+'</span>')); //set display classes for nav jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav}catch(err){}},100); IF Block var intvar = setInterval(function(){if(typeof jQuery == 'function' && typeof nav == 'object' && typeof pageid != 'undefined' && typeof document.getElementById('leftnav') == 'object'){ clearInterval(intvar); jQuery('#'+nav[pageid].t1+'>a').replaceWith(jQuery('<span>'+jQuery('#'+nav[pageid].t1+'>a').text()+'</span>')); //set display classes for nav jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav}},100); Now provide the response and nothing else.
Use the if statement. I don't know what the overhead is for a TRY/CATCH, but I suspect it's far greater than evaluating a boolean expression. To hit the TRY/CATCH you will have to: execute a statement, generate an error [with that associated overhead], log the error (presumably), made a stacktrace(presumably), and moved back into the code. Additionally, if you have to debug code near those lines the real error could get obfuscated with what you are TRY/CATCHing. Furthermore, it's a misuse of TRY/CATCH and can make your code that much harder to read. Suppose you do this for longer or more obfuscated cases? Where might your catch end up? This is referred to as Exception handling EDIT: As commented below, you only take the runtime performance hit if you actually cause an exception.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/558914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68788/']}
jdg_83541
stackexchange
llm_judgeable_groundtruth_similarity
1638987
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find all pairs of nonzero integers $(a,b)$ such that $(a^2+b)(a+b^2)=(a-b)^3$ My effort Rearranging the equation I have \begin{array}\space (a^2+b)(a+b^2)-(a-b)^3 &=0 \\a^2(b^2+3b)+a(-3b^2+b)+2b^3 &=0 \\\end{array} Letting $a=x$, we have the polynomial $Q(x)$ such that $$Q(x)=x^2(b^2+3b)+x(-3b^2+b)+2b^3 $$ So I must have that the roots $a_1,a_2$ must be such that \begin{array}\space a_1+a_2=-\cfrac{-3b+1}{b+3} \\a_1\cdot a_2=\cfrac{2b^2}{b+3} \\\end{array} I am stuck now,should I go by brute force and verify some values or there's still something I can do here to simplify the problem ? Now provide the response and nothing else.
The general solution to $\alpha x^2+\beta x+\gamma=0$ is $x=\frac{-\beta\pm \sqrt{\beta^2-4\alpha\gamma}}{2\alpha}$. Here, after factoring out the common $b$, you get $\alpha = b+3, \beta=-(3b-1),\gamma=2b^2$. In particular, you need $(3b-1)^2-4(b+3)(2b^2)=-8b^3-15b^2-6b+1$ to be a perfect square to even get a rational $a$. But then a miracle occurs, because $-8b^3-15b^2-6b+1=(b+1)^2(1-8b)$. So this is a square exactly when $1-8b$ is a square. Let $1-8b = (2c+1)^2$. Then $b=-\frac{c(c+1)}{2}$, and the formula: $$ \begin{align}a&=\frac{3b-1 \pm (b+1)\sqrt{1-8b}}{2(b+3)}\\ &=\frac{3 \pm \sqrt{1-8b}}{2} +\frac{-10\pm 2\sqrt{1-8b}}{2(b+3)}\\&=\frac{3\pm (2c+1)}{2} + \frac{-10 \pm 2(2c+1)}{-c^2-c+6}\\&=\frac{3\pm (2c+1)}{2}+\frac{-10\pm(4c+2)}{(2-c)(c+3)}\end{align}$$ Note that $3\pm(2c+1)$ is even so you need the second have to be an integer. But this just means you need $4c+12=4(c+3)$ divisible by $(c+3)(c-2)$, or you need $4c-8=4(c-2)$ divisible by $(c+3)(c-2)$. So you need either $c-2$ or $c+3$ a factor of $4$. We can restrict to $c$ non-negative, so we get $c=0,1,3,4,6$. The case $c=0$ gives $b=0$, disallowed. The case $c=1$ gives $a=b=-1$. The case $c=3$ gives $a=9,b=-6$. The case $c=4$ gives $(a,b)=(8,-10)$. The case $c=6$ gives $(a,b)=(9,-21)$. You should also check specifically the case where $b+3=0$, since then the equation is not quadratic. There is no solution in this case. -- Wondering if we write the polynomial in terms of $b$: $$2b^2 + (a^2-3a)b + (3a^2+a)=0$$ The discriminant of this is $a^4-6a^3-15a^2-8a$. While we have an easy factor of $a$ there, that just returns us to a cubic $a^3-6a^2-15a-8=(a+1)^2(a-8)$. But it isn't obvious to me how to see that factorization if you stumbled in this direction first.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1638987', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/291945/']}
jdg_83542
stackexchange
llm_judgeable_groundtruth_similarity
94845
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 have two classes (say 1 and 0), and want to build a classifier. It is possible to use artificial neural networks (ANN) or any "real" classifying method such as SVM or Random Forest. In case of ANN, one can easily estimates confidence level of classification. For example, if we have binary task (with outputs as 0 or 1), and ANN results for some sample is 0.92, one can suppose that ANN "sure" in classification to 1 class. Alternatively, if ANN outputs 0.52, it is considered as unsteady classification to 1 flass. But if we use Random Forest or SVM how it is possible to confidence level of classification? Now provide the response and nothing else.
Confidence intervals for SVMs are often obtained via bootstrapping or by taking a Bayesian approach. For classification, bootstrapping may be a good approach to take. This slide deck illustrates some concepts of how to estimate confidence intervals to a test error of a certainclassifier based on continuous functionals. Another approach given here : Estimating the Confidence Interval for Prediction Errors of Support Vector Machine Classifiers Bo Jiang, Xuegong Zhang, Tianxi Cai; 9(Mar):521--540, 2008. is to use perturbation-resampling (similar to bootstrapping) to obtain the desired confidence intervals.This paper is a bit more interpretable than the slide deck. To summarize, first, it proposes that the classifier be estimated using cross-validation, and that as an output one will have $\hat{D}$ the estimated prediction error (Equation (5)). They go on to point out that it is desirable to know something about the distribution of this estimated prediction error (for instance if we know something about its distribution we can try to obtain confidence intervals for it). In order to do so for a general class of distributions (a problem confronted in the slide deck as well), they detail their resampling approach in Section 3.2. This is consolidated in an algorithm that they provide in this section. You may also have luck attempting to learn something from the LS-SVM toolbox posted by this work group. They implement confidence intervals for Least Squares SVMs for regression using a Baysian confidence interval. This is not for classification, but it may be possible that you can adapt it to your problem.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/94845', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/44315/']}
jdg_83543
stackexchange
llm_judgeable_groundtruth_similarity
365802
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Wolfram MathWorld says As used in physics, the term “exact” generally refers to a solution that captures the entire physics and mathematics of a problem as opposed to one that is approximate, perturbative, etc. Exact solutions therefore need not be closed-form. But Terry Tao seems to take "exact solution" to mean a closed form solution. Is one of these very standard?  Or does usage just vary on this point? Now provide the response and nothing else.
It depends on context. In the physics literature, there is a term "exactly solvable" meaning that a closed form for the solution can be written; it is never used to indicate that the solution exists in an abstract sense. E. g., see Baxter's classical book "Exactly solvable models in Statistical mechanics". So, in this context "exact solution" does mean "closed form solution". Edit inspired by Alexandre Eremenko's answer: more precisely, for a physicist, "exact solution" should be explicit enough to answer all the questions they care about. In practice, these questions often boil down to the asymptotics at singular points and/or infinity. Say, Baxter's exact solutions are primarily interisting because they provide the critical exponents. In that sense, Painleve functions should count as closed form, since the asymptotical expansions and connection formulae are known for them, and Sundman's solution is not. In other context, you may talk about approximate or perturbative solution, and then I feel it is fine to contrast it to the "exact solution" even when the closed form for the latter is not known.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/365802', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38783/']}
jdg_83544
stackexchange
llm_judgeable_groundtruth_similarity
43491498
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 new to Pylint, and when I run it against my script, I get this output: C: 50, 0: Trailing newlines (trailing-newlines) Here, Pylint is saying that it is bad to have a final newline. I like to have a new line at the end of my scripts, so I thought I would disable this warning.I did some google web searching and found this: http://pylint-messages.wikidot.com/messages:c0304 C0304 Message Final newline missing Description Used when a Python source file has no line end character(s) on its last line. This message belongs to the format checker. Explanation While Python interpreters typically do not require line end character(s) on the last line, other programs processing Python source files may do, and it is simply good practice to have it. This is confirmed in Python docs: Line Structure which states that a physical line is ended by the respective line end character(s) of the platform. Here, Pylint is saying that it is bad to miss the final newline. (A) What is the correct view ?(B) How do I disable the check for the final new line ? {{ EDIT : It turns out that this is not an issue with Pylint ; It is an issue with vim , which adds eol automatically : VIM Disable Automatic Newline At End Of File }} Now provide the response and nothing else.
The pylint warning you are getting is complaining that you have multiple trailing newlines. The C0304 message occurs when there is no trailing newline at all. These messages are not contradictory they indicate different problems. The reason you need at least one newline is that historically some tools have problems if the file ends and the last line has text on it but does not have a newline at the end of the file. Badly written tools can miss processing that last partial line, or even worse can read random memory beyond the last line (though that is unlikely to happen with tools written in Python it can happen with tools written in C). So you must ensure there is a newline terminating the last non-blank line. But you don't want any completely blank lines at the end of the file either. They won't actually produce bugs but they're untidy. So delete any blank lines and you should be fine.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43491498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3057742/']}
jdg_83545
stackexchange
llm_judgeable_groundtruth_similarity
90751
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Do C#/.NET floating point operations differ in precision between debug mode and release mode? Now provide the response and nothing else.
They can indeed be different. According to the CLR ECMA specification: Storage locations for floating-point numbers (statics, array elements, and fields of classes) are of fixed size. The supported storage sizes are float32 and float64. Everywhere else (on the evaluation stack, as arguments, as return types, and as local variables) floating-point numbers are represented using an internal floating-point type. In each such instance, the nominal type of the variable or expression is either R4 or R8, but its value can be represented internally with additional range and/or precision. The size of the internal floating-point representation is implementation-dependent, can vary, and shall have precision at least as great as that of the variable or expression being represented. An implicit widening conversion to the internal representation from float32 or float64 is performed when those types are loaded from storage. The internal representation is typically the native size for the hardware, or as required for efficient implementation of an operation. What this basically means is that the following comparison may or may not be equal: class Foo{ double _v = ...; void Bar() { double v = _v; if( v == _v ) { // Code may or may not execute here. // _v is 64-bit. // v could be either 64-bit (debug) or 80-bit (release) or something else (future?). } }} Take-home message: never check floating values for equality.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/90751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288629/']}
jdg_83546
stackexchange
llm_judgeable_groundtruth_similarity
2499036
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 first example using repeated l'Hôpital: $$\lim_{x \rightarrow 0} \frac{x^4}{x^4+x^2} = \lim_{x \rightarrow 0} \frac{\frac{d}{dx}(x^4)}{\frac{d}{dx}(x^4+x^2)} = \lim_{x \rightarrow 0} \frac{4x^3}{4x^3+2x} = ... = \lim_{x \rightarrow 0}\frac{\frac{d}{dx}(24x)}{\frac{d}{dx}(24x)} = \frac{24}{24}=1 $$ Consider the following example using a different method: $$ \lim_{x \rightarrow 0} \frac{x^4}{x^4+x^2} = \lim_{x \rightarrow 0}\frac{\frac{x^4}{x^4}}{\frac{x^4}{x^4}+\frac{x^2}{x^4}} = \lim_{x \rightarrow 0} \frac {1}{1 +\frac{1}{x^2}} = \frac {1}{1+\infty} = \frac{1}{\infty}=0 $$ The graph here clearly tells me the limit should be $0$, but why does l'Hôpital fail? Now provide the response and nothing else.
$$\lim_{x \rightarrow 0} \frac{x^4}{x^4+x^2} = \lim_{x \rightarrow 0} \frac{\frac{d}{dx}(x^4)}{\frac{d}{dx}(x^4+x^2)} = \lim_{x \rightarrow 0} \frac{4x^3}{4x^3+2x} = \lim_{x\to0} \frac{12x^2}{12x^2+2} = \frac{0}{0+2} = 0$$ There. You can't apply l'Hospital there because the denominator doesn't go to $0$.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2499036', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296508/']}
jdg_83547
stackexchange
llm_judgeable_groundtruth_similarity
1358926
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to append log4j content to a Swing component (JTextArea or similar). Is there a common way to do this? Now provide the response and nothing else.
Instead of introducing an external library, I ended up editing the log4j.properties file to include the following: log4j.rootCategory=DEBUG, applog4j.appender.app=path.to.class.extending.WriterAppender Then I employed an observer pattern to post the data into my GUI's JTextArea.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1358926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11760/']}
jdg_83548
stackexchange
llm_judgeable_groundtruth_similarity
662217
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am using an on-demand instance for testing some services in my spare time. So, I start and stop that instance very frequently, and I see its public and private IPs changing each time. This is annoying, because I always need to change hostname in several applications using test services. What I want is to have at least a "fixed", static private IP. I read somewhere that adding ENI interface could be the solution. In this case, can you provide me a simple example on how to do that? In other case, what's the cleaner solution? Now provide the response and nothing else.
You tagged this amazon-vpc , but the behavior you describe is what happens when an instance is launched in EC2-Classic. When you launch an instance in a VPC, it is assigned a private IP address and it remains for the lifetime of the instance. Their documentation is pretty clear on that point. To be clear, 'instance' in this case is a discrete 'i-' number. EC2-Classic has no support for what you're looking for, and you can't assign new interfaces to it . If you're not actually keeping the same instance defined and are spinning a new one up in a VPC based off of an AMI you have, you will get a new private IP address each time. As you suspected, if you define a new Interface and associate it with the instance, that Interface will have a static IP address. When you terminate the instance, the extra Interface goes unassigned. Reassign it to a new instance when you spin one up.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/662217', 'https://serverfault.com', 'https://serverfault.com/users/63433/']}
jdg_83549
stackexchange
llm_judgeable_groundtruth_similarity
57599776
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 do me code in Cromedrive in 'normal' mode and works fine. When I change to headless mode it don't download the file. I already try the code I found alround internet, but didn't work. chrome_options = Options()chrome_options.add_argument("--headless")self.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'{}/chromedriver'.format(os.getcwd()))self.driver.set_window_size(1024, 768)self.driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': os.getcwd()}}self.driver.execute("send_command", params) Anyone have any idea about how solve this problem? PS: I don't need to use Chomedrive necessarily. If it works in another drive it's fine for me. Now provide the response and nothing else.
First the solution Minimum Prerequisites: Selenium client version: Selenium v3.141.59 Chrome version: Chrome v77.0 ChromeDriver version: ChromeDriver v77.0 To download the file clicking on the element with text as Download Data within this website you can use the following solution: Code Block: from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.chrome.options import Optionsoptions = Options()options.add_argument("--headless")options.add_argument("--window-size=1920,1080")options.add_experimental_option("excludeSwitches", ["enable-automation"])options.add_experimental_option('useAutomationExtension', False)driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe', service_args=["--log-path=./Logs/DubiousDan.log"])print ("Headless Chrome Initialized")params = {'behavior': 'allow', 'downloadPath': r'C:\Users\Debanjan.B\Downloads'}driver.execute_cdp_cmd('Page.setDownloadBehavior', params)driver.get("https://www.mockaroo.com/")driver.execute_script("scroll(0, 250)"); WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#download"))).click()print ("Download button clicked")#driver.quit() Console Output: Headless Chrome InitializedDownload button clicked File Downloading snapshot: Details Downloading files through Headless Chromium was one of the most sought functionality since Headless Chrome was introduced. Since then there were different work-arounds published by different contributors and some of them are: Downloading with chrome headless and selenium Python equivalent of a given wget command Now the, the good news is Chromium team have officially announced the arrival of the functionality Downloading file through Headless Chromium . In the discussion Headless mode doesn't save file downloads @eseckler mentioned: Downloads in headless work a little differently. There's the Page.setDownloadBehavior devtools command to set a download folder. We're working on a way to use DevTools network interception to stream the downloaded file via DevTools as well. A detailed discussion can be found at Issue 696481: Headless mode doesn't save file downloads Finally, @bugdroid revision seems to have nailed the issue for us. [ChromeDriver] Added support for headless mode to download files Previously, Chromedriver running in headless mode would not properly download files due to the fact it sparsely parses the preference file given to it. Engineers from the headless chrome team recommended using DevTools's "Page.setDownloadBehavior" to fix this. This changelist implements this fix. Downloaded files default to the current directory and can be set using download_dir when instantiating a chromedriver instance. Also added tests to ensure proper download functionality. Here is the revision and commit From ChromeDriver v77.0.3865.40 (2019-08-20) release notes: Resolved issue 2454: Headless mode doesn't save file downloads [Pri-2] Solution Update ChromeDriver to latest ChromeDriver v77.0 level. Update Chrome to Chrome Version 77.0 level. (as per ChromeDriver v76.0 release notes ) Note : Chrome v77.0 is yet to be GAed/pushed for release so till then you can download and install a development build and test either from: Chrome Canary Latest build from the Dev Channel Outro However Mac OSX users have a wait for their pie as On Chromedriver, headless chrome crashes after sending Page.setDownloadBehavior on MacOSX .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57599776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11547296/']}
jdg_83550
stackexchange
llm_judgeable_groundtruth_similarity
107
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The intertemporal capital asset pricing model (ICAPM) is different from the CAPM in that in the ICAPM, utility is conditioned on some set of state variables. The ICAPM results in a multifactor pricing model of the market if investor care about hedging against changing investment opportunities and exposure to these factors. Are there any canonical examples of these factors? I know that the Fama-French multifactor models (e.g., the three factor model ) are often justified on grounds of the ICAPM (or APT -- arbitrage pricing theory). What are the underlying risk factors that justify this model? Are there any other examples of underlying risk factors that show up a lot? Now provide the response and nothing else.
ICAPM Factors People have chosen different ways to pick factors. Chen, Roll and Ross are a classic example of attempts to find reasonable ICAPM factors. Fama-French factors are often explained as correlated with underlying ICAPM factors. Other researchers have chosen to look for factors without assuming outwardly observable exposures by analyzing returns using factor analysis or principal components. Explanations of Fama-French I don't know if there are "commonly accepted" explanations for the Fama French factors. This is not to say that there aren't explanations, there are a lot of them. Just no one seems to agree on which ones are "best". Candidates include both consumption based explanations AND production based models, each of which relates Fama-French factors to underlying economic variables. Cochrane has a nice summary of the performance of both in pricing Fama-French portfolios here . Additional factors commonly used Fama and French are now talking about a five-factor asset pricing model which also includes profitability and investment, similar to Novy-Marx 's paper and work by Chen, Novy-Marx and Zhang which more directly relates to production asset pricing. Momentum is also a consistent candidate, although it's a real pain to put any kind of explanation to. There are tons of others. This paper lists many of them, as well as calling the significance of some of them into question.
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/107', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/59/']}
jdg_83551
stackexchange
llm_judgeable_groundtruth_similarity
11996809
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 stub a method using Mockito 1.8.5, but doing so calls the real method implementation (with "" as parm values) which throws an exception. package background.internal; //located in trunk/tests/java/background/internalpublic class MoveStepTest { @Test public void testMoveUpdate() { final String returnValue = "value"; final FileAttachmentContainer file = mock(FileAttachmentContainer.class); doReturn(returnValue).when(file).moveAttachment(anyString(), anyString(), anyString()); //this also fails //when(file.moveAttachment(anyString(), anyString(), anyString())).thenReturn(returnValue); final AttachmentMoveStep move = new AttachmentMoveStep(file); final Action moveResult = move.advance(1, mock(Context.class)); assertEquals(Action.done, moveResult); }} The method I'm trying to mock looks like this. There are no final method or classes. package background.internal; //located in trunk/src/background/internal public class FileAttachmentContainer { String moveAttachment(final String arg1, final String arg2, final String arg3) throws CustomException { ... } String getPersistedValue(final Context context) { ... } } And the class I'm passing the mock looks like this: package background.internal; //located in trunk/src/background/internalpublic class AttachmentMoveStep { private final FileAttachmentContainer file; public AttachmentMoveStep(final FileAttachmentContainer file) { this.file = file; } public Action advance(final double acceleration, final Context context) { try { final String attachmentValue = this.file.getPersistedValue(context); final String entryId = this.file.moveAttachment(attachmentValue, "attachment", context.getUserName()); //do some other stuff with entryId } catch (CustomException e) { e.log(context); } return Action.done; }} What is causing the real implementation to be invoked and how can I prevent it? Now provide the response and nothing else.
The method you are mocking is not accessible to the Mockito code. Because your test code and your code under test are in the same package, the compiler lets you set up your mock that way, but at runtime, the Mockito library has to try to access moveAttachment , but it's not working in your case. This appears to be a bug or known limitation in Mockito as it should support that case, (and in fact, does support it in most cases). The easiest thing to do would be to make moveAttachment a public method. If that is not an option, then first question whether you want to even mock it. What happens if the real method gets called? The last option is to use PowerMock to treat the moveAttachment method as a private method and mock it that way.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11996809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/672584/']}
jdg_83552
stackexchange
llm_judgeable_groundtruth_similarity
645840
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: When connecting a capacitor directly to a voltage supply (without a resistor), is it correct to expect a surge in current at the instant when the capacitor and the battery are connected, then current immediately drops to zero because the capacitor is fully charged up? I tried to do a simulation with only a voltage supply and an ideal capacitor (no resistor) and run a transient simulation. I then plotted the current flowing into the capacitor against time. The plot showed that current was always at 0 A. No surge in current was observed. So would a surge in current happen in a real experiment? If so, does it mean that the simulation fails to represent the real circuit behaviour. Thanks. Now provide the response and nothing else.
The IRFZ44N is not well suited to logic level drive. You should get a MOSFET with a much lower gate threshold voltage to get the lowest ON resistance. But you also need to drive it with more current than an Arduino output can provide. Here is a simple gate driver that should improve things, although a dedicated driver will work even better. simulate this circuit – Schematic created using CircuitLab I also ran this simulation with an IRFZ44, and directly from the 5V PWM signal with 200 ohm series resistance (simulating Arduino GPIO with 25 mA maximum drive), and it is clear that the MOSFET is not properly driven for efficient switching, causing a lot of heating:
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/645840', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/261579/']}
jdg_83553
stackexchange
llm_judgeable_groundtruth_similarity
39661441
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 used to have a selenium script code in Python for a firefox website that worked fine.After a while I updated Firefox (48) and selenium 2.9.1.1, python is 3.5.0 the code, # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re, os class Jqueryx(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://127.0.0.1:8080/" self.verificationErrors = [] self.accept_next_alert = True self.path_upload_quest = r'C:\\Users\jl\Documents\DONNEES\DONNEES_LIMONDE' self.path_upload_ref = r'C:\\Users\jl\Documents\DONNEES\DONNEES_LIMONDE\ref' def test_jqueryx(self): driver = self.driver driver.get(self.base_url + "/lim/home.php") If I run the script now i ve got this message: os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' >executable needs to be in PATH. So I download this geckodriver thing and try to add it to the python but nothing works yet, I try to add this in the script; os.environ["PATH"] += r'C:\Users\jl\geckodriver' without success or adding a .pth file in the site-package folder but no change too... What can I do to get this script back on track ? thx Now provide the response and nothing else.
You should not be adding formControlName attribute to the input field in the template of your custom component. You should be adding the formControlName on the custom-input element itself as per the best practice. Here what you can use in your custom-input component is the controlValueAccessor interface to make your custom-input have the value updated whenever there is an event of input field in the template of your custom input changed or blurred. It provides a connection (to update values or other needs) between the form control behavior of your custom input and the UI you are providing for that custom form control. Below is the code of a custom input component in TypeScript. import { Component, Input, forwardRef, AfterViewInit, trigger, state, animate, transition, style, HostListener, OnChanges, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core';import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormControl } from '@angular/forms';export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputComponent), multi: true};@Component({ selector: 'inv-input', templateUrl:'./input-text.component.html', styleUrls: ['./input-text.component.css'], encapsulation: ViewEncapsulation.None, providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR], animations:[trigger( 'visibilityChanged',[ state('true',style({'height':'*','padding-top':'4px'})), state('false',style({height:'0px','padding-top':'0px'})), transition('*=>*',animate('200ms')) ] )]})export class InputComponent implements ControlValueAccessor, AfterViewInit, OnChanges { // Input field type eg:text,password @Input() type = "text"; // ID attribute for the field and for attribute for the label @Input() idd = ""; // The field name text . used to set placeholder also if no pH (placeholder) input is given @Input() text = ""; // placeholder input @Input() pH:string; //current form control input. helpful in validating and accessing form control @Input() c:FormControl = new FormControl(); // set true if we need not show the asterisk in red color @Input() optional : boolean = false; //@Input() v:boolean = true; // validation input. if false we will not show error message. // errors for the form control will be stored in this array errors:Array<any> = ['This field is required']; // get reference to the input element @ViewChild('input') inputRef:ElementRef; constructor() { } ngOnChanges(){ } //Lifecycle hook. angular.io for more info ngAfterViewInit(){ // set placeholder default value when no input given to pH property if(this.pH === undefined){ this.pH = "Enter "+this.text; } // RESET the custom input form control UI when the form control is RESET this.c.valueChanges.subscribe( () => { // check condition if the form control is RESET if (this.c.value == "" || this.c.value == null || this.c.value == undefined) { this.innerValue = ""; this.inputRef.nativeElement.value = ""; } } ); } //The internal data model for form control value access private innerValue: any = ''; // event fired when input value is changed . later propagated up to the form control using the custom value accessor interface onChange(e:Event, value:any){ //set changed value this.innerValue = value; // propagate value into form control using control value accessor interface this.propagateChange(this.innerValue); //reset errors this.errors = []; //setting, resetting error messages into an array (to loop) and adding the validation messages to show below the field area for (var key in this.c.errors) { if (this.c.errors.hasOwnProperty(key)) { if(key === "required"){ this.errors.push("This field is required"); }else{ this.errors.push(this.c.errors[key]); } } } } //get accessor get value(): any { return this.innerValue; }; //set accessor including call the onchange callback set value(v: any) { if (v !== this.innerValue) { this.innerValue = v; } } //propagate changes into the custom form control propagateChange = (_: any) => { } //From ControlValueAccessor interface writeValue(value: any) { this.innerValue = value; } //From ControlValueAccessor interface registerOnChange(fn: any) { this.propagateChange = fn; } //From ControlValueAccessor interface registerOnTouched(fn: any) { }} Below is the template HTML for the custom input component <div class="fg"> <!--Label text--> <label [attr.for]="idd">{{text}}<sup *ngIf="!optional">*</sup></label> <!--Input form control element with on change event listener helpful to propagate changes --> <input type="{{type}}" #input id="{{idd}}" placeholder="{{pH}}" (blur)="onChange($event, input.value)"> <!--Loop through errors--> <div style="height:0px;" [@visibilityChanged]="!c.pristine && !c.valid" class="error"> <p *ngFor="let error of errors">{{error}}</p> </div></div> Below is custom input component which can be used in a fromGroup or individually <inv-input formControlName="title" [c]="newQueryForm.controls.title" [optional]="true" idd="title" placeholder="Type Title to search" text="Title"></inv-input> In this fashion if you implement your custom form controls you can apply your custom validator directives easily and accumulate the errors on that form control to display your errors. One can imitate the same style to develop custom select component, radio button group, checkbox, textarea, fileupload etc in the above fashion with minor changes as per what the form control's behavior demands.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39661441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/513609/']}
jdg_83554
stackexchange
llm_judgeable_groundtruth_similarity
26358684
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My code sends a GET request to a server, URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); I get a BufferedReader object that prints, { "status": "ERROR", "errorCode": "MISSING_PARAMS", "errorMessage": null, "requestId": "20141014181739_11625805172", "downstreamModuleErrorCode": null, "object": [ "activity_code", "activity_name", "points", "frequency", "strategy", "vsa_app_access_token" ]} I want to get a JSONOBject or a Map from this. I tried converting this into a String and manipulating it. But it's not that easy to do. Please help. Now provide the response and nothing else.
First do it as string. you can use custom librarys for that like String message = org.apache.commons.io.IOUtils.toString(rd); or a StringBuilder StringBuilder sb = new StringBuilder(); String line; br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } Then you can parse it. Since it's an object because of the "{" (array begin and ends with []) you need to create an JSONObject. JSONObject json = new JSONObject(sb.toString()); then you can access your elements with //{ "status": "ERROR", "errorCode": "MISSING_PARAMS", "errorMessage": null, "requestId": "20141014181739_11625805172", "downstreamModuleErrorCode": null, "object": [ "activity_code", "activity_name", "points", "frequency", "strategy", "vsa_app_access_token" ]}json.getString("status"); or the array with JSONArray jsonArray = new JSONArray(json.getString("object")); or you use the method getJSONArray() JSONArray jsonArray = json.getJSONArray("object");
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26358684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4079056/']}
jdg_83555
stackexchange
llm_judgeable_groundtruth_similarity
19828236
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'd like to record audio from my microphone. My OS is ubuntu. I've tried the following and got errors $ ffmpeg -f alsa -ac 2 -i hw:1,0 -itsoffset 00:00:00.5 -f video4linux2 -s 320x240 -r 25 /dev/video0 out.mpgffmpeg version 0.8.8-4:0.8.8-0ubuntu0.12.04.1, Copyright (c) 2000-2013 the Libavdevelopers built on Oct 22 2013 12:31:55 with gcc 4.6.3*** THIS PROGRAM IS DEPRECATED ***This program is only provided for compatibility and will be removed in a future release.Please use avconv instead.ALSA lib conf.c:3314:(snd_config_hooks_call) Cannot open shared librarylibasound_module_conf_pulse.soALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM hw:1,0[alsa @ 0xbda7a0] cannot open audio device hw:1,0 (No such file or directory)hw:1,0: Input/output error Then I tried $ ffmpeg -f oss -i /dev/dsp audio.mp3ffmpeg version 0.8.8-4:0.8.8-0ubuntu0.12.04.1, Copyright (c) 2000-2013 the Libavdevelopersbuilt on Oct 22 2013 12:31:55 with gcc 4.6.3*** THIS PROGRAM IS DEPRECATED ***This program is only provided for compatibility and will be removed in a future release.Please use avconv instead.[oss @ 0x1ba57a0] /dev/dsp: No such file or directory/dev/dsp: Input/output error I haven't been able to get ffmpeg to find my microphone. How can I tell ffmpeg to record from my microphone? It seems the 'Deprecated' message can be ignored because of this topic Now provide the response and nothing else.
I realise this is a bit old. Just in case anyone else is looking: ffmpeg -f alsa -ac 2 -i default -itsoffset 00:00:00.5 -f video4linux2 -s 320x240 -r 25 -i /dev/video0 out.mpg This way it will use the default device to record from. You were also missing a -i before the video capture device - /dev/device0 If you want to get more specific you should take a look in /proc/asound .Check the cards , devices , pcm files and the card subdirectories. You should be able to glean enough information there to be able to make an educated guess; e.g hw:1,0 or hw:2,0 The documentation may provide further clues: http://www.alsa-project.org/main/index.php/DeviceNames The same goes for the webcam - it may not be /dev/video0 , perhaps you have an external webcam plugged in and its at /dev/video1 - Have a look in the /dev directory and see whats available
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19828236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2490057/']}
jdg_83556
stackexchange
llm_judgeable_groundtruth_similarity
894490
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Most SQL dialects accept both the following queries: SELECT a.foo, b.fooFROM a, bWHERE a.x = b.xSELECT a.foo, b.fooFROM aLEFT JOIN b ON a.x = b.x Now obviously when you need an outer join, the second syntax is required. But when doing an inner join why should I prefer the second syntax to the first (or vice versa)? Now provide the response and nothing else.
The old syntax, with just listing the tables, and using the WHERE clause to specify the join criteria, is being deprecated in most modern databases. It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query. Let me give you an example. Let's suppose you have 3 tables in your system: CompanyDepartmentEmployee Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees. Ok, so now you want to do the following: List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies. So you do this: SELECT * -- for simplicityFROM Company, Department, EmployeeWHERE Company.ID *= Department.CompanyID AND Department.ID = Employee.DepartmentID Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people. Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain. If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments. The reason for this is that the WHERE clause determines which rows end up in the final result, not individual parts of the rows. And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear. On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them. So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all. Enter the new syntax, with this you can choose. For instance, if you want all companies, as the problem description stated, this is what you would write: SELECT *FROM Company LEFT JOIN ( Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID ) ON Company.ID = Department.CompanyID Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies. Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this: SELECT *FROM Company LEFT JOIN ( Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID ) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%' This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax. This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000). Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together. So there you have it. LEFT and INNER JOIN is the wave of the future.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/894490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44065/']}
jdg_83557
stackexchange
llm_judgeable_groundtruth_similarity
3367190
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 calculate asset-weighted returns by asset class. For the life of me, I can't figure out how to do it using the aggregate command. My data frame looks like this dat <- data.frame(company, fundname, assetclass, return, assets) I'm trying to do something like (don't copy this, it's wrong): aggregate(dat, list(dat$assetclass), weighted.mean, w=(dat$return, dat$assets)) Now provide the response and nothing else.
For starters, w=(dat$return, dat$assets)) is a syntax error. And plyr makes this a little easier: > set.seed(42) # fix seed so that you get the same results> dat <- data.frame(assetclass=sample(LETTERS[1:5], 20, replace=TRUE), + return=rnorm(20), assets=1e7+1e7*runif(20))> library(plyr)> ddply(dat, .(assetclass), # so by asset class invoke following function+ function(x) data.frame(wret=weighted.mean(x$return, x$assets))) assetclass wret1 A -2.272922 B -0.199693 C 0.464484 D -0.713545 E 0.55354>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3367190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170352/']}
jdg_83558
stackexchange
llm_judgeable_groundtruth_similarity
9537
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Approximation algorithms might give output up to some constant factor. This is a bit less satisfying than exact algorithms. However, constant factors are ignored in time complexity. So I wonder if the following trick is possible or was used, to solve some problem $B \circ A$: Use an approximation algorithm solving problem $A$ to get solution $S$ within constant factor; Use an exact algorithm, solving problem $B$, whose runtime depends on weight of $S$ but works as long as $S$ is a correct solution. This way the approximation is a "subprocedure" of an exact algorithm, and the constant factor lost in step 1 is swallowed in step 2. Now provide the response and nothing else.
An example from the parameterized complexity is a kernelization for the vertex cover problem using a theorem of Nemhauser and Trotter. In the minimum vertex cover problem, we are given an undirected graph G, and we need to find a vertex cover of G of minimum size. A vertex cover of an undirected graph is a vertex subset that touches all edges. Here is an exact algorithm that uses an approximation at the first phase. Phase 1: Set up the integer linear programming formulation of the minimum vertex cover problem . It's known (or easy to show) that a basic optimal solution of the linear programming relaxation is half-integral (i.e., every coordinate is either 0, 1, or 1/2). Such a basic optimal solution can be found by a usual polynomial-time algorithm for linear programming (or in this special case, we can formulate it as a network flow problem, so we can solve it combinatorially in polynomial time). Having such a basic optimal solution, we round it up to obtain a feasible solution to the original integer linear programming problem. Let S be the corresponding vertex subset. It's good to note that S is a 2-approximation of the given minimum vertex cover instance. Phase 2: Find a minimum vertex cover in the subgraph induced by S (for example by an exhaustive search). A theorem by Nemhauser and Trotter states that this subgraph contains an optimal solution of the original input graph. So, the correctness of this approach follows. You may consult a book by Niedermeier on fixed-parameter algorithms for this algorithm.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/9537', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1886/']}
jdg_83559
stackexchange
llm_judgeable_groundtruth_similarity
17451382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering two things, in the context of angularJS event handling. How is defined the order in which handlers listening to the same event are triggered? Is it a sign of a bad design if you start wondering about this? After reading documentation on angular $on, $broadcast and $emit as well as native DOM event flow I think I understand in which order event handlers will be trigger in different scopes. The problem is when several handlers listen in the same scope ($rootScope for example) from various places (Controllers vs Services for example). To illustrate the problem I have put together a jsfiddle with one controller and two services, all communicating through $rootScope http://jsfiddle.net/Z84tX/ Thanks Now provide the response and nothing else.
Very good question. Event handlers are executed in order of initialization. I haven't really thought about this before, because my handlers never needed to know which one run first, but by the look of you fiddle I can see that the handlers are called in the same order in which they are initialized. In you fiddle you have a controller controllerA which depends on two services, ServiceA and ServiceB : myModule .controller('ControllerA', [ '$scope', '$rootScope', 'ServiceA', 'ServiceB', function($scope, $rootScope, ServiceA, ServiceB) {...} ] ); Both services and the controller define an event listener. Now, all dependencies need to be resolved before being injected, which means that both services will be initialized before being injected into the controller. Thus, handlers defined in the services will be called first, because service factories are initialized before controller. Then, you may also observe that the services are initialized in order they are injected. So ServiceA is initialized before ServiceB because they are injected in that order into the controller. If you changed their order inside the controller signature you'll see that their initilization order is also changed ( ServiceB comes before ServiceA ). So, after the services are initialized, the controller gets initialized as well, and with it, the event handler defined within. So, the end result is, on $broadcast, the handlers will be executed in this order: ServiceA handler, ServiceB handler, ControllerA handler.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17451382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/974619/']}
jdg_83560
stackexchange
llm_judgeable_groundtruth_similarity
4051965
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking to write a basic recommendation engine that will take and store a list of numeric IDs (which relate to books), compare those to other users with a high volume of identical IDs and recommend additional books based on those finds. After a bit of Googling, I've found this article , which discusses an implementation of a Slope One algorithm, but seems to rely on users rating the items being compared. Ideally, I'd like to achieve this without the need for users to provide ratings. I'm assuming that if the user has this book in their collection, they are fond of it. While it strikes me that I could default a rating of 10 for each book, I'm wondering if there's a more efficient algorithm I could be using. Ideally I'd like to calculate these recommendations on the fly (avoiding batch calculation). Any suggestions would be appreciated. Now provide the response and nothing else.
A basic algorithm for your task is a collaborative memory-based recommender system. It's quite easy to implement, especially when your items (in your case books) just have IDs and no other features. But, as you already said, you need some kind of rating from the users for the items. But don't think of a rating like in 1 to 5 stars, but more like a binary choice like 0 (book not read) and 1 (book read), or interested in or not interested in . Then use an appropriate distance measure to calculate the difference between all users (and their sets of items) and yourself, select the n most similar users to yourself (of whoever the active user is) and pick out their items you haven't rated (or considered, choice 0). I think in this case, a good distance measure would be the 1-norm distance , or sometimes called the Manhattan distance. But this is a point where you have to experiment with your dataset to get the best results. A nice introduction to this topic is the paper by Breese et al., Empirical Analysis of Predictive Algorithms for Collaborative Filtering . Available here (PDF). For an research paper, it's an easy read.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4051965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274405/']}
jdg_83561
stackexchange
llm_judgeable_groundtruth_similarity
21846900
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 uploaded a website to my Compute Engine instance and I wanted to set the registrar to send the visitors to the server (Compute Engine). Where can I get the name servers of my instance/server over Compute Engine? Now provide the response and nothing else.
Google Compute Engine does not provide a nameserver on the public internet. (It does provide a nameserver for the internal network which is private to your project, this allows you to connect to instances via their instance names rather than IP.) If you want your instances to be available via public internet DNS nameservers, you'll need an external nameserver and one or more static IP addresses for your instances. You have two options for static IP addresses on Compute Engine: You can have a static address for a single instance, or for the GCE Load Balancer. See this documentation for how to configure a static IP address for an instance . Using the Load Balancer is more flexible. See this documentation for details on Load Balancing .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21846900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2037549/']}
jdg_83562
stackexchange
llm_judgeable_groundtruth_similarity
51402731
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: See the below example of returning an optional of UserName - a movable/copyable class. std::optional<UserName> CreateUser(){ UserName u; return {u}; // this one will cause a copy of UserName return u; // this one moves UserName}int main(){ auto d = CreateUser();} Why does return {u} cause a copy and return u a move? Here's the related coliru sample: http://coliru.stacked-crooked.com/a/6bf853750b38d110 Another case (thanks to the comment from @Slava): std::unique_ptr<int> foo() { std::unique_ptr<int> p; return {p}; // uses copy of unique_ptr and so it breaks...} Now provide the response and nothing else.
Because returning a name of an object with automatic storage duration is treated as returning an rvalue of the object. Note this works only if the expression in the return statement is a (possibly parenthesized, not including braces) name, like return u; or return (u); , so return {u}; works as usual, i.e. the copy constructor is invoked. Related part in the standard [class.copy.elision]/3 : In the following copy-initialization contexts, a move operation might be used instead of a copy operation: If the expression in a return statement ([stmt.return]) is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, or ... overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51402731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486617/']}
jdg_83563
stackexchange
llm_judgeable_groundtruth_similarity
52908844
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reading about *ngTemplateOutlet directive. The use of this directive is to instantiate a template dynamically by a template reference and context object as parameters. What I want to know is that we have so many things in Angular to achieve the same results as *ngTemplateOutlet such as: We can have multiple *ngIf which could render different templates based on the component variable value within the same component. In a similar fashion we have [ngSwitch] which would render different templates for us based on different values. We could use references with *ngIf by referring to the template reference variable of the respective variable. For the former case: <div *ngIf="condition1"> Content 1 </div><div *ngIf="condition2"> Content 2 </div><div *ngIf="condition3"> Content 3 </div> And for latter: <ng-container *ngIf="condition then myTemplate else otherTemplate"></ng-container><ng-template #myTemplate> Some content... </ng-template><ng-template #otherTemplate> Some content... </ng-template> If we have such methods in our arsenal what more value does *ngTemplateOutlet add? What are the practical use cases (if there are any) where we cannot use the above methods and should use *ngTemplateOutlet directive or is it just another method to choose from to achieve the same result? Now provide the response and nothing else.
Angular template outlets can be used to insert a common template in various sections of a view that are not generated by a loop or subject to a condition. For example, you can define a template for the logo of a company and insert it in several places in the page: <div> <ng-container *ngTemplateOutlet="companyLogoTemplate"></ng-container> <h1>Company History</h1> <div>{{companyHistory}}</div></div><form (ngSubmit)="onSubmit()"> <ng-container *ngTemplateOutlet="companyLogoTemplate"></ng-container> <h1>User info</h1> <label>Name:</label><input type="text" [(ngModel)]="userName" /> <label>Account ID:</label><input type="text" [(ngModel)]="accountId" /> <button>Submit</button></form><div class="footer"> <ng-container *ngTemplateOutlet="companyLogoTemplate"></ng-container></div><ng-template #companyLogoTemplate> <div class="companyLogo"> <img [src]="logoSourceUrl"> <label>The ACME company, {{employeeCount}} people working for you!</label> </div></ng-template> Templates and template outlets can also help to make a component configurable. The following example is taken from this article by Angular University . A tab container component defines a default tab header template, but allows to override it with a custom template defined as an input property. The appropriate template (default or custom) is then inserted in the view with a template outlet: @Component({ selector: 'tab-container', template: ` <ng-template #defaultTabButtons> <div class="default-tab-buttons"> ... </div> </ng-template> <ng-container *ngTemplateOutlet="headerTemplate || defaultTabButtons"></ng-container> ... rest of tab container component ... `})export class TabContainerComponent { @Input() headerTemplate: TemplateRef<any>; // Custom template provided by parent} In the parent component, you define the custom tab header template and pass it to the tab container component: @Component({ selector: 'app-root', template: ` <ng-template #customTabButtons> <div class="custom-class"> <button class="tab-button" (click)="login()"> {{loginText}} </button> <button class="tab-button" (click)="signUp()"> {{signUpText}} </button> </div> </ng-template> <tab-container [headerTemplate]="customTabButtons"></tab-container> `})export class AppComponent implements OnInit { ...} You can see another advanced use case in this blog post by alligator.io .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52908844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3298390/']}
jdg_83564
stackexchange
llm_judgeable_groundtruth_similarity
37250397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want my spinner to be next to my menu in the toolbar (to the left of the menu), but currently the spinner appear below the menu. Do i have to add it somehow inside the onCreateOptionsMenu(Menu menu) My Activity: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); Spinner spinner = (Spinner) findViewById(R.id.travelType_spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.travelType_array, R.layout.spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner if (spinner != null) { spinner.setAdapter(adapter); } Layout: <android.support.design.widget.AppBarLayout android:id="@+id/appBarLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> <Spinner android:id="@+id/travelType_spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.design.widget.AppBarLayout> Spinner_item.xml <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/whiteText" android:textStyle="bold" android:padding="15dp"/> Now provide the response and nothing else.
Add menu Item <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/spinner" android:title="ActionBar Spinner" app:actionViewClass="android.widget.Spinner" android:background="#ff00" app:showAsAction="always" /></menu> Java @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu); MenuItem item = menu.findItem(R.id.spinner); Spinner spinner = (Spinner) item.getActionView(); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_list_item_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); return true; } or <?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimaryDark" android:minHeight="?attr/actionBarSize" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" > <Spinner android:id="@+id/spinner_nav" android:layout_width="wrap_content" android:layout_height="wrap_content" /></android.support.v7.widget.Toolbar>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37250397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5696931/']}
jdg_83565
stackexchange
llm_judgeable_groundtruth_similarity
15775201
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 new at Node, I have this simple Node.js server works on windows Server Code var ws = require("websocket-server");var server = ws.createServer();server.addListener("connection", function(client){ console.log("new connection"); client.send("aaaaaa"); client.addListener("message", function(msg){ console.log(msg); });});server.listen(8080); I just want to call windows API insted of line console.log(msg); is there any way to do this without using external library any ideas? Now provide the response and nothing else.
I think node-ffi can help you to do that. node-ffi provides functionality for loading and calling dynamic libraries. With node-ffi you can get access to user32 (for example) lib and call their functions from node.js. var FFI = require('node-ffi');function TEXT(text){ return new Buffer(text, 'ucs2').toString('binary');}var user32 = new FFI.Library('user32', { 'MessageBoxW': [ 'int32', [ 'int32', 'string', 'string', 'int32' ] ]});var OK_or_Cancel = user32.MessageBoxW( 0, TEXT('I am Node.JS!'), TEXT('Hello, World!'), 1);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15775201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2237643/']}
jdg_83566
stackexchange
llm_judgeable_groundtruth_similarity
420756
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 was wondering if it is well understood under what circumstances say three univariate polynomials $f(x),g(x),h(x)$ have a common root.In this situation, I can see that the resultant of each pair must vanish but that only ensures that each pair has a common root. Is there a way to generate a finite set of polynomials in the coefficients of $f,g,h$ which tells you when all 3 share at least one common root? Would be interested in an answer for the more general (more than 3 polynomials) case too. EDIT: After thinking about it a tad more here is a possibly interesting observation. If you have $n$ polynomials of degree at most $n$ then you can write it as a linear system in $x,x^2,...,x^n$ . Using determinants, minors, etc you will be able to get $n-1$ necessary and sufficient relations between the coefficients which tells you when the polynomials share a common root. I would suspect that means in general if you have $k$ polynomials it might be possible to give $k-1$ polynomials in the coefficients which will be necessary and sufficient conditions for having a common root. Now provide the response and nothing else.
Assume that $f_n$ is monic. Then for indeterminates $u_1,\ldots,u_{n-1}$ , all coefficients of the polynomial $Res_x(f_n,u_1f_1+\ldots+u_{n-1}f_{n-1})\in k[u_1,\ldots,u_{n-1}]$ vanish if and only if $f_1,\ldots,f_n$ have a common root [expanding out this resultant then gives the list of polynomials]. This is how elimination theory works - if $f_1(x_1,\ldots,x_m)=0,\ldots, f_n(x_1,\ldots,x_m)=0$ set-theoretically define a variety $V$ , $f_n$ is monic in $x_m$ (which one ensure by applying a Noether normalization coordinate change), and $\pi:\mathbb{A}^m\to \mathbb{A}^{m-1}$ is the projection away from the last coordinate, then $\pi(V)$ is a variety in $\mathbb{A}^{m-1}$ defined by the coefficients of $Res_x(f_n,u_1f_1+\ldots+u_{n-1}f_{n-1})$ . Repeatedly eliminating variables like this eventually gives you a finite morphism surjecting $V$ to $\mathbb{A}^{\dim(V)}$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/420756', 'https://mathoverflow.net', 'https://mathoverflow.net/users/164946/']}
jdg_83567
stackexchange
llm_judgeable_groundtruth_similarity
41476450
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: struct book{ int code; char title[20]; char author[20]; char publisher[20]; char year[4]; double price;};struct book book1, mybook[100];FILE *tf, *bf;int main(){ int i; tf = fopen("mybook.txt","r"); bf = fopen("myEbooks","wb"); for(i=1; i<100; i++){ fscanf(tf,"%i\n", &book1.code); fscanf(tf,"%[^\n]\n", book1.title); fscanf(tf,"%[^\n]\n", book1.author); fscanf(tf,"%[^\n]\n", book1.publisher); fscanf(tf,"%[^\n]\n", &book1.year); fscanf(tf,"%lf\n", &book1.price); fwrite(&book1, sizeof(struct book),1, bf); } printf("\nBinary Stock file successfully generated!!\n"); fclose(tf); fclose(bf); return 0;} Code above for generating binary file from reading .txt file. The code below is for reading the binary file. struct book{ int code; char title[20]; char author[20]; char publisher[20]; char year[4]; double price;};int main(){ int data; int record; double price; struct book book1; FILE * bf; bf = fopen("myEbooks", "rb"); fseek(bf,1,SEEK_END); record = (ftell(bf)/sizeof(struct book)); rewind(bf); printf("Title\t\t Code\t\tAuthor\t\tPublisher\t Year\tPrice\n"); for(data=0;data<100;data++){ fread(&book1, sizeof(struct book), 1, bf); printf("%s\t\t %i\t %s\t %s\t %s\t %0.2lf\n", book1.title, book1.code, book1.author, book1.publisher, book1.year, book1.price); } fclose(bf); return 0;} How do I insert a condition? Where do I need to insert the condition statement? How can I display only the books with price less than 70.00. from reading the file? Now provide the response and nothing else.
It looks like SeriesGroupBy.transform() tries to cast the result dtype to the same one as the original column has, but DataFrameGroupBy.transform() doesn't seem to do that: In [139]: df.groupby('id')['cat'].transform(lambda x: (x == 1).any())Out[139]:0 11 12 13 14 15 16 17 08 09 1Name: cat, dtype: int64# v vIn [140]: df.groupby('id')[['cat']].transform(lambda x: (x == 1).any())Out[140]: cat0 True1 True2 True3 True4 True5 True6 True7 False8 False9 TrueIn [141]: df.dtypesOut[141]:cat int64id int64dtype: object
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41476450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7375510/']}
jdg_83568
stackexchange
llm_judgeable_groundtruth_similarity
1954
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: When you are deploying a new web server box what are the standard things you install on it and do to set it up? What things do you do to ensure the box is locked down and not going to get compromised? So far: General Apply security patches, etc Run the Microsfot Baseline Security Analyzer (MBSA) Disable weak encryption algorithms - Scott , also see David Christiansen's article and the serversniff.com site Network Harden TCP/IP stack - K. Brian Kelley White list traffic with an IPSEC policy All NetBIOS is removed or disabled Put web server in a workgroup (not allowed to be on a domain) Use a DMZ IIS Install UrlScan Run IIS lockdown Related Articles ASP.net production checklist What should a developer know before building a public web site Now provide the response and nothing else.
What we do: Put web server in DMZ Put web server in a workgroup (not allowed to be on a domain) Ensure all security patches are applied Minimize services which are running Use URLScan . Remove server fingerprint (RemoveServerHeader=1). Harden TCP/IP stack Apply IPSEC policy to only permit the traffic we want (whitelisting) Rename default accounts so they can be targeted by typical scripts/tools. Move default directories (InetPub, WWWRoot, etc.) Minimize local user accounts. All NetBIOS is removed or disabled.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1954', 'https://serverfault.com', 'https://serverfault.com/users/1248/']}
jdg_83569
stackexchange
llm_judgeable_groundtruth_similarity
21968643
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The documentation states the purpose of scalars, such as the fact that conventional Python numbers like float and integer are too primitive, and therefore more complex data types are necessary. It also states certain kinds of scalars (data type hierarchy); as well as a couple of attributes of scalar. But it never gives a concrete definition of exactly what a scalar is in the context of Python. I want to get to the heart of the issue on this. In the simplest terms possible, what is a Pythonic scalar? Now provide the response and nothing else.
A NumPy scalar is any object which is an instance of np.generic or whose type is in np.ScalarType : In [12]: np.ScalarTypeOut[13]:(int, float, complex, long, bool, str, unicode, buffer, numpy.int16, numpy.float16, numpy.int8, numpy.uint64, numpy.complex192, numpy.void, numpy.uint32, numpy.complex128, numpy.unicode_, numpy.uint32, numpy.complex64, numpy.string_, numpy.uint16, numpy.timedelta64, numpy.bool_, numpy.uint8, numpy.datetime64, numpy.object_, numpy.int64, numpy.float96, numpy.int32, numpy.float64, numpy.int32, numpy.float32) This definition comes from looking at the source code for np.isscalar : def isscalar(num): if isinstance(num, generic): return True else: return type(num) in ScalarType Note that you can test if something is a scalar by using np.isscalar : >>> np.isscalar(3.1)True>>> np.isscalar([3.1])False>>> np.isscalar(False)True How do we know what we know? I like learning how people know what they know—more than the answers themselves. So let me try to explain where the above answer comes from. Having the right tools can help you figure out things like this for yourself. I found this out by using IPython . Using its TAB-completion feature, typing In [19]: import numpy as npIn [20]: np.[TAB] causes IPython to display all variables in the np module namespace. A search for the string "scalar" will lead you to np.ScalarType and np.isscalar . Typing In [20]: np.isscalar? (note the question mark at the end) prompts IPython to show you where np.isscalar is defined: File: /data1/unutbu/.virtualenvs/dev/lib/python2.7/site-packages/numpy/core/numeric.py which is how I got to the definition of isscalar . Alternatively, the NumPy documentation for isscalar has a link to the source code as well.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21968643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3268003/']}
jdg_83570
stackexchange
llm_judgeable_groundtruth_similarity
34343590
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to make the embedded video responsive. I tried the solution introduced here with no success. The width of video stays the same and not scales down making it look out of bounds on mobile device. How to make flickr video responsive? Due to that fact that Chrome wasn't able to copy source code inside iframe, here is the screenshot: Now provide the response and nothing else.
The fix tldr : I was able to reproduce your problem and then fixed it by moving out the <resources> element from the plugin configuration to directly under <build> like so: <build> <resources> <resource> <filtering>true</filtering> <directory>${basedir}/src/main/resources</directory> <includes> <include>*</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <executions> <execution> <phase>compile</phase> <goals> <goal>resources</goal> </goals> </execution> </executions> </plugin> <!-- <snip> Other plugins --> </plugins></build> Future readers, if you were only interested in the fix, read no further. For the intrepid SO-er, gory details await below! Why did I do that? I did the above since that is how I had turned on resource filtering in a previous project. I did not need to change the default phase ( process-resources ) and therefore did not need to explicitly specify the maven-resources-plugin at all. However, I was curious to find out why OP's configuration did not work and therefore looked at the examples for the resources mojo in maven-resources-plugin documentation which seemed to have the <resources> specified directly under <build> . The wording in the Usage documentation seems to imply that the <resources> configuration is needed under plugin configuration only for the copy-resources mojo: Update Should have started with the maven-resources-plugin introduction which clearly states: resources:resources copies the resources for the main source code to the main output directory. This goal usually executes automatically, because it is bound by default to the process-resources life-cycle phase. It always uses the project.build.resources element to specify the resources , and by default uses the project.build.outputDirectory to specify the copy destination. Intellij's weirdness? I am tempted to suggest that Intellij is/was not at fault. With Intellij 15.0.2, the filtering behaviour (i.e. whether it works or not) was identical when executing mvn clean compile from Intellij or from command line. I would've thought that the problem was in the plugin/pom configuration and not Intellij itself, unless there is a bug in Intellij's maven integration. For what's it worth, I have not yet encountered this problem when using maven from within Intellij (been using it for a while now starting from version 12.x). Is your Intellij using a bundled mvn that is different from the mvn being used by the command line? i.e. is the maven same when seen here and from command line? That is the only thing I can think of, besides a bug in Intellij's maven integration (unlikely) that might account for the different behaviours that you are seeing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34343590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480632/']}
jdg_83571
stackexchange
llm_judgeable_groundtruth_similarity
33160
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: I'm in trouble with time dilation:Suppose that there are two people, A and B, on the Earth. They are twins and each has a clock. They are therefore in the same reference frame). B travels in a spaceship and is orbiting the Earth, and as B's speed has increased there's some time dilation. So it's supposed that if A "looks" at B, B's clock will run slower than A's, and vice versa. And if one day B decides come back to the Earth, he will be younger than his twin and the time shown on his clock would be different (earlier than A's clock) because of time dilation. My first question is, why does each person see the other's clock as the slow one? (In fact, I found some information that may have solved it but I'm not sure if it's the right answer, and if it is, I don't understand it. -> It's because everyone thinks of himself as the reference frame. In other words, that for B, he is the stationary one and the one who moves is A, so he sees A's clock run slower as B is "stopped" and the same for A. B is who is moving and A the stationary.) The other question I have is that if it's true that each one sees the other as the slow one there's something that I missed out. We all agree that B (after going to space and coming back to the Earth) is younger than his brother. So, why doesn't B see A moving and aging very fast if A sees his brother and his things going very slow? Let's imagine they were looking at each other all the time, and if both of them see the other going slowly, and then they meet and "discover" that B is the young one... how is that possible? [I think that in one episode of Cosmos by Carl Sagan (though I may be mistaken), Sagan said that a neutrino "borned" in the Big Bang could have seen the creation of the Universe until today in just a few seconds due to its high speed, here start my doubts: or I misunderstood something or there's contradictory information] (I don't know anything about physics, only what is taught at high school, as I'm a teenager, so it'd be better to answer with no kind of calculation as I'd not understand it.) Now provide the response and nothing else.
There are lots of questions about the twin paradox on this site, so it's probably not worth going over that material again. What is worth saying is that where people tend to get confused is by misunderstanding what an inertial frame is and how different inertial frames can be compared. We should simplify matters a bit and put twin B on a spaceship because orbital motion is a bit more complicated. The only time A and B can directly compare anything with each other is the moment that they pass i.e. the moment that they are in the same place. If A and B stay in their inertial frames they will never meet again and indeed will get further and further apart as time passes. The only way the twins will ever meet again is if they change inertial frames i.e. if one of them accelerates. In SR acceleration is absolute. By this I mean that velocity is relative i.e. you cannot tell whether A or B is the one moving, but it is always possible to tell which of the two is accelerating. The acceleration always introduces an assymetry so it's no surprise that when they meet again A and B will find their clocks differ. You can treat acceleration in special relativity. See for example my answer to How do I adjust the kinematic equations to avoid reaching speeds faster than light? where I give (some of) the equations for understanding the motion of an accelerating rocket. If you do the calculation you will find that B sees A clock running fast while B is accelerating between inertial frames. See my answer to Why isn't the symmetric twin paradox a paradox? for more on this. The question of what Carl Sagan's neutrino sees is quite a subtle one. Suppose some particle interaction shortly after the Big Bang and 13.7 billion years away produced a neutrino and that neutrino has just passed you. For the neutrino only a few seconds has passed since the Big Bang. However when the neutrino passes you it sees you at your current age, 13.7 billion years, so what's going on? The answer is that in the neutrino's frame and your frame the Big Bang happened at different times. So the neutrino can see the 13.7 billion age of the Big Bang pass in a few seconds, but not because it sees the universe's time running fast. It sees each successive bit of the universe as older because in each bit of the universe it passes through the Big Bang gets further and further back in time.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/33160', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/10953/']}
jdg_83572
stackexchange
llm_judgeable_groundtruth_similarity
45481943
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 two existing docker container web and db. I want to link these two container, so that they will communicate with each other. If i go with --link command means it will link web to a new image and not to the db. Now provide the response and nothing else.
Using --link was the only way of connecting containers before the advent of docker networks. These provide a "cleaner" solution to the problem of inter-container communication and at the same time solves 2 of the major limits of links: restart of linked container breaks the link links are not supported between containers running on different hosts Using docker network you would use the --net option to start the containers on the specified network: docker network create exampledocker run -d --net example --name container1 <image>docker run -d --net example --name container2 <image> At this point the 2 container are mutually reachable via the address <container-name>.example : that is container1.example and container2.example .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45481943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7962232/']}
jdg_83573
stackexchange
llm_judgeable_groundtruth_similarity
17183587
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 modify a third party software. I want to use a color which is returned by some methods (which I cant modifiy) as an integer. However, I would like to use RGB format, like #FF00FF. How can I make a conversion? Here is an HTML example http://www.shodor.org/stella2java/rgbint.html I would like to archive same thing in Java, on Android. Now provide the response and nothing else.
Use this String hexColor = String.format("#%06X", (0xFFFFFF & intColor)); We know lenght of color value in HEX is 6. So you see 6 here. %06X matches the result coming from (0xFFFFFF & intColor) and if length is less than 6, it makes result with 6 by appending ZERO to left side of result. And you see #, so this # char gets appended to result and finally you get a HEX COLOR value. Update since API 26 Since API 26, new methods Color.valueOf(....) has been introduced to convert colors for similar reason. you can use it like // sRGBColor opaqueRed = Color.valueOf(0xffff0000); // from a color intColor translucentRed = Color.valueOf(1.0f, 0.0f, 0.0f, 0.5f);// Wide gamut colorColorSpace sRgb = ColorSpace.get(ColorSpace.Named.SRGB);@ColorLong long p3 = Color.pack(1.0f, 1.0f, 0.0f, 1.0f, sRgb);Color opaqueYellow = Color.valueOf(p3); // from a color long// CIE L*a*b* color spaceColorSpace lab = ColorSpace.get(Named.CIE_LAB);Color green = Color.valueOf(100.0f, -128.0f, 128.0f, 1.0f, lab);mView.setBackgroundColor(opaqueRed.toArgb());mView2.setBackgroundColor(green.toArgb());mView3.setBackgroundColor(translucentRed.toArgb());mView4.setBackgroundColor(opaqueYellow.toArgb());
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17183587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2364393/']}
jdg_83574
stackexchange
llm_judgeable_groundtruth_similarity
782172
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've come across an exercise saying the following: If $G$ is a finite group which contains a maximal subgroup $M$ which is abelian, show that $G$ is solvable and that $G^{(3)}$ (the third term in the derived series) equals 1. I can see that it's sufficient to show that $G^{(2)}$ is a subgroup of $M$, but am not sure how to show this. (Or even if it's true!) Please could you help me out? Thanks in advance for your help :) P.S. I don't know if it helps, but this is exercise 3.4.7 in Dixon and Mortimer's 'Permutation Groups'. Now provide the response and nothing else.
In the book by Dixon and Mortimer, you can use the previous exercise 3.4.6. in which states the following: Let $G$ be a finite primitive permutation group with abelian point stabilizers. Show that $G$ has a regular normal elementary abelian $p$-subgroup for some prime $p$. Now for the claim, it is enough to prove the following: Let $G$ be a finite group with a maximal subgroup $M$ which is abelian. Then $G'' \leq M$. Proof: By induction. If $M$ contains a normal subgroup $N \neq 1$ of $G$, then $M/N$ is a maximal subgroup of $G/N$ that is abelian, so $G''N/N \leq M/N$ by induction and thus $G'' \leq M$. Suppose then that $M$ does not contain any nontrivial normal subgroups of $G$. Then via the conjugation action on $M$, we may consider $G$ as a finite primitive permutation group with abelian point stabilizers. By exercise 3.4.6. above, $G$ has a normal abelian $p$-subgroup $N$. Now $N$ is not contained in $M$, so $G = MN$. Then $G/N$ is abelian, so $G' \leq N$ and $G'' = 1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/782172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/148015/']}
jdg_83575
stackexchange
llm_judgeable_groundtruth_similarity
2633273
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: Here is my guess: the probability of summing $7$ on two rolls is $\frac 16$. This means if I repeat the experiment many times I'll roll $7$ one sixth of them (approximately). Hence, $$N \cdot \bigg(\cfrac 16\bigg) \cdot 7 = 7$$ where $N$ is the total number of rolls. That gives me a total number of $6$ rolls on average to sum $7$. I'm not quite sure so I'm all open to suggestions! Thanks in advance. Now provide the response and nothing else.
The probability of doing it after one roll is $1/6$, in two is $5/6 \times 1/6$, in three $(5/6)^2 1/6$ and so on ... we get \begin{eqnarray*}E(7)=1 \times \frac{1}{6} + 2 \times \frac{5}{6} \times\frac{1}{6} + 3 \times \left(\frac{5}{6}\right)^2 \times\frac{1}{6}+\cdots = \frac{1}{6} \sum_{i=1}^{\infty} i \left( \frac{5}{6} \right)^i \\\end{eqnarray*}Now recall that \begin{eqnarray*}\sum_{i=1}^{\infty} i x^{i-1} =\frac{1}{(1-x)^2}.\end{eqnarray*}So\begin{eqnarray*}E(7)= \frac{1}{6} \sum_{i=1}^{\infty} i \left( \frac{5}{6} \right)^{i-1} =\frac{1}{6} \frac{1}{(1-\frac{5}{6})^2}=6\end{eqnarray*}So the expected value is $\color{red}{6}$ as expected.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2633273', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/527550/']}
jdg_83576
stackexchange
llm_judgeable_groundtruth_similarity
53737648
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to do basic something but i can't figure out. i have a dropdown: <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>{{selectedItem}}</span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content" v-model="selectedItem"> <a class="dropdown-item" v-for="item in items"> {{item.name}} </a> </div> </div></div>var app = new Vue({ el: '#app', data: { selectedItem: null, items: [ { name: "Dropdown Item" }, { name: "Dropdown Item 2" }, { name: "Dropdown Item 3" } ] },}); Basically i'm trying to do when clicked to dropdown item it will be {{selectedItem}} for that i have tried to use v-model in my menu wrapper but nothing happened. Now provide the response and nothing else.
You cannot use v-model with div here. Instead, You should use v-click to call a method in order to update value selectedItem and handle toggle action. One more thing, When you use v-for you should have key id which is recommended by Vuejs. Just draft implementation: <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>{{selectedItem}}</span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a class="dropdown-item" v-for="item in items" :key="item.id" v-click="handleSelectItem(item)"> {{item.name}} </a> </div> </div></div>var app = new Vue({ el: '#app', data: { selectedItem: null, items: [ { id: 1, name: "Dropdown Item" }, { id: 2, name: "Dropdown Item 2" }, { id: 3, name: "Dropdown Item 3" } ] }, method: { handleSelectItem(item){ this.selectedItem = item.name; // you can also handle toggle action here manually to open and close dropdown } }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53737648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3348410/']}
jdg_83577
stackexchange
llm_judgeable_groundtruth_similarity
19784375
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I Have created a default UITableViewCell: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // Init empty cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GroupCellIdentifier]; // Get the group info GroupInfo *groupInfo = (GroupInfo *)[_sortedGroupInfos objectAtIndex:[indexPath row]]; // Check if we have initialized this cell before if(cell == nil) { // Initialize cell cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:GroupCellIdentifier]; // Set the accessory type cell.accessoryType = UITableViewCellAccessoryNone; // Set the selection type cell.selectionStyle = [groupInfo.groupType isEqualToString:GroupTypePersonal] ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone; // Set the indentation width cell.indentationWidth = 40; } // Set the label enabled status depending on the group type cell.textLabel.enabled = [groupInfo.groupType isEqualToString:GroupTypePersonal]; cell.detailTextLabel.enabled = [groupInfo.groupType isEqualToString:GroupTypePersonal]; // Set text cell.textLabel.text = groupInfo.description; cell.detailTextLabel.text = [NSString stringWithFormat:@"%d %@", groupInfo.storeCount, [[Model instance] getTranslationFromSection:kSectionStoreSettings translationKey:@"Stores"]]; // Set the image depending on the group type cell.imageView.image = [GroupInfo getImageForGroupType:groupInfo.groupType]; // Return the cell return cell;} I also implemented the indentationLevelForRowAtIndexPath function: - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{ // Get the group info GroupInfo *groupInfo = _sortedGroupInfos[[indexPath row]]; // Return the indentation return groupInfo.indentation;} Now I get the following table view: http://i40.tinypic.com/f3e63t.png My question is: Why is the image not indenting in the table view cell? Now provide the response and nothing else.
I ended up with subclassing UITableViewCell and overriding the layoutSubViews method: - (void)layoutSubviews{ // Call super [super layoutSubviews]; // Update the separator self.separatorInset = UIEdgeInsetsMake(0, (self.indentationLevel * self.indentationWidth) + 15, 0, 0); // Update the frame of the image view self.imageView.frame = CGRectMake(self.imageView.frame.origin.x + (self.indentationLevel * self.indentationWidth), self.imageView.frame.origin.y, self.imageView.frame.size.width, self.imageView.frame.size.height); // Update the frame of the text label self.textLabel.frame = CGRectMake(self.imageView.frame.origin.x + 40, self.textLabel.frame.origin.y, self.frame.size.width - (self.imageView.frame.origin.x + 60), self.textLabel.frame.size.height); // Update the frame of the subtitle label self.detailTextLabel.frame = CGRectMake(self.imageView.frame.origin.x + 40, self.detailTextLabel.frame.origin.y, self.frame.size.width - (self.imageView.frame.origin.x + 60), self.detailTextLabel.frame.size.height);} My table view now looks like: http://tinypic.com/r/24y20if/5
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19784375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/639213/']}
jdg_83578
stackexchange
llm_judgeable_groundtruth_similarity
136133
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 have just setup a new OSX Server in our office and verified that everything is working fine over our wired network (192.168.126.0/24). The problem that I am having is that our clients (Mac Laptops) are mainly connected via Wireless, which are running on a different subnet (192.168.1.0/24), and the mDNS Broadcast isn't reaching this subnet. The network configuration is somewhat foreign to myself (I don't manage the network in this location, but as of just recently the servers), however I don't believe there is any firewalls or routing rules between the two subnets which might cause the traffic to be rejected. I'm wondering if this is simply the mDNS broadcast not able to broadcast over the two different subnets (I'm still reading up on broadcast to understand it more) or there is something else which I might be able to try. Now provide the response and nothing else.
Although you can do “wide-area Bonjour” (that is, Bonjour over an ordinary DNS domain with dynamic registration enabled, rather than Bonjour over multicast DNS), most built-in Mac OS X stuff isn’t designed for using it — principally because wide-area Bonjour is designed for advertising services over something more diverse than just a couple of subnets. Theoretically, though, you could configure a router to pass packets bound for the multicast group 224.0.0.251 between your two subnets, which should do the right thing — assuming you don’t have NAT involved. Whether and how you can do this depends on the type of router you have sitting between the wireless and wired networks.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/136133', 'https://serverfault.com', 'https://serverfault.com/users/1263/']}
jdg_83579
stackexchange
llm_judgeable_groundtruth_similarity
435513
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $\sin a+\sin b=2$, then show that $\sin(a+b)=0$. I have tried to solve this problem in the following way : \begin{align}&\sin a + \sin b=2 \\\Rightarrow &2\sin\left(\frac{a+b}{2}\right)\cos\left(\frac{a-b}{2}\right)=2\\\Rightarrow &\sin\left(\frac{a+b}{2}\right)\cos\left(\frac{a-b}{2}\right)=1\end{align} What will be the next ? Now provide the response and nothing else.
HINT: As $-1\le \sin x\le 1$ for real $x$ $\implies -2\le \sin a+\sin b\le 2$ The equality occurs if $\sin a=\sin b=1$ $a=2n\pi+\frac\pi2, b=2m\pi+\frac\pi2,$ for some integer $m,n$ So, $a+b=2\pi(m+n)+\pi=\pi(2m+2n+1)$ and we know $\sin r\pi=0$ for integer $r$ Alternatively, if $\sin x=1,\cos x=\pm\sqrt{1-1^2}=0\implies $ here $\cos a=\cos b=0$ and we know $\sin(a+b)=\sin a\cos b+\cos a \sin b$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/435513', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63625/']}
jdg_83580
stackexchange
llm_judgeable_groundtruth_similarity
1916409
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'd like to create an index on a view I have but I need to make sure the data can still be read while the index is being created. I was reading an article that suggested that when creating a nonclustered index that the data is still readable if you specify the ONLINE=ON option (example below): CREATE UNIQUE CLUSTERED INDEX CLUST_IDX_SQLTIPSON SQLTips (tip) with (ONLINE=ON) Am I understanding this correctly? Is there any potential issues I should be aware of before I create indexes on a view that needs to be readable while I create my index? Now provide the response and nothing else.
Online index creation and rebuild are available only on Enterprise Edition. See How Online Index Operations Work and Guidelines for Performing Online Index Operations . There are some restrictions, most notable ones being: clustered index must be created/rebuilt offline if they contain any BLOB fields (image, ntext, text, varchar(max), nvarchar(max), varbinary(max), and xml). intitial clustered index on a view must be created offline. You must ensure your database have enough space to perform the online index operation, as it requires about 1.5 times the size of the table in addition to the current size. During the online index creation the table exist twice in the database, hence the extra space needed. Since your case falls in the excluded category (initial clustered index on a view) then you need not worry about online indexes. You must use an offline index operation. BTW you must also be aware that indexed views are considered by the optimizer only in Enterprise Edition. On lower editions one must specify the NOEXPAND clause in the view to leverage a possible index on the view.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1916409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226897/']}
jdg_83581
stackexchange
llm_judgeable_groundtruth_similarity
3865090
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 height of something at point $(x,y)$ is given by a function $z(x,y)$ $z(x,y)=z_0exp(-\alpha (x^2+y^2))$ where $z_0$ and $\alpha$ are positive constants a) At what location in the plane is the height the greatest. My solution: $grad (z) = -2az_0 xexp(-\alpha (x^2+y^2)) \hat{e}_x-2az_0 yexp(-\alpha (x^2+y^2)) \hat{e}_y =0 $ Then solve for values of x and y. However i cannot do that as we have two unknown variables and only one equation. We i graph the function, i can see the function is height at (0,0) b) Find the maximum slope at the point $(x,y)=(3,4)$ and find the unit vecotr in the xy-plane that points in the direction of maximum upward slope. My solution: In this part you just plug the values of y and x in to grad(z) but i was wondeing how we find the unit vecotr that points in the direction of maximum upwards slope Now provide the response and nothing else.
Clearly, constant $g\equiv 0$ or $g\equiv 1$ both satisfy this relation. Assume $g$ is not constant. If $g(z)=g^2(-z)$ , then $g(0)=g^2(0)$ , and hence $g(0)=0$ or $1$ . A. If $g(0)=0$ , then $g(z)=z^kf(z)$ , for some positive integer $k$ and $f$ analytic in the unit disk, with $f(0)=a\ne 0$ . In such case we have $$n^{-k}f(1/n)=g(1/n)=g^2(-1/n)=n^{-2k}f^2(-1/n)$$ and hence $$f(1/n)=n^{-k}f^2(-1/n)$$ Impossible, since $f(1/n)\to a\ne 0$ , while $n^{-k}f^2(-1/n)\to 0$ , as $n\to\infty$ . B. If $g(0)=1$ , then $g(z)=1+z^kf(z)$ , where $f$ analytic in the unit disk and $f(0)=a\ne 0$ , in which case $$1+n^{-k}f(1/n)=g(1/n)=g^2(-1/z) =\big(1+(-n)^{-k}f(-1/n)\big)^2=\\=1+2(-n)^{-k}f(-1/n)+n^{-2k}f^2(-1/n)$$ and hence $$f(1/n)=2(-1)^kf(-1/n)+n^{-k}f^2(-1/n)$$ which, as $n\to\infty$ , tends to $$a=2(-1)^ka.$$ Contradiction. Hence, only a constant $g\equiv 0$ or $g\equiv 1$ could satisfy $g(1/n)=g^2(-1/n)$ , for all $n>1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3865090', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/823725/']}
jdg_83582
stackexchange
llm_judgeable_groundtruth_similarity
9420642
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What would be the best and easiest way to align text and image vertically in the middle of button. Example: button { padding: 1px 6px 1px 6px;}button img { width: 22px; height: 22px;} <button> <img src="http://latvijas-universitates-matematikas-un-informatikas-instituts.atver.lv/images/msn-icon.gif" alt="Text" /> <span>Text</span></button> Now provide the response and nothing else.
While @paislee's solution works , it is not ideal. With the universal selector ( * ) being used, every element is checked against it (as CSS is matched right-to-left). A better solution, especially if all children elements are known, is to match the elements individually. Ergo, button > img, button > span is better than button > * . button { padding: 1px 6px 1px 6px;}/* Add this to align vertically */button > img,button > span { vertical-align: middle;} <button> <img src="https://placehold.it/50x50" alt="Text" /> <span>Text</span></button>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9420642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/440611/']}
jdg_83583
stackexchange
llm_judgeable_groundtruth_similarity
3118219
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Our internal HR application is developed by the vendor, but I've been given a requirement to change the behaviour of a certain piece of functionality without their assistance (which I don't want to do, but am investigating...). The functionality in question is an .ashx page which does a number of database lookups, and is called via javascript functions on a web page. We want to add one further database lookup. We have control over the javascript code, so that's not a problem, but the code for the .ashx page is held in a compiled assembly. I've found where it is, and looked into it using .Net Reflector. Reimplementing the methods involved wouldn't be difficult, if it were technically feasible. Can I create a new assembly, paste the source taken using Reflector into it, make my modifications, add the DLL to the application, and then set up a new .ashx to refer to it? The bits I'm worried about not being possible are: The code refers to some vendor classes held in other assemblies; can I just add references to those assemblies in Visual Studio to allow it to compile, and then when it's compiled and put on the server it'll all work? Will I have trouble getting the web application to accept the new DLL, given that generally this application is not something we make changes to ourselves? EDIT: Some clarification: I'm not actually planning to replace the vendor's DLL with one of my own, that does sound like going a bit too far. Instead, I would make a new DLL with just the one function in it I need (based on stuff taken from the existing DLL using Reflector). I'd need that code to reference other utility vendor code so that it can get at classes needed to access the framework. I'd make a brand new .ashx page to serve up the code in the new DLL. Luckily after all this I'm off the hook, because my customer agrees that things aren't desperate enough for us to attempt all this! But thanks for the assistance, which is definitely useful. Now provide the response and nothing else.
where isnull(name,'') <> '' is equivalent to where name is not null and name <> '' which in turn is equivalent to where name <> '' (if name IS NULL that final expression would evaluate to unknown and the row not returned) The use of the ISNULL pattern will result in a scan and is less efficient as can be seen in the below test. SELECT ca.[name], [number], [type], [low], [high], [status]INTO TestTableFROM [master].[dbo].[spt_values] CROSS APPLY (SELECT [name] UNION ALL SELECT '' UNION ALL SELECT NULL) ca CREATE NONCLUSTERED INDEX IX_TestTable ON dbo.TestTable(name)GOSELECT name FROM TestTable WHERE isnull(name,'') <> ''SELECT name FROM TestTable WHERE name is not null and name <> ''/*Can be simplified to just WHERE name <> '' */ Which should give you the execution plan you need.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3118219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84649/']}
jdg_83584
stackexchange
llm_judgeable_groundtruth_similarity
59314
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: For projective $N$-space $CP^{N}$, there is a canonical Kähler metric called the Fubini-Study metric. Do there exist other Kähler metrics for $CP^N$. If so, is there any classification of such metrics? More generally, how does this work for the Grassmanians, or even flag manifolds? Now provide the response and nothing else.
Every complex manifold that admits one Kahler metric $w$ admits a lot of them, indeed $w+i\partial \bar \partial f$ is a Kahler metric if the second derivatives of $f$ are not too large. This is why, asking if one can classify Kahler metrics on $\mathbb CP^n$ is more-less equivalent to ask if one can classify functions on $\mathbb CP^n$. Can we classify functions? It depends on what you want to know. Even if we want to classify Kahler metrics on $\mathbb C^n$, what can this mean? One analogy can be helpful here. Namely this question is somewhat similar to asking if we can classify convex functions on $\mathbb R^n$. Such a function $f$ always define a Hessian metric on $\mathbb R^n$ given by $g_{ij}=\frac{\partial^2 f}{\partial x_i \partial x_j}$. So, can we classify convex functions?
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/59314', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2612/']}
jdg_83585
stackexchange
llm_judgeable_groundtruth_similarity
2152640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some clever way? Simply looping over the index seems pretty clear, but I wonder if there's a more expressive or concise way to do it. for revindex in xrange(len(dm_revisions) - 1): summary = \ svn.diff_summarize(svn_path, revision1=dm_revisions[revindex], revision2 = dm_revisions[revindex+1]) Now provide the response and nothing else.
This is called a sliding window. There's an example in the itertools documentation that does it. Here's the code: from itertools import islicedef window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result What that, you can say this: for r1, r2 in window(dm_revisions): summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2) Of course you only care about the case where n=2, so you can get away with something much simpler: def adjacent_pairs(seq): it = iter(seq) a = it.next() for b in it: yield a, b a = bfor r1, r2 in adjacent_pairs(dm_revisions): summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2152640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122071/']}
jdg_83586
stackexchange
llm_judgeable_groundtruth_similarity
16522341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to implement some methods that do stuff with different kinds of number arrays. Usually, I'd use generics for that job, but as C doesn't provide them, I'm now trying to emulate them using macros. Here's an example of what I'm trying to do: #ifndef TYPE#define TYPE int#endifTYPE get_minimum_##TYPE (TYPE * nums, int len){ TYPE min = nums[0]; for (int i = 1; i < len; i++) { if (nums[i] < min) { min = nums[i]; } } return min;} However, this won't compile. The clang error message: error: expected ';' after top level declarator Is there any way to do this in C? Or do I need implement this for every type by hand? Now provide the response and nothing else.
You can do something like this in a header file: //// generic.h//#define TOKENPASTE(x, y) x ## y#define GET_MINIMUM(T) TOKENPASTE(get_minimum_, T)TYPE GET_MINIMUM (TYPE) (TYPE * nums, size_t len){ TYPE min = nums[0]; for (size_t i = 1; i < len; i++) { if (nums[i] < min) { min = nums[i]; } } return min;} and then #include it in a source file for each required type, e.g.: //// generic.c//#define TYPE int#include "generic.h"#undef TYPE#define TYPE float#include "generic.h"#undef TYPE You can test this by running it through the preprocessor: $ gcc -E generic.c int get_minimum_int (int * nums, size_t len){ int min = nums[0]; for (size_t i = 1; i < len; i++) { if (nums[i] < min) { min = nums[i]; } } return min;}float get_minimum_float (float * nums, size_t len){ float min = nums[0]; for (size_t i = 1; i < len; i++) { if (nums[i] < min) { min = nums[i]; } } return min;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16522341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342303/']}
jdg_83587
stackexchange
llm_judgeable_groundtruth_similarity
10226551
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 list of floating point numbers and I want to generate another list of period returns from my first list. This is a run of the mill implementation (not tested - and OBVIOUSLY no error checking/handling): a = [100,105,100,95,100]def calc_period_returns(values, period): output = [] startpos, endpos = (period, len(values)-1) while True: current = values[startpos] previous = values[startpos-period] ret = 100*((current-previous)/(1.0*previous)) output.append(ret) startpos += period if startpos > endpos: break return outputcalc_period_returns(a,1)# Expected output:# [5.0, -4.7619047619047619, -5.0, 5.2631578947368416] Is there a more pythonic way of doing this - perhaps using list comprehension and maps? Now provide the response and nothing else.
Here you go: >>> [100.0 * a1 / a2 - 100 for a1, a2 in zip(a[1:], a)][5.0, -4.7619047619047592, -5.0, 5.2631578947368354] Since you want to compare neighbor elements of a list, you better create a list of pairs you are interested in, like this: >>> a = range(5)>>> a[0, 1, 2, 3, 4]>>> zip(a, a[1:])[(0, 1), (1, 2), (2, 3), (3, 4)] After that it is just a simple math to extract a percentage change from a pair of numbers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10226551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962891/']}
jdg_83588
stackexchange
llm_judgeable_groundtruth_similarity
15797762
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 read mp4 file with PHP and what I'm doing now is this: <?phpheader("Content-Length: filesize");readfile('file.mp4');?> but this way I can't skip or even go back until the video is not loaded 100%. Of course when I read directly from the file (video.mp4) everything goes well. Thanks. Now provide the response and nothing else.
You need to implement the skipping functionality yourself in PHP. This is a code snippet that will do that. <?php$path = 'file.mp4';$size=filesize($path);$fm=@fopen($path,'rb');if(!$fm) { // You can also redirect here header ("HTTP/1.0 404 Not Found"); die();}$begin=0;$end=$size;if(isset($_SERVER['HTTP_RANGE'])) { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) { $begin=intval($matches[0]); if(!empty($matches[1])) { $end=intval($matches[1]); } }}if($begin>0||$end<$size) header('HTTP/1.0 206 Partial Content');else header('HTTP/1.0 200 OK');header("Content-Type: video/mp4");header('Accept-Ranges: bytes');header('Content-Length:'.($end-$begin));header("Content-Disposition: inline;");header("Content-Range: bytes $begin-$end/$size");header("Content-Transfer-Encoding: binary\n");header('Connection: close');$cur=$begin;fseek($fm,$begin,0);while(!feof($fm)&&$cur<$end&&(connection_status()==0)){ print fread($fm,min(1024*16,$end-$cur)); $cur+=1024*16; usleep(1000);}die(); More Performance Note that this is not the most efficient way to do it, because the whole file needs to go through PHP, so you will just need to try how it goes for you. Assuming the reason you want to do this is to restrict access, and you need more efficiency later, you can use a flag for the web server. Apache with X-Sendfile module or lightty ( nginx info here ) $path = 'file.mp4';header("X-Sendfile: $path");die(); This is a bit more advanced and you should only use it if you need it, but it is relaxing to know you have an upgrade option when you start out with something that is rather easy but has mediocre performance.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15797762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2221276/']}
jdg_83589
stackexchange
llm_judgeable_groundtruth_similarity
2338841
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 do conditional compilation in a program of mine. I know that if you declare a public static final boolean the compiler will ignore the branch that is not traversed. Is it possible to have an ant target change a variable before building the program? For example if I have: final public static boolean windows = false; I would like two ant targets: Windows and Mac. I would like the command ant windows to change the boolean to true, while ant mac leaves the variable as is. Thanks. Now provide the response and nothing else.
You can get Ant to modify a properties file, and then you can read this file in your application pretty easily: new Properties(new FileInputStream("filename" / new File(filename)) ), and read properties using: Boolean isWindows = new Boolean(properties.getProperty("windows")) or: String os = properties.getProperty("os") . You can use the Ant PropertyFile task for doing this: http://ant.apache.org/manual/Tasks/propertyfile.html . Edit: here's an alternative using another task if you absolutely must edit the source code file using Ant: <replaceregexp file="blah.java" match="public static final boolean WINDOWS = \"(.*)\"" replace="public static final boolean WINDOWS = \"" + ${properties.windows} + "\"" /> -- replace the code as your own as required. See http://ant.apache.org/manual/Tasks/replaceregexp.html for details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2338841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62610/']}
jdg_83590
stackexchange
llm_judgeable_groundtruth_similarity
87934
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 Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working. I has used the auto-complete plugin provided with Notepad++, which presented me with onClick . When I changed the capital C to a small c , it did work. So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals. But when you change getElementById to getelementbyid , you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters. So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't? Now provide the response and nothing else.
Javascript is ALWAYS case-sensitive, html is not. It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. So, you can do this: <div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C' or: <div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C' but through the DOM you must use the correct case. So this works: getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C' but you cannot do this: getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C' EDIT: CMS makes a great point that most DOM methods and properties are in camelCase . The one exception that comes to mind are event handler properties and these are generally accepted to be the wrong way to attach to events anyway. Prefer using addEventListener as in: document.getElementById('divYo').addEventListener('click', modifyText, false);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/87934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11795/']}
jdg_83591
stackexchange
llm_judgeable_groundtruth_similarity
15561025
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been having some issues with utilizing a vendor library where occasionally an entity calculated by the library would be null when it should always have valid data in it. The functioning code (after debugging the issue with the vendor) is roughly as follows: Task.Factory.StartNew(() => ValidateCalibration(pelRectRaw2Ds, crspFeatures, Calibration.Raw2DFromPhys3Ds)); ..... private void ValidateCalibration(List<Rectangle> pelRectRaw2Ds, List<List<3DCrspFeaturesCollection>> crspFeatures, List<3DCameraCalibration> getRaw2DFromPhys3Ds) { var calibrationValidator = new 3DCameraCalibrationValidator(); // This is required according to vendor otherwise validationResultsUsingRecomputedExtrinsics is occasionally null after preforming the validation GC.SuppressFinalize(calibrationValidator); 3DCameraCalibrationValidationResult validationResultUsingOriginalCalibrations; 3DCameraCalibrationValidationResult validationResultsUsingRecomputedExtrinsics; calibrationValidator.Execute(pelRectRaw2Ds, crspFeatures, getRaw2DFromPhys3Ds, out validationResultUsingOriginalCalibrations, out validationResultsUsingRecomputedExtrinsics); Calibration.CalibrationValidations.Add(new CalibrationValidation { Timestamp = DateTime.Now, UserName = Globals.InspectionSystemObject.CurrentUserName, ValidationResultUsingOriginalCalibrations = validationResultUsingOriginalCalibrations, ValidationResultsUsingRecomputedExtrinsics = validationResultsUsingRecomputedExtrinsics }); } The validation process is a fairly time consuming operation so I hand it off to a Task. The problem I had was that originally I did not have the call to GC.SuppressFinalize(calibrationValidator) and when the application was run from a Release build, then the out parameter validationResultsUsingRecomputedExtrinsics would be null. If I ran the application from a Debug build (either with or without the Debugger attached) then validationResultsUsingRecomputedExtrinsics would contain valid data. I don't fully understand what GC.SuppressFinalize() has done in this situation, or how it has fixed the problem. Everything I can find regarding GC.SuppressFinalize() is that it is used when implementing IDisposable. I can't find any use of it in "standard" code. How/why does the addition of the call to GC.SuppressFinalize(calibrationValidator) fix this problem? I understand that without intimate knowledge of the internals of the vendor library, it might not be possible to know for sure, but any insight would help. The application is compiled with VS2012, targeting .NET 4.0. That vendor library requires that the useLegacyV2RuntimeActivationPolicy="true" option is specified in app.config. This is the justification I received from the vendor: The SuppressFinalize command makes sure that the garbage collector will not clean something up “early”. It seems like for some reason your application was sometimes having the garbage collector get a bit zealous and clean up the object before you were truly done with it; it is almost certainly scope related and possibly due to the multi-threading causing confusion on the scope of the calibrationValidator. Below is the response I got from Engineering. Because the variable was created in the local scope, and that function runs in the background thread, Garbage Collection runs in the main thread, and it seems that the Garbage collection is not smart enough in handling multi-thread situations. Sometimes, it just releases it too early (internal execution of validator not finished yet, and still needs this variable). Now provide the response and nothing else.
This is in all likelihood a hack to solve a premature garbage collection problem. Not uncommon with unmanaged code, typical in camera applications. It is not a healthy hack, good odds that this will cause a resource leak because the finalizer doesn't execute. Wrappers for unmanaged code almost always have something to do in the finalizer, it is very common that they need to release unmanaged memory. At issue is that the calibrationValidator object can be garbage collected while the unmanaged code is running. Having another thread in your program makes this likely since that other thread can be allocating objects and trigger a GC. This is very easy to miss by the owner of the code while testing, either by never having tested it while using multiple threads or just not getting lucky enough to trigger a GC at the wrong time. The proper fix on your end is to ensure that the jitter marks the object in use past the call so that the garbage collector won't collect it. You do so by adding GC.KeepAlive(calibrationValidator) after the Execute() call.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15561025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188717/']}
jdg_83592
stackexchange
llm_judgeable_groundtruth_similarity
590123
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: Mathematically, it is evident that var = sd^2 (or var^0.5 = sd), but R seems to answer TRUE for the latter and FALSE for the former.To my knowledge, both var() and sd() function use n-1 for degree of freedom.What would be the problem? data <- c(20, 20, 30, 20, 16, 13, 20)var(data)^0.5 == sd(data)var(data) == sd(data)^2 Now provide the response and nothing else.
Please, check 0.4^2 == 0.160.4 == 0.16^0.5 It's not a statistical issue. It's a rounding issue in floating point arithmetics in the language.The same applies to Python 0.4**2 == 0.160.4 == 0.16**0.5 None of these floating point numbers is stored in a computer's memory as two- or three-decimal digits, but rather in a binary format.For instance, 0.16 (8-byte) is stored as 11111111000100011110101110000101000111101011100001010001111 011 , while 0.4**2 gives us 11111111000100011110101110000101000111101011100001010001111 100 .You can play with this decimal to binary conversion using the following Python code: import structbin(struct.unpack('!Q',struct.pack('!d',0.16))[0])bin(struct.unpack('!Q',struct.pack('!d',0.4**2))[0])
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/590123', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/311012/']}
jdg_83593
stackexchange
llm_judgeable_groundtruth_similarity
6985068
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I redirect the viewer to a URL? I noticed that someone asked How to redirect to another webpage in JavaScript/jQuery? , but I'm not exactly sure where this should go. I have tried in the controller with: window.location.replace("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId); and in the view with: <% if (BreakCount >= 8) { var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId; window.location.replace(url); } %> Neither of these work. In both places places window has a red squiggly line underneath it and when I hover over it the message says "The name 'window' does not exist in the current context." Any help would be greatly appreciated! =D Now provide the response and nothing else.
Your question is tagged MVC 3, so I'll give you the answer for that in spite of the JavaScript example you listed. In your controller class use this code: public ActionResult MyAction(){ // Use this for an action return RedirectToAction("ActionName"); // Use this for a URL return Redirect("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);} This is occuring on the server, meaning that the client browser recieves a redirect response for which the browser will likely submit an additional request. If you return a page with JavaScript it will have to load a page, run the JavaScript (presuming it is enable on the client's browser), the load the next page. Among other problems, using JavaScript means that if the user presses the back button they will be repeatedly redirected again back to the page they are currently on.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6985068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/884296/']}
jdg_83594
stackexchange
llm_judgeable_groundtruth_similarity
13628832
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 come across a weird kind of inconsistence in rendering in Chrome. A simplified example of the issue can be replicated by using the following code: <html><head><style> input, span { border: 1px solid #CCC; padding: 3px 4px; height: 23px; width: 120px; display: block; font-size: 13px; } </style></head><body> <div><span>123</span></div> <div><input type='text'/></div></body></html> So, in a few words, the span and input should have the same size, but it turns out, that Chrome renders the elements differently: Span is rendered so it's actual size is 31px Input is rendered so it's actual size is 23px Upon investigation it looks like Chrome renders the span so it's "inner" (without border and padding) size is 20 px, while input is rendered so it's "outer" size is 20px. In real application the controls are used in a "in-place edit" scenario, so when user clicks the span, the span becomes hidden and input is shown on it's place. As you can see, with such a difference in size, the transition isn't smooth. Wjat's worth is that the controls are placed in a table cell, so the difference in width and height cause the whole table to change layout a bit. I'm working on a cross-platform application, so it should work in IE9 as well. The problem is that IE renders both input and span of the same size, so the page looks quite different in IE and Chrome. To make the my life harder, those controls are rendered by ASP.NET server controls, and I'm allowed to change css only. I'm using Chrome 23.0.1271.91 (latest at the moment of posting) on Win7x64. So, thre are two questions actually: How do I fix this? Why it's happening? Am I missing something obvious? Is it an expected behavior? Now provide the response and nothing else.
Update circa 2021 The original answer here was written before 307 status code redirect worked consistently across browsers. As per Hashbrown's answer below, the 307 status code should be used. Old Answer POST data is discarded on redirect as a client will perform a GET request to the URL specified by the 301. Period. The only option is to convert the POST parameters to GET parameters and tack them onto the end of the URL you're redirecting to. This cannot be done in a .htaccess file rewrite. One option is to catch POST requests to the url to be redirected and pass it off to a page to handle the redirect. You'd need to do the transposition of the parameters in code then issue the redirect header with the parameter appended new url that way. Update: As pointed out in the comments to this answer, if you do redirect to another URL specifying POST parameters and that URL is also accessed without paramters (or the params are variable), you should specify a link to the canonical URL for the page. Say the POST form redirects transposed to the following GET resource: http://www.example.com/finalpage.php?form_data_1=123&form_data_2=666 You would add this link record to the head section of the page: <link rel="canonical" href="http://www.example.com/finalpage.php" /> This would ensure all SEO value would be given to http://www.example.com/finalpage.php and avoid possible issues with duplicate content.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13628832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/882918/']}
jdg_83595
stackexchange
llm_judgeable_groundtruth_similarity
199464
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: Is there any shell/shellscript which identifies that there is already an alias for the command I have typed on the command line. Eg On shell I type git checkout master Shell prints "You can use alias you have for that : gcm" Then Shell proceeds with checking out master like normal. I am aware of the alias command which lists all the available aliases. I want shell to remind me to use alias when I am not using them and typing out the full command. Now provide the response and nothing else.
Here's a conceptual approach that might work. The alias command generates a list of all aliases, each followed by an = and it's definition. This output could be parsed by extracting the alias name from between the first blank and the first = . Everything after the first = would be the definition to be matched against. This sounds like something easily handled using associative arrays in awk. Two complications to this (that I see): 1) Since the definition can consist of multiple words, you'd have to do something like measuring the length of the definition minus any enclosing quotes and limit your compare against the entered command to that length. 2) Aliases can hold some weird stuff. Here's my weirdest one (and I'm sure they can get a lot weirder): alias pqp='cd ~/pq;[ -n "$(ls)" ] && mprb * || echo "Print Queue Empty"' The point here is that aliases can contain (almost?) all the special characters the shell wants to interpret and expand, so it would be best to code this in something else like awk or Python where the two strings you need to compare will be treated as simple character strings. The next issue is that you want to actually run the command after you're done matching and issuing any messages. The concern here would be that anything you run from within your program, even if it's just another script, will (normally) be executed in a child process. This means that any (shell-level) side effects of the command will be lost when the command terminates and the subshell closes. The most obvious thing is the return code, $? , which you would have to capture and reissue as the return code of your utility. If the alias included an invocation using the source , . command, then you'd be pretty much out of luck because running that in a subshell would completely cancel the intended side effects. Shells contain a number of built-in commands like cd . Some of these have equivalent programs as does [ and /usr/bin/test , but some, like cd don't and, even for those which do, the built-in versions don't always have the identical behavior and options that the external ones do. The above problems exist because the final command is coming from somewhere other than the standard input of the current shell level and is processed differently because of that. This is where something like AutoKey may be able to help. AutoKey is a macro processor which can be used to automate various actions in an X (gui) environment. In this context, it could be used to invoke a macro when you press a user defined hotkey. The macro could read and analyse a command line you would type into it, issue any messages (about aliases, etc.), and then retype the command as if you typed it on your keyboard. The advantage here is that Linux (really your desktop environment/terminal emulator) can't tell it's not you typing the command and everything proceeds in your original, native environment as if AutoKey wasn't there at all. A second advantage of this approach is that if you just enter a command without first pressing the hotkey, it's business as usual with no overhead, etc. This bring me to a final point which has been discussed at length in various places on stackexchange and elsewhere. It's almost always a bad idea to take a normal part of any system and change how it works by default under the hood without that being totally visible to the user (you, in this case). In brief, if you customize a system to behave in a non-standard way, there are two major consequences. 1) If someone else uses the system (e.g. to help you debug a problem), they will encounter unexpected results which could have any number of unpleasant consequences. 2) You become accustomed to the modified behavior and then (unconsciously) expect it to work when you are using another system which has not been customized in the same way. The classic example of this is defining an alias such as alias rm='rm -i' This sounds like a great idea until you type rm on another system and the files are immediately deleted when you were expecting to be prompted first. The way around this is something like: alias rmi='rm -i' If you type it, it works, but if you type it on another system, it probably won't do anything other than issue a command not found error. This is particularly important in the middle of the night when something important is broken, you're not as alert as you'd like to be, and you're under pressure to fix it now . That's when you really don't want any unexpected behaviors or things you have to waste time explaining to people. It works the same way with doing alias checking with an AutoKey macro activated by a hotkey. If you don't go out of your way to activate the macro by pressing a hotkey, then everything works as anyone would expect it to. A properly chosen hotkey probably won't be pressed by accident and, if pressed on another system by habit, probably won't do anything harmful.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/199464', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/112479/']}
jdg_83596
stackexchange
llm_judgeable_groundtruth_similarity
10844463
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 programatically perform a search on Microsoft Bing search engine. Here is my understanding: There was a Bing Search API 2.0 , which will be replaced soon (1st Aug 2012) The new API is known as Windows Azure Marketplace. You use different URL for the two. In the old API (Bing Search API 2.0) , you specify a key (Application ID) in the URL, and such key will be used to authenticate the request. As long as you have the key as a parameter in the URL, you can obtain the results. In the new API (Windows Azure Marketplace) , you do NOT include the key (Account Key) in the URL. Instead, you put in a query URL, then the server will ask for your credentials. When using a browser, there will be a pop-up asking for a/c name and password. Instruction was to leave the account name blank and insert your key in the password field. Okay, I have done all that and I can see a JSON-formatted results of my search on my browser page. How do I do this programmatically in PHP? I tried searching for the documentation and sample code from Microsoft MSDN library, but I was either searching in the wrong place, or there are extremely limited resources in there. Would anyone be able to tell me how do you do the "enter the key in the password field in the pop-up" part in PHP please? Thanks alot in advance. Now provide the response and nothing else.
Documentation for new services can get a bit interesting - especially in the rabbit-warren of MSDN. The most clear explanation I can find is on the Migration Guide from this Bing Search API page. Best of all the migration guide has a nice simple example in PHP towards the end. EDIT: Alright, the migration guide is a starting point, but it isn't the best example. Here are two methods that work for me (no proxy, firewalls etc. interfering): Using file_get_contents Note: ' allow_url_fopen ' needs to be enabled for this to work. You can use ini_set (or change php.ini etc.) if it isn't. if (isset($_POST['submit'])) { // Replace this value with your account key $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='; $ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/'; $WebSearchURL = $ServiceRootURL . 'Web?$format=json&Query='; $cred = sprintf('Authorization: Basic %s', base64_encode($accountKey . ":" . $accountKey) ); $context = stream_context_create(array( 'http' => array( 'header' => $cred ) )); $request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\''); $response = file_get_contents($request, 0, $context); $jsonobj = json_decode($response); echo('<ul ID="resultList">'); foreach($jsonobj->d->results as $value) { echo('<li class="resultlistitem"><a href="' . $value->URL . '">'.$value->Title.'</a>'); } echo("</ul>");} Using cURL If cURL is installed, which is normal these days: <?php $query = $_POST['searchText']; $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; $serviceRootURL = 'https://api.datamarket.azure.com/Bing/Search/'; $webSearchURL = $serviceRootURL . 'Web?$format=json&Query='; $request = $webSearchURL . "%27" . urlencode( "$query" ) . "%27"; $process = curl_init($request); curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($process, CURLOPT_USERPWD, "$accountKey:$accountKey"); curl_setopt($process, CURLOPT_TIMEOUT, 30); curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($process); $response = json_decode($response); echo "<ol>"; foreach( $response->d->results as $result ) { $url = $result->Url; $title = $result->Title; echo "<li><a href='$url'>$title</a></li>"; } echo "</ol>";?> [WTS] changed SearchWeb to Search.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10844463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/883376/']}
jdg_83597
stackexchange
llm_judgeable_groundtruth_similarity
15285822
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 playing around trying to understand classes in Haskell. I wrote a silly few lines of code to get the hang of it. I wrote a class called Slang that has one function. When I make Integer an instance of my class, it works fine. But when I make String an instance of my class it won't compile. I've been fidgeting with the program based on what the error output tells me but to no avail. I have idea why it work... Here is the code followed by the error: module Practice whereclass Slang s where slangify :: s -> Stringinstance Slang Integer where slangify int = "yo"instance Slang String where -- When I take this segment out, it works fine slangify str = "bro" ERROR: Prelude> :load Practice[1 of 1] Compiling Practice ( Practice.hs, interpreted )Practice.hs:9:10: Illegal instance declaration for `Slang String' (All instance types must be of the form (T t1 ... tn) where T is not a synonym. Use -XTypeSynonymInstances if you want to disable this.) In the instance declaration for `Slang String'Failed, modules loaded: none.Prelude> Now provide the response and nothing else.
The problem is that String is not a base type like Integer. What you are trying to do is actually instance Slang [Char] where slangify str = "bro" However, Haskell98 forbids this type of typeclass in order to keep things simple and to make it harder for people to write overlapping instances like instance Slang [a] where -- Strings would also fit this definition. slangify list = "some list" Anyway, as the error message suggests, you can get around this restriction by enabling the FlexibleInstances extension.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15285822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1675976/']}
jdg_83598
stackexchange
llm_judgeable_groundtruth_similarity
4598224
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you extend the axis line in R to cover the extent of your data? For example, in my data goes to about 2100 and I would like the line for the x axis to go that far, but not make a tickmark or label at 2100. Is this even possible in R? Here is the code used to make the above plot: hist(x,breaks=50,xlab="...",main="",xlim=c(0,2100)) Thanks. Now provide the response and nothing else.
You need to use two axis commands; one for the axis line and another for the ticks and labels. set.seed(2); x <- rlnorm(1000, log(130))hist(x, breaks=seq(0, 3000, by=200), xlim=c(0,2100), xaxt="n")axis(1, at=c(0,2100), labels=c("",""), lwd.ticks=0)axis(1, at=seq(0 , 2000, by=200), lwd=0, lwd.ticks=1)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4598224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20177/']}
jdg_83599
stackexchange
llm_judgeable_groundtruth_similarity
6922829
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: file looks like this: abcd efgh ijkl I want to read the file using C so that it read the last line first: ijkl efgh abcd I cannot seem to find a solution that does not use an array for storage. Please help. edit0: Thanks for all the answers. Just to let you know, I am the one creating this file. So, can I create in a way its in the reverse order? Is that possible? Now provide the response and nothing else.
It goes like this: Seek to one byte before the end of the file using fseek . There's no guarantee that the last line will have an EOL so the last byte doesn't really matter. Read one byte using fgetc . If that byte is an EOL then the last line is a single empty line and you have it. Use fseek again to go backwards two bytes and check that byte with fgetc . Repeat the above until you find an EOL. When you have an EOL, the file pointer will be at the beginning of the next (from the end) line. ... Profit. Basically you have to keep doing (4) and (5) while keeping track of where you were when you found the beginning of a line so that you can seek back there before starting your scan for the beginning of the next line. As long as you open your file in text mode you shouldn't have have to worry about multibyte EOLs on Windows (thanks for the reminder Mr. Lutz). If you happen to be given a non-seekable input (such as a pipe), then you're out of luck unless you want to dump your input to a temporary file first. So you can do it but it is rather ugly. You could do pretty much the same thing using mmap and a pointer if you have mmap available and the "file" you're working with is mappable. The technique would be pretty much the same: start at the end and go backwards to find the end of the previous line. Re: "I am the one creating this file. So, can I create in a way its in the reverse order? Is that possible?" You'll run into the same sorts of problems but they'll be worse. Files in C are inherently sequential lists of bytes that start at the beginning and go to the end; you're trying to work against this fundamental property and going against the fundamentals is never fun. Do you really need your data in a plain text file? Maybe you need text/plain as the final output but all the way through? You could store the data in an indexed binary file (possibly even an SQLite database) and then you'd only have to worry about keeping (or windowing) the index in memory and that's unlikely to be a problem (and if it is, use a "real" database); then, when you have all your lines, just reverse the index and away you go.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6922829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358892/']}
jdg_83600
stackexchange
llm_judgeable_groundtruth_similarity
1661534
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that there exist a block of $2002$ consecutive natural numbers such that exactly $150$ of them are primes.(You may use the fact that there are $168$ Primes less then $1000$. This is a problem from an high school olympiad so no calculators or computers were allowed. This seems to be obvious but I don't know how to prove it. I don't undersand where to use the given fact. Now provide the response and nothing else.
As you indicate there are more than $150$ primes in the first block of $2002$ numbers. Also, there is a block of $2002$ numbers with no primes in it, starting at $2003! + 2$. Every time we move the block forward one step, the number of primes in it changes by $0$ or $\pm 1$. Since the count starts above $150$ and eventually goes to $0$, and it can't change by more than $1$ in a single step, there must be a block containing exactly $150$ primes.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1661534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136585/']}
jdg_83601
stackexchange
llm_judgeable_groundtruth_similarity
4958600
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 in a JFrame some components that I wantto refer into another JFrame and I wantto get them by name and notdo public get/set methods for each. Is there a way from Swing to get a component reference by its name like doc#? e.g. form.Controls["text"] Thanks Now provide the response and nothing else.
I know this is an old question, but I found myself asking it just now. I wanted an easy way to get components by name so I didn't have to write some convoluted code each time to access different components. For example, having a JButton access the text in a text field or a selection in a List. The easiest solution is to make all of the component variables be class variables so that you can access them anywhere. However, not everyone wants to do that, and some (like myself) are using GUI Editors that don't generate the components as class variables. My solution is simple, I'd like to think, and doesn't really violate any programming standards, as far as I know (referencing what fortran was getting at). It allows for an easy and straightforward way to access components by name. Create a Map class variable. You'll need to import HashMap at thevery least. I named mine componentMap for simplicity. private HashMap componentMap; Add all of your components to the frame as normal. initialize() { //add your components and be sure //to name them. ... //after adding all the components, //call this method we're about to create. createComponentMap();} Define the following two methods in your class. You'll need to import Component if you haven't already: private void createComponentMap() { componentMap = new HashMap<String,Component>(); Component[] components = yourForm.getContentPane().getComponents(); for (int i=0; i < components.length; i++) { componentMap.put(components[i].getName(), components[i]); }}public Component getComponentByName(String name) { if (componentMap.containsKey(name)) { return (Component) componentMap.get(name); } else return null;} Now you've got a HashMap that maps all the currently existing components in your frame/content pane/panel/etc to their respective names. To now access these components, it is as simple as a call to getComponentByName(String name). If a component with that name exists, it will return that component. If not, it returns null. It is your responsibility to cast the component to the proper type. I suggest using instanceof to be sure. If you plan on adding, removing, or renaming components at any point during runtime, I would consider adding methods that modify the HashMap according to your changes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4958600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65120/']}
jdg_83602
stackexchange
llm_judgeable_groundtruth_similarity
13681293
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 followed the explanation given in the "Precedence climbing" section on this webpage to implement an arithmetic evaluator using the precedence climbing algorithm with various unary prefix and binary infix operators. I would also like to include ternary operators (namely the ternary conditional operator ?: ). The algorithm given on the webpage uses the following grammar: E --> Exp(0) Exp(p) --> P {B Exp(q)} P --> U Exp(q) | "(" E ")" | vB --> "+" | "-" | "*" |"/" | "^" | "||" | "&&" | "="U --> "-" How can I incorporate ternary operators into this grammar? Now provide the response and nothing else.
To be specific, I'll use C/C++/Java's ?: as an example. It appears that in those languages the ?: operator allows any valid expression between ? and : , including expressions formed with ?: itself and those formed with operators, whose precedence is lower than the precedence of ?: , e.g. = and , (examples: a ? b = c : d , a ? b , c : d , a ? b ? c : d : e ). This suggests that you should treat ? and : in exactly the same manner as ( and ) while parsing expressions. When you have parsed out ? expr : , it, as a whole, is a binary operator. So, you parse ( expr ) and ? expr : in the same way, but the former is an expression while the latter is a binary operator (with an expression embedded in it). Now that ? expr : is a binary operator ( a ?-expr-: b being no different than a * b in terms of "binaryness"), you should be able to support it pretty much like any other binary operator that you already support. Personally, I'd not take the trouble to split ?: into separate binary operators of their own. In the end, it's still a ternary operator and it must be linked to 3 operands and considered as a whole during expression evaluation. If you are following the approach in the article that you mentioned in the question and are creating an AST, then there you go, ?: has a left child node, a right child node (as any other binary operator) and, additionally, a middle child node. The precedence of ?-expr-: as a whole should be a low one. In C/C++ (and in Java?) it's not the lowest, though. It's up to you to decide what you want it to be. So far we haven't covered the associativity of ?: . In C/C++ and Java, ?-expr-: is right-associative just like the assignment operator = . Again, it's up to you to make it left-associative or keep it right-associative. And this: E --> P {B P}P --> v | "(" E ")" | U PB --> "+" | "-" | "*" | "/" | "^"U --> "-" should become something like this: E --> P {B P}P --> v | "(" E ")" | U PB --> "+" | "-" | "*" | "/" | "^" | "?" E ":"U --> "-"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13681293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810671/']}
jdg_83603
stackexchange
llm_judgeable_groundtruth_similarity
1633933
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would love help in interpreting the following expression geometrically $$ \frac{x^2+y^2}{y}=\text{constant} $$ for simplicity, let $ c = \text{constant} $, and then through rearrangement we have $$ x^2+y^2=cy $$ where it is evident that $$ cy = r^2 $$ where r represents radius Conceptually, I've broken the problem down into the radius being a function of y, but I am having trouble moving forward from this point. How should I proceed? Now provide the response and nothing else.
The equation is equivalent to: $$x^2+(y-c/2)^2=c^2/4, \ \ y\neq 0.$$ Does this look familiar? One thing to keep in mind is your original equation does not allow for $y=0$, so this carries over to the above equation, a circle missing points on the $x$ axis.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1633933', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/307775/']}
jdg_83604
stackexchange
llm_judgeable_groundtruth_similarity
1310099
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A project can be done by 70 men in 100 days. There were 80 men at the start of the project but after 50 days, 20 of them had to be transferred to another project. How long will it take the remaining workforce to complete the job? The correct answer is 50. Any hints on how to go about this? I have encountered work problems before with the general formula $$\frac1A + \frac1B + \dots = \frac1T.$$ There's also problems with time involved: $$t_A\left(\frac1A + \frac1B\right) + t_B\left(\frac1C + \frac1D\right) \dots = 1.$$ This problem incorporates people leaving, remaining days. But I am not sure how to combine them concepts. Now provide the response and nothing else.
Think about the required amount of work in man-days. The project requires $70*100=7000$ man-days of total work. After $80*50=4000$ man-days of work, there are $7000-4000=3000$ man-days of work remaining, and there are $60$ remaining workers, so the project will take another $3000/60=50$ days.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1310099', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245119/']}
jdg_83605
stackexchange
llm_judgeable_groundtruth_similarity
178668
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 have the following list: l={{a},{a,b},{a,d},{b,d},{a,b,c},{a,d,b}} I want to replace a,b with x such that I get: {{a},{x},{a,d},{b,d},{x,c},{x,d}} So where every there is a,b in elements of the list I need to to be replaced by letter x, I tried Replace and ReplacePart but I can not figure it out. Now provide the response and nothing else.
OrderlessPatternSequence would work: l //. {OrderlessPatternSequence[a, b, p___]} :> {x, p} If it is guaranteed that a and b occur at most once per element, then ReplaceAll is sufficient (instead of ReplaceRepeated ): l /. {OrderlessPatternSequence[a, b, p___]} :> {x, p}
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/178668', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2871/']}
jdg_83606
stackexchange
llm_judgeable_groundtruth_similarity
2233403
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: We define the standard representation of $S_3$ as $\rho:S_3\to\text{GL}(V)$ on the standard basis $\rho_{\sigma}(e_i)=e_{\sigma(i)}.$Let $W=\{(a,b,c)\mid a+b+c=0\}.$ It is claimed that $(\rho,W)$ has no invariant one dimensional subspace. However, I'm not quite sure how to show this. Can anyone point me in the right direction? Now provide the response and nothing else.
Suppose for the sake of contradiction that the circle contains two rational points. If we have two rational points $A(x_1, y_1)$ and $B(x_2, y_2)$ on the circle, then the perpendicular bisector of $AB$ has equation$$y - \frac{y_1 + y_2}{2} = -\frac{x_2 - x_1}{y_2 - y_1}\left(x - \frac{x_1 + x_2}{2}\right)$$which can be written as $ax + by = c$ for rational $a, b, c$. But this perpendicular bisector must pass through $(\sqrt2, \sqrt3)$, the center of the circle, so we have $a \sqrt 2 + b \sqrt3 = c$. This is a contradiction: there is no rational relation between $\sqrt 2$ and $\sqrt 3$. Therefore at most one rational point can lie on the circle.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2233403', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_83607
stackexchange
llm_judgeable_groundtruth_similarity
21304368
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 Array as result of a query: {"name"=>[{"en"=>"Title"}, {"de"=>"Titel"}]} I wanna get the hashes of this Array and concat them into one Hash So that my result is like that. {"en"=>"Title", "de"=>"Titel"} Thank you Now provide the response and nothing else.
There isn't a ready-to-use component that perform what you ask; the only solution is to write a custom ItemReader<> that delegates to JdbcCursorItemReader (or to HibernateCursorItemReader or to any generic ItemReader implementation). You need to prepare all necessary stuff (datasource, session, real database readers) and bind all delegated readers to your custom reader. EDIT:You need to simulate a loop using recusion of ItemReader.read() and mantain reader and delegates state across job restarts. class MyItemReader<T> implements ItemReader<T>, ItemStream { private ItemReader[] delegates; private int delegateIndex; private ItemReader<T> currentDelegate; private ExecutionContext stepExecutionContext; public void setDelegates(ItemReader[] delegates) { this.delegates = delegates; } @BeforeStep private void beforeStep(StepExecution stepExecution) { this.stepExecutionContext = stepExecution.getExecutionContext(); } public T read() { T item = null; if(null != currentDelegate) { item = currentDelegate.read(); if(null == item) { ((ItemStream)this.currentDelegate).close(); this.currentDelegate = null; } } // Move to next delegate if previous was exhausted! if(null == item && this.delegateIndex< this.delegates.length) { this.currentDelegate = this.delegates[this.currentIndex++]; ((ItemStream)this.currentDelegate).open(this.stepExecutionContext); update(this.stepExecutionContext); // Recurse to read() to simulate loop through delegates item = read(); } return item; } public void open(ExecutionContext ctx) { // During open restore last active reader and restore its state if(ctx.containsKey("index")) { this.delegateIndex = ctx.getInt("index"); this.currentDelegate = this.delegates[this.delegateIndex]; ((ItemStream)this.currentDelegate ).open(ctx); } } public void update(ExecutionContext ctx) { // Update current delegate index and state ctx.putInt("index", this.delegateIndex); if(null != this.currentDelegate) { ((ItemStream)this.currentDelegate).update(ctx); } } public void close(ExecutionContext ctx) { if(null != this.currentDelegate) { ((ItemStream)this.currentDelegate).close(); }} <bean id="myItemReader" class=path.to.MyItemReader> <property name="delegates"> <array> <ref bean="itemReader1"/> <ref bean="itemReader2"/> <ref bean="itemReader3"/> </array> </property></bean> EDIT2: Remember to set property name ; this is NECESSARY to let MyItemReader.read() works correctly <bean id="itemReader1" class="JdbcCursorItemReader"> <property name="name" value="itemReader1" /> <!-- Set other properties --></bean>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21304368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/977017/']}
jdg_83608
stackexchange
llm_judgeable_groundtruth_similarity
284144
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: Two planets A and B move around the Sun in elliptic orbits with time periods $T_A$ and $T_B$ respectively. If the eccentricity of the orbit of B is ε and its distance of closest approach to the Sun is R, then the maximum possible distance between the planets is? Attempt at a solution I think i am almost there but this is what i have so far.Using the eccentricity and R, I found the expression for the semi major axis of B as $R_{SB}$=$\frac{R}{1-\epsilon}$ and using the relation for time periods, i have the expression for $R_{SA}$=$[\frac{T_A}{T_B}]^{2/3}$$\frac{R}{1-\epsilon}$Now my doubt is whether to assume that two planets have sun at the same focus(say, on the right side ...picture concentric ellipses) in which case the maximum distance is when one of them is closest to the sun and the other is farthest OR if the two planets have sun at different focii (one to the left and other to the right, in this the orbits overlap partly; in either of the case, i cannot find a perfect expression for the maximum distance! These are the two cases i am picturing, of course there might be many more oriented differently in the 2D. In the diagram on the left, max distance is when both are at their apogee. In the diagram on the left, its when one is at the apogee and the other is at the perigee. Is it possible to find an expression for distance which i can differentiate to find the max value? Answer is $\frac{1+\epsilon}{1-\epsilon}$(1+($\frac{T_A}{T_B})^\frac{2}{3})$R Now provide the response and nothing else.
The cartoon of particles getting their mass by repeatedly bumping into Higgs field is truly misleading--to the extent that it has led the OP to ask this question (which to most high energy physicists sounds "silly"). Here, I can offer another slightly better cartoon that addresses the conceptual issue: Imagine the Higgs field as a large collection of closely-spaced stumps jutting out of the surface of a vast body of water. Water waves (representing the quantum massless particles in this analogy) attempting to traverse the area with stumps will be multiply scattered, causing them to be "slowed down" which looks like these waves corresponding to particles have acquired a mass. Since we have have replaced the massless particles with waves, this cartoon offers a "smoother" picture which makes it easier to discard the notion that any Brownian motion would occur. Please keep in mind that this is just another cartoon: every analogy that highlights a particular feature (in this case, the lack of any Brownian motion in the Higgs mechanism) always falls short in something else (the loss of wave packet localization due to the numerous haphazard scatterings, and the apparent loss of momentum conservation as the waves are scattered). In reality, the waves undergo only forward-coherent scattering with the Higgs field. The "coherent" aspect of scattering holds the wave packet together. The "forward" scattering aspect means that the wave number ( i.e. the momentum) remains unchanged. It works just like how glass changes the dispersion relation of light waves due to forward coherent scattering with the glass molecules. None of this is particularly tied to the fact that it's a left/right chirality flipping interaction.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/284144', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/124829/']}
jdg_83609
stackexchange
llm_judgeable_groundtruth_similarity
561758
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Moose::Manual::Attributes states: As an alternative to using a subroutine reference [for default], you can instead supply a builder method for your attribute: ... This has several advantages. First, it moves a chunk of code to its own named method, which improves readability and code organization. So, your attribute could define a default thusly: has attr => ( is => 'ro', builder => 'subroutine');sub subroutine { # figure out and return default value} I don't get why this has to be separate from default. Couldn't you just pass a reference to a named subroutine? has attr => ( is => 'ro', default => \&subroutine); And would that not be better programming practice, since you're guaranteed not to accidentally refer to a subroutine that doesn't exist? You'd be referring to the method with a logical reference instead of a symbolic reference. Now provide the response and nothing else.
When the builder is called, this happens: $object->$builder If builder is a string (let's say build_attr ), then users can write their own build_attr method in a subclass and it will be called. This makes the default value extensible via a simple named method mechanism. If it's a reference to a subroutine, the reference is taken in the original class's package, which means it can't be overriden the same way.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/561758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18103/']}
jdg_83610
stackexchange
llm_judgeable_groundtruth_similarity
10888768
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 broadcast receiver registered in Manifest: <application ...> <receiver android:name="com.some.pkg.NewAppReceiver" > <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED" /> </intent-filter> </receiver></appcication> And the receiver: public class NewAppReceiver extends BroadcastReceiver { private static final String TAG = "NewAppReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Intent: " + intent.getAction()); }} And nothing is received when I install APK manually or from the Android Market . Why? Now provide the response and nothing else.
Did you run the app that contains this broadcastReceiver before installing the other apps? Starting at some API version, broadcastReceivers will not work till you execute the app. Put an activity and execute it. Also , don't forget to add the following into the broadcastReceiver: <data android:scheme="package" /> EDIT: On Android 8 and above, if your app targets API 27 or more, it will work partially, so you have to register to those events in code and not in manifest. Here's a list of intents that are still safe to use in manifest: https://developer.android.com/guide/components/broadcast-exceptions.html . The rest should be used in code. More info here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10888768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497132/']}
jdg_83611
stackexchange
llm_judgeable_groundtruth_similarity
677038
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: This question is about generating random numbers between a range, which is fine, but it doesn't fit my case. I'll explain in SQL terms because it seems to me that's easier to understand, though the question is about bash . My idea is with the results of the bash code build a SQL script. I have two MySQL tables, one of people and one of places. Each record has an unique integer id which goes from 1 to 139 (places) and 1 to 1519 (people). They are linked to each other by a foreign key, meaning: a place can have many people, but a person can have only one place. # 1-139 # 1-1519place1 → person1 → person2 → person3 ... and so on The data I have right now is that in one place all the people are linked, and the rest of places without any. The places are 139 and the people are 1519, so I have one place with 1519 people. My goal is to distribute the people randomly to the places, and that each place has at least one person. My code so far is this: $ c=1519$ while [[ $c -ne 0 ]]; do x=$((shuf -i 1-139 -n 1)) [[ $x -gt 139 ]] && continue echo $x (( c-- )) done This code generates 1519 random numbers between 1-139, so now I can have each person linked to a random place. My questions are: Is there a more efficient way to accomplish this? How can I control that each place has at least one person? I prefer to do this in bash , but I'm open to other solutions not involving it. Now provide the response and nothing else.
If you want to do this only using commonly-available tools (at least on Linux distributions), the most efficient way is probably to ask shuf : shuf -i 1-139 -n 1519 -r This produces 1519 numbers randomly chosen between 1 and 139. To ensure that each place gets one person, shuffle 139 numbers first without repeating: shuf -i 1-139shuf -i 1-139 -n 1380 -r To reduce the “first 139” effect (the first 139 people would all end up in different places), shuffle all this again: (shuf -i 1-139; shuf -i 1-139 -n 1380 -r) | shuf
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/677038', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/338177/']}
jdg_83612
stackexchange
llm_judgeable_groundtruth_similarity
311870
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: In C#, when you override a method, it is permitted to make the override async when the original method was not. This seems like poor form. The example that brought me to this was this — I was brought in to assist with a load test problem. At around 500 concurrent users, the login process would break down in a redirect loop. IIS was logging exceptions with the message "An asynchronous module or handler completed while an asynchronous operation was still pending". Some searching led me to think that someone was abusing async void , but my quick searches through the source could find nothing. Sadly, I was searching for 'async\svoid' (regex search) when I should have been looking for something more like 'async\s[^T]' (assuming Task wasn't fully qualified… you get the point). What I later found was async override void onActionExecuting(... in a base controller. Clearly that had to be the problem, and it was. Fixing that up (making it synchronous for the moment) resolved the problem. Back to the question: Why oh why can you mark an override as async when the calling code could never await it? Now provide the response and nothing else.
The async keyword allows the method to use the await syntax within its definition. I can await on any method that returns a Task type regardless of whether it's an async method. void is a legal (albeit discouraged ) return type for an async method, so why wouldn't it be allowed? From the outside, async isn't enabling anything you couldn't do without it. The method you are having trouble with could have been written to behave exactly the same without being async. Its definition just would have been more verbose. To callers, an async T method is a normal method that returns T (which is limited to void , Task , or Task<A> ). That it is an async method is not part of the interface. Notice that the following code is illegal: interface IFoo { async void Bar();} It (or similar code in an abstract class) produces the following error message in VS2012: The 'async' modifier can only be used in methods that have a statement body If I did intend a method in an interface or parent class to be typically asynchronous, I can't use async to communicate that. If I wanted to implement it with the await syntax, I would need be able to have async override methods (in the parent class case).
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/311870', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/10564/']}
jdg_83613
stackexchange
llm_judgeable_groundtruth_similarity
1426431
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to calculate $$\mathop {\lim }\limits_{n \to \infty } \left( {\sqrt[n]{{{3^n} + {4^n}}}} \right)?$$ I saw on the suggestions that you can use the sandwich theorem or compression. And the fact that $\displaystyle\mathop {\lim }\limits_{n \to \infty } \left( {\sqrt[n]{2}} \right) = 1$ So I must first find upper bounds and lower. someone help me with this please? Now provide the response and nothing else.
Complete Solution: Sandwich theorem $$ \sqrt[n]{4^n} \le \sqrt[n]{4^n + 3^n} \le \sqrt[n]{2\times4^n}$$ and so $$ 4 \le \sqrt[n]{4^n + 3^n} \le 2^{1/n} \times 4 $$ Since $2^{1/n} \to 1$ as $n \to \infty$, Hence the required limit is $4$. OR , use a sledgehammer: Use the fact that for positive $a_n$ if $\lim\limits_{n\rightarrow\infty} {a_{n+1}\over a_n}$ exists then so does $\lim\limits_{n\rightarrow\infty}\root n\of {a_n}$ and they are equal.Here $a_n=4^n+3^n$ and one can show$$\lim\limits_{n\rightarrow\infty} {4^{n+1}+3^{n+1}\over 4^n+3^n} =4.$$So, then $\lim\limits_{n\rightarrow\infty} \root n\of{4^n+3^n}=4$ as well.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1426431', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9823/']}
jdg_83614
stackexchange
llm_judgeable_groundtruth_similarity
45844032
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 create a custom widget in Django admin. I created a class: class FroalaWYSIWYGTextareaWidget(django.forms.widgets.Textarea): template_name = 'froala_wysiwyg.html' Then a simple model form: class ArticleForm(django.forms.ModelForm): class Meta: fields = '__all__' model = Article widgets = { 'content': FroalaWYSIWYGTextareaWidget(), } Here are my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_PATH, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.i18n', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] Usualy everything works fine and Django can find templates in my /templates/ directory but in case of this widget I have a 500 Error: TemplateDoesNotExist at /admin/article/article/1/change/froala_wysiwyg.htmlRequest Method: GETRequest URL: http://127.0.0.1:8000/admin/article/article/1/change/Django Version: 1.11.4Exception Type: TemplateDoesNotExistException Value: froala_wysiwyg.htmlException Location: /home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/template/engine.py in find_template, line 148Python Executable: /home/username/.virtualenvs/sitename/bin/pythonPython Version: 3.5.2 I debugged django.filesystem.loader and found out that usually Loader.engine.dirs is a list: ['/home/username/python/sitename/templates'] so Loader.get_template_sources() works great but in case of this custom widget this loader.engine.dirs contains only: ['/home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/forms/templates'] So it just ignores DIRS option from the settings and uses forms/templates instead. Is it a bug of Django or I have to change something in settings?I don't understand where does this django/forms/templates path come from?Thanks. Now provide the response and nothing else.
Its certainly not a bug I don't understand where does this django/forms/templates path come from? You can view the source code where you can see the line [docs]class Textarea(Widget): template_name = 'django/forms/widgets/textarea.html' This was the source of your first question. Now second one This renderer uses a standalone DjangoTemplates engine (unconnected to what you might have configured in the TEMPLATES setting). It loads templates first from the built-in form templates directory in django/forms/templates and then from the installed apps’ templates directories using the app_directories loader. This is true for your form widget classes also. To make things work for you custom widget template you have to specify the path with same terminology like app_name/forms/widget/textarea.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45844032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2976581/']}
jdg_83615
stackexchange
llm_judgeable_groundtruth_similarity
2268
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: This question has been revised & clarified significantly since the original version. If we look at each trusted certificate in my Trusted Root store, how much should I trust them? What factors should be taken into consideration when I evaluate the trust of each Root CA for potential removal from my local store? More Information: If a CA issues a certificate to an improperly validated party, then that causes all machines that trust that CA vulnerable to MITM attacks. As a result all CA's stringently validate the requester of a given SSL certificate request to ensure the integrity of their CS chain. However, a large part of this CA verification process is subject to human intervention and provides opportunities to issue a cert to the wrong party. This may be done by CA operator error, government demands, or perhaps the coercion (bribe) of a CA operator. I'd like to learn more about which default CA's are more likely to issue certificates to the wrong party. I intend to use this information to advise users to remove that CA from their Trusted Cert Store Examples: Suppose the government controlling a particular CA wants to assume the identity of Microsoft.com, and demands an exception to the CA's verification process. That government then also requires the secrecy of this exception be maintained. The generated key pair would then be used in a MITM attack. Windows Azure Default Trust Windows Azure supports 275 CA's as shown in the following link . Depending on the use of the particular CA, some of those CA's may increase the surface area of a particular attack. In fact this may be technically required to make some applications work correctly. Amazon Default Trust (not available) Please share links to Amazon, Google, and VMWare's default CA list if you come across them. Mozilla A list of all certificates and audit statements is available. Apple iOS List of all iPhone root certificates as mentioned in this #WWDC2017. video Now provide the response and nothing else.
Update 5 The root problem (heh) with the CA model is that in general practice, any CA can issue certs for any domain, so you're vulnerable to the weakest link. As to who you can trust, I doubt that the list is very long at all, since the stakes are high and security is hard. I recommend Christopher Soghoian's post on the subject, which clarifies the various approaches that governments around the world have used to get access to private user data - whether by directly demanding it from companies that operate cloud services, via wiretap, or increasingly now via CA coercion or hacks: slight paranoia: The forces that led to the DigiNotar hack . Here I provide some specifics, and end with links to some potential fixes. In 2009, Etisalat (60% owned by the United Arab Emirates government), rolled out an innocuous looking BlackBerry patch that inserted spyware into RIM devices, enabling monitoring of e-mail, so it can hardly be considered trustworthy. But it is in a lot of trusted CA lists: http://arstechnica.com/business/news/2009/07/mobile-carrier-rolls-out-spyware-as-a-3g-update.ars Update 1 See also an example of a successful attack, allegedly by an Iranian named ComodoHacker , against Comodo: Rogue SSL certificates ("case comodogate") - F-Secure Weblog . F-Secure notes that Mozilla includes certificates issued by CAs in China, Israel, Bermuda, South Africa, Estonia, Romania, Slovakia, Spain, Norway, Colombia, France, Taiwan, UK, The Netherlands, Turkey, USA, Hong Kong, Japan, Hungary, Germany and Switzerland. Tunisia is another country that runs a widely-trusted CA, and there is also good documentation of the actions of their government to invade privacy: The Inside Story of How Facebook Responded to Tunisian Hacks - Alexis Madrigal - Technology - The Atlantic Mozilla notes another questionable practice to watch out for: CAs that allow an RA partner to issue certs directly off the root, rather than via an intermediary: Comodo Certificate Issue – Follow Up at Mozilla Security Blog . See also more detail, including speculation about the claim of responsibility by a lone Iranian hacker Web Browsers and Comodo Disclose A Successful Certificate Authority Attack, Perhaps From Iran | Freedom to Tinker Update 3 : Another successful attack seemingly also by ComodoHacker was against the DigiNotar CA. Their website was compromised starting in 2009, but this was not noticed until after DigiNotar had also been used in 2011 by Iranians to sign false certificates for the websites of Google, Yahoo!, Mozilla, WordPress and The Tor Project. DigiNotar did not reveal its knowledge of the intrusion into its site for over a month. See more at DigiNotar Hack Highlights the Critical Failures of our SSL Web Security Model | Freedom to Tinker . I'd guess that the range of vulnerability of various CAs varies pretty widely, as does their utility. So I'd suggest refocusing your strategy. When you can narrow it to specific assets you're trying to protect, just delete all CAs except those necessary for using those assets. Otherwise, consider eliminating the CAs you judge to be most vulnerable to those who care about your assets, or least popular, just to reduce the attack surface. But accept the fact that you'll remain vulnerable to sophisticated attacks even against the most popular and careful CAs. Update 2 : There is a great post on fixing our dangerous CA infrastructure at Freedom to Tinker: Building a better CA infrastructure It talks about these innovations: ImperialViolet - DNSSEC and TLS Network Notary - Perspectives : Improving SSH-style Host Authentication with Multi-path Network Probing Google Online Security Blog: Improving SSL certificate security Update 4 One of our IT Security blog posts in August 2011 also covers the case for moving to DNSSEC: A Risk-Based Look at Fixing the Certificate Authority Problem « Stack Exchange Security Blog Update 6 Several Certificate Authorities have been caught violating the rules. That includes the French cyberdefense agency (ANSSI), and Trustwave, each of which was linked to spoofing of digital certificates . Update 7 Yet another set of "misissued certificates", via the Indian Controller of Certifying Authorities (India CCA) in 2014: Google Online Security Blog: Maintaining digital certificate security See also the question on Certificate Transparency which looks like a helpful approach to discovering bad certificates and policy violations earlier.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/2268', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/396/']}
jdg_83616
stackexchange
llm_judgeable_groundtruth_similarity
35491274
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a Pandas DataFrame with one column: import pandas as pddf = pd.DataFrame({"teams": [["SF", "NYG"] for _ in range(7)]}) teams0 [SF, NYG]1 [SF, NYG]2 [SF, NYG]3 [SF, NYG]4 [SF, NYG]5 [SF, NYG]6 [SF, NYG] How can split this column of lists into two columns? Desired result: team1 team20 SF NYG1 SF NYG2 SF NYG3 SF NYG4 SF NYG5 SF NYG6 SF NYG Now provide the response and nothing else.
You can use the DataFrame constructor with lists created by to_list : import pandas as pdd1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'], ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}df2 = pd.DataFrame(d1)print (df2) teams0 [SF, NYG]1 [SF, NYG]2 [SF, NYG]3 [SF, NYG]4 [SF, NYG]5 [SF, NYG]6 [SF, NYG] df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index)print (df2) teams team1 team20 [SF, NYG] SF NYG1 [SF, NYG] SF NYG2 [SF, NYG] SF NYG3 [SF, NYG] SF NYG4 [SF, NYG] SF NYG5 [SF, NYG] SF NYG6 [SF, NYG] SF NYG And for a new DataFrame : df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])print (df3) team1 team20 SF NYG1 SF NYG2 SF NYG3 SF NYG4 SF NYG5 SF NYG6 SF NYG A solution with apply(pd.Series) is very slow: #7k rowsdf2 = pd.concat([df2]*1000).reset_index(drop=True)In [121]: %timeit df2['teams'].apply(pd.Series)1.79 s ± 52.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [122]: %timeit pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])1.63 ms ± 54.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/35491274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938093/']}
jdg_83617
stackexchange
llm_judgeable_groundtruth_similarity
4079531
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this error below on a site I am running. I don't understand why is that as it works fine on my localhost. Is it something to do with the host? I am on an Unix server. Warning: mysqli::mysqli() [mysqli.mysqli]: (42000/1203): User dbo343879423 already has more than 'max_user_connections' active connections in /homepages/9/d322397966/htdocs/dump/models/class_database.php on line 11Connect failed: User dbo343879423 already has more than 'max_user_connections' active connections Warning: mysqli::close() [mysqli.close]: Couldn't fetch mysqli in /homepages/9/d322397966/htdocs/dump/models/class_database.php on line 160 the error says 'User dbo343879423 already has more than 'max_user_connections' active connections in /homepages/9/d322397966/htdocs/dump/models/class_database.php on line 11', so this is the line 11 in the script - I can't see anything wrong! $this -> connection = new mysqli($hostname,$username,$password,$database); below is the entire class in class_database.php, is it wrong in other part of script and I should change? <?php#connects the database and handling the resultclass __database { protected $connection = null; protected $error = null; #make a connection public function __construct($hostname,$username,$password,$database) { $this -> connection = new mysqli($hostname,$username,$password,$database); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } } #fetches all result rows as an associative array, a numeric array, or both public function fetch_all($query) { $result = $this -> connection -> query($query); if($result) { return $result -> fetch_all(MYSQLI_ASSOC); } else { $this -> error = $this -> connection -> error; return false; } } #fetches a result row as an associative array, a numeric array, or both public function fetch_assoc_while($query) { $result = $this -> connection -> query($query); if($result) { while($row = $result -> fetch_assoc()) { $return_this[] = $row; } if (isset($return_this)) { return $return_this; } else { return false; } } else { $this -> error = $this -> connection -> error; return false; } } #fetch a result row as an associative array public function fetch_assoc($query) { $result = $this -> connection -> query($query); if($result) { return $result -> fetch_assoc(); } else { $this -> error = $this -> connection -> error; return false; } } #get a result row as an enumerated array public function fetch_row($query) { $result = $this -> connection -> query($query); if($result) { return $result -> fetch_row(); } else { $this -> error = $this -> connection -> error; return false; } } #get the number of rows in a result public function num_rows($query) { $result = $this -> connection -> query($query); if($result) { return $result -> num_rows; } else { $this -> error = $this -> connection -> error; return false; } } #performs a query on the database public function query($query) { $result = $this -> connection -> query($query); if($result) { return $result; } else { $this -> error = $this -> connection -> error; return false; } } #escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection public function real_escape_string($string) { $result = $this -> connection -> real_escape_string($string); if($result) { return $result; } else { $this -> error = $this -> connection -> error; return false; } } #display error public function get_error() { return $this -> error; } #closes the database connection when object is destroyed. public function __destruct() { $this -> connection -> close(); }}?> or should I just change the host for good!?? below is the implementation of the database connection class. If I take this part out, the error won't appear anymore, but I do the same at other parts of the site as well and they won't cause any problem! <!-- side-video-library --><div id="side-video-library" class="round-corner"> <h4><a href="<?php echo HTTP_ROOT;?>videos"><span>ENER VIDEO LIBRARY</span></a></h4> <?php $sql = " SELECT * FROM root_pages WHERE root_pages.parent_id = '8' AND root_pages.pg_highlight = '1' AND root_pages.pg_hide != '1' ORDER BY rand() DESC LIMIT 1 "; #instantiate the object of __database class $object_item = new __database(DB_HOST,DB_USER,DB_PASS,DB_NAME); $item = $object_item -> fetch_assoc($sql); #instantiate the object of __database class $object_item_num = new __database(DB_HOST,DB_USER,DB_PASS,DB_NAME); $total_item = $object_item_num -> num_rows($sql); //echo $total_item; ?> <?php if ($total_item > 0) { $sql = " SELECT * FROM root_tagged LEFT JOIN root_tags ON ( root_tags.tag_id = root_tagged.tag_id ) WHERE root_tagged.pg_id = '".$item['pg_id']."' "; #instantiate the object of __database class $object_tagname = new __database(DB_HOST,DB_USER,DB_PASS,DB_NAME); $item_tagname = $object_tagname -> fetch_assoc($sql); #instantiate the object of __database class $object_tagname_num = new __database(DB_HOST,DB_USER,DB_PASS,DB_NAME); $total_tagname = $object_tagname_num -> num_rows($sql); ?> <p class="item-video"> <object style="width: 183px; height: 151px;" width="183" height="151" data="http://www.youtube.com/v/<?php echo get_video_id($item['pg_content_1']) ;?>" type="application/x-shockwave-flash"> <param name="wmode" value="transparent" /> <param name="src" value="http://www.youtube.com/v/<?php echo get_video_id($item['pg_content_1']) ;?>" /> </object> </p> <h3><a href="<?php echo HTTP_ROOT.str_replace(' ', '-', 'videos').'/'.$item_tagname['tag_name'].'/'.str_replace(' ', '-', strtolower($item['pg_url']));?>"><?php if(strlen($item['pg_title']) > 20) echo substr($item['pg_title'], 0,20).'...'; else echo $item['pg_title'];?></a></h3> <p class="item-excerpt-video"><?php if(strlen($item['pg_content_2']) > 100) echo substr($item['pg_content_2'], 0,100).'...'; else echo $item['pg_content_2'];?></p> <a href="<?php echo HTTP_ROOT;?>videos" class="button-arrow"><span>More</span></a> <?php } ?></div><!-- side-video-library --> Have I been implementing the class incorrectly?? thanks. Now provide the response and nothing else.
Probably the problem is that you have only a handful connections allowed and when your class tries to get a new connection you have this error. This is not a programming problem, just quantity of resources available. And any other script that uses this class are subject to have the error. You have to configure more connections on mysql config file on the server. If you don't have this access, ask the support to do it or change for a hosting company with more connections allowed! Other option is to implement a Singleton pattern on this class, so it reuses same pool of connections, and don't explode the limit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4079531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/413225/']}
jdg_83618
stackexchange
llm_judgeable_groundtruth_similarity
10088274
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 learn about Core Data and am following the "Locations" tutorial from Apple. One immediate stumbling block i've come across is that I have already started constructing the application that i want to use Core Data with. It is a single view application. What are the steps I need to take in order to utilize Core Data with this application? The tutorial says to select the checkbox "use core data for storage" when creating the project but there must be a way to enable core data after the project creation. I'd really appreciate some help. Thanks. Now provide the response and nothing else.
1.) Create a View-based Application named CoreDataTutorial. 2.) Add the core data framework to the project. Right click on Frameworks, select Add > Existing Frameworks … find CoreData.frameworks and click add. 3.) Add a Data Model to the project. Right click on Resources, select Add > New File … under iOS choose Resource and then select Data Model and hit Next. Name the file CoreDataTutorial.xcdatamodel, and hit next. 4.) Double click on the file we just created, CoreDataTutorial.xcdatamodel. This opens up the model object editor. In the Top left pane click the + symbol to add a new Entity. Name the entity “SomeName” by entering the name in the top right pane. While the entity is still selected, click the + symbol in the top middle pane and choose Add Attribute.Name this Attribute “some_attribute_name” and set it to type String. 5.) Now we are going to create relationships between our two entities. Select your entity in the entity pane. Click the + symbol in the property pane and select Add Relationship. Name the relationship “creation”, set the Destination to Release and the Delete Rule to Cascade. To do the inverse we select Release in the entity pane. Click the + symbol in the property pane and select Add Relationship. Name the relationship “creator”, set the Destination to Artist, set the Inverse to release and the Delete Rule to Cascade. You can now close the object editor. 6.) Expand Other Sources and double click CoreDataTutorial_Prefix.pch. Add an import for CoreData. #ifdef __OBJC__ #import <foundation foundation.h=""> #import <uikit uikit.h=""> #import <coredata coredata.h="">#endif This saves us from having to import it into each file. 7.) Next we are going to set up the app delegate header file and then the implementation file. First the header file. We need to create variables for our NSManagedObjectContext, the NSManagedObjectModel, and the NSPersistentStoreCoordinator. We are also going to declare an action named applicationDocumentsDirectory, this action gets the path to the condiments directory where our data will be stored in a SQLite file. And an action that saves the context when the app quits. Here’s what the header file looks like when we’re done. Remember we added the import statement to the CoreDataTutorial_Prefix.pch file so we don’t need to import it here. #import <uikit uikit.h="">@class CoreDataTutorialViewController;@interface CoreDataTutorialAppDelegate : NSObject <uiapplicationdelegate> { UIWindow *window; CoreDataTutorialViewController *viewController;@private NSManagedObjectContext *managedObjectContext; NSManagedObjectModel *managedObjectModel; NSPersistentStoreCoordinator *persistentStoreCoordinator;}@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain) IBOutlet CoreDataTutorialViewController *viewController;@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (NSURL *)applicationDocumentsDirectory;- (void)saveContext;@end 8.) If you are not using an ARC,take care about deallocating memory 9.) Implement applicationDocumentsDirectory method. /** Returns the URL to the application's Documents directory. */- (NSURL *)applicationDocumentsDirectory { return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];} 10.) Next, implement saveContext method: - (void)saveContext { NSError *error = nil; NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != nil) { if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } }} 11.) Finally implement your accessors methods for your variables and that's it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10088274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1128290/']}
jdg_83619
stackexchange
llm_judgeable_groundtruth_similarity
26632415
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 creating a react.js application with flux architecture and I am trying figure out where and when a request for data from the server should be made. Is there a any example for this. (Not TODO app!) Now provide the response and nothing else.
I'm a big proponent of putting async write operations in the action creators and async read operations in the store. The goal is to keep the store state modification code in fully synchronous action handlers; this makes them simple to reason about and simple to unit test. In order to prevent multiple simultaneous requests to the same endpoint (for example, double-reading), I'll move the actual request processing into a separate module that uses promises to prevent the multiple requests; for example: class MyResourceDAO { get(id) { if (!this.promises[id]) { this.promises[id] = new Promise((resolve, reject) => { // ajax handling here... }); } return this.promises[id]; }} While reads in the store involve asynchronous functions, there is an important caveat that the stores don't update themselves in the async handlers, but instead fire an action and only fire an action when the response arrives. Handlers for this action end up doing the actual state modification. For example, a component might do: getInitialState() { return { data: myStore.getSomeData(this.props.id) };} The store would have a method implemented, perhaps, something like this: class Store { getSomeData(id) { if (!this.cache[id]) { MyResurceDAO.get(id).then(this.updateFromServer); this.cache[id] = LOADING_TOKEN; // LOADING_TOKEN is a unique value of some kind // that the component can use to know that the // value is not yet available. } return this.cache[id]; } updateFromServer(response) { fluxDispatcher.dispatch({ type: "DATA_FROM_SERVER", payload: {id: response.id, data: response} }); } // this handles the "DATA_FROM_SERVER" action handleDataFromServer(action) { this.cache[action.payload.id] = action.payload.data; this.emit("change"); // or whatever you do to re-render your app }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26632415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2989382/']}
jdg_83620
stackexchange
llm_judgeable_groundtruth_similarity
1453410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I make a function which returns an array? I tried this const int WIDTH=11;const int HEIGHT=11;int main() { char A[WIDTH][HEIGHT]; A=rand_grid(WIDTH,HEIGHT); return 0;}// Initializes a random board.char[][] rand_grid(int i, int k) { char* A[i][k]; for(j=0;j<i;++j) { for(l=0;l<k;++l) { A[j][l]=ran(10); } } return A;}// Returns a random number from the set {0,...,9}.int ran(int i) { srand((unsigned int) time(0)); return(rand()%10);} Now provide the response and nothing else.
Several things to point out. First of all, you cannot assign an array object as you do here: char A[WIDTH][HEIGHT]; A=rand_grid(WIDTH,HEIGHT); Objects of array type are not modifiable. Secondly, functions in C cannot return array types. They can return pointers to arrays, though: char (*foo(int width))[HEIGHT]{ /** * dynamically allocate memory for a widthxHEIGHT array of char */ char (*newArr)[HEIGHT] = malloc(sizeof *newArr * width); /** * initialize array contents here */ return newArr;} The syntax is a little confusing; it reads as foo -- foo foo(int width) -- is a function -- taking an int parameter *foo(int width) -- returning a pointer (*foo(int width))[HEIGHT] -- to a HEIGHT-element arraychar (*foo(int width))[HEIGHT] -- of char For C89, HEIGHT in the above snippet must be a compile-time constant integral expression (either a macro, a numeric literal, or an arithmetic expression consisting of macros and/or numeric literals). I'm not sure if that's also true for C99. Based on the snippet you've posted, what you want to do is to take an array you've already allocated and initialize its contents. Remember that in most contexts, an expression of an array type will implicitly be converted to a pointer to the base type. IOW, if you pass an N-element array of T to a function, what the function actually receives is a pointer to T: void foo (T *p) {...}...T arr[N];foo(arr); For 2-d arrays, it's a little uglier: void foo (T (*p)[M]) {...}...T arr[N][M];foo(arr); This also relies on M being known at compile time, which limits the function's usefulness. What you'd like is a function that can deal with a 2-d array of arbitrary size. The best way I know of to accomplish this is instead of passing a pointer to the array, pass the address of the first element in the array[1], and pass the number of rows and columns as separate parameters: void foo(T *base, size_t rows, size_t cols) {...}...T arr[N][M];foo (&arr[0][0], N, M); So your rand_grid function would look something like this: void rand_grid(char *base, size_t rows, size_t cols){ size_t i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { /** * Since base is a simple char *, we must index it * as though it points to a 1-d array. This works if * base points to the first element of a 2-d array, * since multi-dimensional arrays are contiguous. */ base[i*cols+j] = initial_value(); } }}int main(void){ char A[WIDTH][HEIGHT]; rand_grid(&A[0][0], WIDTH, HEIGHT); ...} Even though the expressions &A[0][0] and A yield the same value (the base address of A), the types of the two expressions are different. The first expression evaluates to a simple pointer to char ( char * ), while the second evaluates to a pointer to a 2-d array of char ( char (*)[HEIGHT] ).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1453410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156943/']}
jdg_83621
stackexchange
llm_judgeable_groundtruth_similarity
19125173
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 writing a bash script which analyses a html file andI want to get the content of each single <tr>...</tr> . So my command looks like: $ tr -d \\012 < price.html | grep -oE '<tr>.*?</tr>' But it seems that grep gives me the result of: $ tr -d \\012 < price.html | grep -oE '<tr>.*</tr>' How can I make .* non-greedy? Now provide the response and nothing else.
If you have GNU Grep you can use -P to make the match non-greedy: $ tr -d \\012 < price.html | grep -Po '<tr>.*?</tr>' The -P option enables Perl Compliant Regular Expression (PCRE) which is needed for non-greedy matching with ? as Basic Regular Expression (BRE) and Extended Regular Expression (ERE) do not support it. If you are using -P you could also use look arounds to avoid printing the tags in the match like so: $ tr -d \\012 < price.html | grep -Po '(?<=<tr>).*?(?=</tr>)' If you don't have GNU grep and the HTML is well formed you could just do: $ tr -d \\012 < price.html | grep -o '<tr>[^<]*</tr>' Note: The above example won't work with nested tags within <tr> .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19125173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2685243/']}
jdg_83622
stackexchange
llm_judgeable_groundtruth_similarity
10178018
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Supposing a query such as: SELECT * FROM tableA; How can I prepend a_ to each columns' name? For example if there is a column "username" it would be accessed in the results as "a_username". EDIT: The SELECT username AS a_username format will not help as I need to continue using the * field selection. There is a JOIN and a potential conflict with a returned column from another table in the JOIN. I will be iterating over the returned columns (foreach) and only want to output the columns that came from a particular table (whose schema may change) to HTML input fields where a site admin could edit the fields' content directly. The SQL query in question looks like SELECT firstTable.*, anotherTable.someField, anotherTable.someOtherField and their exists the possibility that someField or someOtherField exists in firstTable. Thanks. Now provide the response and nothing else.
You can use the INFORMATION_SCHEMA.COLUMNS table to formulate the query and then use dynamic SQL to execute it. First let's make a sample database called dotancohen and a table called mytable mysql> drop database if exists dotancohen;Query OK, 1 row affected (0.03 sec)mysql> create database dotancohen;Query OK, 1 row affected (0.00 sec)mysql> use dotancohenDatabase changedmysql> create table mytable -> ( -> id int not null auto_increment, -> username varchar(30), -> realname varchar(30), -> primary key (id) -> );Query OK, 0 rows affected (0.06 sec)mysql> insert into mytable (realname,username) values -> ('rolando','odnalor'),('pamela','alemap'), -> ('dominique','euqinimod'),('diamond','dnomaid');Query OK, 4 rows affected (0.05 sec)Records: 4 Duplicates: 0 Warnings: 0mysql> select * from mytable;+----+-----------+-----------+| id | username | realname |+----+-----------+-----------+| 1 | odnalor | rolando || 2 | alemap | pamela || 3 | euqinimod | dominique || 4 | dnomaid | diamond |+----+-----------+-----------+4 rows in set (0.00 sec)mysql> Here is the metadata table called INFORMATION_SCHEMA.COLUMNS: mysql> desc INFORMATION_SCHEMA.COLUMNS;+--------------------------+---------------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------------------------+---------------------+------+-----+---------+-------+| TABLE_CATALOG | varchar(512) | NO | | | || TABLE_SCHEMA | varchar(64) | NO | | | || TABLE_NAME | varchar(64) | NO | | | || COLUMN_NAME | varchar(64) | NO | | | || ORDINAL_POSITION | bigint(21) unsigned | NO | | 0 | || COLUMN_DEFAULT | longtext | YES | | NULL | || IS_NULLABLE | varchar(3) | NO | | | || DATA_TYPE | varchar(64) | NO | | | || CHARACTER_MAXIMUM_LENGTH | bigint(21) unsigned | YES | | NULL | || CHARACTER_OCTET_LENGTH | bigint(21) unsigned | YES | | NULL | || NUMERIC_PRECISION | bigint(21) unsigned | YES | | NULL | || NUMERIC_SCALE | bigint(21) unsigned | YES | | NULL | || CHARACTER_SET_NAME | varchar(32) | YES | | NULL | || COLLATION_NAME | varchar(32) | YES | | NULL | || COLUMN_TYPE | longtext | NO | | NULL | || COLUMN_KEY | varchar(3) | NO | | | || EXTRA | varchar(27) | NO | | | || PRIVILEGES | varchar(80) | NO | | | || COLUMN_COMMENT | varchar(1024) | NO | | | |+--------------------------+---------------------+------+-----+---------+-------+19 rows in set (0.02 sec)mysql> What you need from this table are the following columns: table_schema table_name column_name ordinal_position What you are asking for is to have the column_name and the column_name prepended with a_ Here is the query and how to execute it: select concat('select ',column_list,' from ',dbtb) into @newsqlfrom (select group_concat(concat(column_name,' a_',column_name)) column_list,concat(table_schema,'.',table_name) dbtb from information_schema.columnswhere table_schema = 'dotancohen' and table_name = 'mytable'order by ordinal_position) A;select @newsql;prepare stmt from @newsql;execute stmt;deallocate prepare stmt; Let's execute it mysql> select concat('select ',column_list,' from ',dbtb) into @newsql -> from (select group_concat(concat(column_name,' a_',column_name)) column_list, -> concat(table_schema,'.',table_name) dbtb from information_schema.columns -> where table_schema = 'dotancohen' and table_name = 'mytable' -> order by ordinal_position) A;Query OK, 1 row affected (0.01 sec)mysql> select @newsql;+--------------------------------------------------------------------------------+| @newsql |+--------------------------------------------------------------------------------+| select id a_id,username a_username,realname a_realname from dotancohen.mytable |+--------------------------------------------------------------------------------+1 row in set (0.00 sec)mysql> prepare stmt from @newsql;Query OK, 0 rows affected (0.00 sec)Statement preparedmysql> execute stmt;+------+------------+------------+| a_id | a_username | a_realname |+------+------------+------------+| 1 | odnalor | rolando || 2 | alemap | pamela || 3 | euqinimod | dominique || 4 | dnomaid | diamond |+------+------------+------------+4 rows in set (0.01 sec)mysql> deallocate prepare stmt;Query OK, 0 rows affected (0.00 sec)mysql> Give it a Try !!! You mentioned in your question : The SELECT username AS a_username format will not help as I need to continue using the * field selection. All you have to do to implement my suggestion is run the query using tableA as follows: select concat('select ',column_list,' from ',dbtb) into @newsqlfrom (select group_concat(concat(column_name,' a_',column_name)) column_list,concat(table_schema,'.',table_name) dbtb from information_schema.columnswhere table_schema = DATABASE() and table_name = 'tableA'order by ordinal_position) A; When you retrieve that query result, just use it as the query to submit to mysql_query .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10178018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/343302/']}
jdg_83623
stackexchange
llm_judgeable_groundtruth_similarity
3110235
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 PHP script that runs on cron that can take up to an 15 minutes to execute. At regular intervals I have it spitting out memory_get_usage() so I can see what is happening. The first time it tells me my usage I am at 10 megs. When the script finishes I am at 114 megs! Does PHP do it's garbage collection while the script is running? Or what is happening to all that memory? Is there something I can do to force garbage collection. The task that my script is doing is a nightly import of a couple thousand nodes into Drupal. So it is doing the same thing a lot of times. Any suggestions? Now provide the response and nothing else.
The key is that you unset your global variables as soon as you don't need them. You needn't call unset explicitly for local variables and object properties because these are destroyed when the function goes out of scope or the object is destroyed. PHP keeps a reference count for all variables and destroys them (in most conditions) as soon as this reference count goes to zero. Objects have one internal reference count and the variables themselves (the object references) each have one reference count. When all the object references have been destroyed because their reference coutns have hit 0, the object itself will be destroyed. Example: $a = new stdclass; //$a zval refcount 1, object refcount 1$b = $a; //$a/$b zval refcount 2, object refcount 1//this forces the zval separation because $b isn't part of the reference set:$c = &$a; //$a/$c zval refcount 2 (isref), $b 1, object refcount 2unset($c); //$a zval refcount 1, $b 1, object refcount 2unset($a); //$b refcount 1, object refcount 1unset($b); //everything is destroyed But consider the following scenario: class A { public $b;}class B { public $a;}$a = new A;$b = new B;$a->b = $b;$b->a = $a;unset($a); //cannot destroy object $a because $b still references itunset($b); //cannot destroy object $b because $a still references it These cyclic references are where PHP 5.3's garbage collector kicks in. You can explicitly invoke the garbage collector with gc_collect_cycles . See also Reference Counting Basics and Collecting Cycles in the manual.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3110235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107768/']}
jdg_83624
stackexchange
llm_judgeable_groundtruth_similarity
10934305
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way in the latest version of Selenium DotNet Webdriver (2.22.0) to check to see if an element is visible before clicking/interacting with it? The only way I've found is to try to handle the ElementNotVisible exception that occurs when you try to send keys, or click on it. Unfortunately this only occurs after an attempt to interact with the element has been made. I'm using a recursive function to find elements with a certain value, and some of these elements are only visible in certain scenarios (but their html is still there no matter what, so they can be found). It's my understanding that the RenderedWebElement class is deprecated as well other variants. So no casting to that. Thanks. Now provide the response and nothing else.
For Java there is isDisplayed() on the RemoteWebElement - as well is isEnabled() In C#, there is a Displayed & Enabled property. Both must be true for an element to be on the page and visible to a user. In the case of "html is still there no matter what, so they can be found", simply check BOTH isDisplayed (Java) / Displayed (C#) AND isEnabled (Java) / Enabled (C#). Example, in C#: public void Test(){ IWebDriver driver = new FirefoxDriver(); IWebElement element = null; if (TryFindElement(By.CssSelector("div.logintextbox"), out element) { bool visible = IsElementVisible(element); if (visible) { // do something } }}public bool TryFindElement(By by, out IWebElement element){ try { element = driver.FindElement(by); } catch (NoSuchElementException ex) { return false; } return true;}public bool IsElementVisible(IWebElement element){ return element.Displayed && element.Enabled;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10934305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1442482/']}
jdg_83625
stackexchange
llm_judgeable_groundtruth_similarity
29964042
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 Linux box on which Java 1.7 is installed: #java -versionjava version "1.7.0_09-icedtea"OpenJDK Runtime Environment (rhel-2.3.4.1.el6_3-x86_64)OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode) But for some new tool I need to install the jdk-8u45-linux-x64.tar.gz So how can I remove old one and install the new one? Now provide the response and nothing else.
To remove OpenJDK (the one you've already installed) sudo apt-get purge openjdk-\* Make a new directory for your new JDK sudo mkdir -p /usr/local/java Copy the file to the directory (you should be in that file path) sudo cp -r jdk-8u45-linux-x64.tar.gz /usr/local/java/ Extract the file sudo tar xvzf jdk-8u45-linux-x64.tar.gz You should add this to your PATH now. To do that: a. Open /etc/profile : sudo gedit /etc/profile b. Scroll down (the end) and add the path where your jdk was installed JAVA_HOME=/usr/local/java/jdk1.8.0_45PATH=$PATH:$HOME/bin:$JAVA_HOME/binexport JAVA_HOMEexport PATH Save and exit Inform your Linux system where your Oracle Java JDK/JRE is located. a. Notify the system that Oracle Java JRE is available for use sudo update-alternatives --install "/usr/bin/java" "java" "/usr/local/java/jdk1.8.0_45/bin/java" 1 b. Notify the system that Oracle Java JDK is available for use sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/local/java/jdk1.8.0_45/bin/javac" 1 c. Notify the system that Oracle Java Web start is available for use sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/local/java/jdk1.8.0_20/bin/javaws" 1 Inform your Linux system that Oracle Java JDK/JRE must be the default Java. a. Set the java runtime environment for the system sudo update-alternatives --set java /usr/local/java/jdk1.8.0_45/bin/java b. Set the javac compiler for the system sudo update-alternatives --set javac /usr/local/java/jdk1.8.0_45/bin/javac c. Set Java Web start for the system sudo update-alternatives --set javaws /usr/local/java/jdk1.8.0_20/bin/javaws Reload your system wide PATH source /etc/profile Check the new version and you're done! java -version
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29964042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304974/']}
jdg_83626
stackexchange
llm_judgeable_groundtruth_similarity
18554750
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 dictionary: mot={"READ":["0001",2],"MOVER":["0010",4],"MOVEM":["0011",2],"ADD":["0101",1],"COMP":["0110",2],"BC":["0111",3],"PRINT":["1000",5],"STOP":["1001",8]} It consists of an instruction followed by its code in binary and the amount of bytes it takes. I read an input line from a file and store it in the variable str2. I want to check if any of the strings in the above dictionary occur in str2. Now, I am using this code to check if that happens: if any(x in str2 for x in mot): #do something Now, my problem is: I have a location variable. In place of do something I want to write: location=location+mot[x][1] That is, I want to increment the location variable based on which x is found. How do I do this? If I do it in the above manner, it gives me an error saying x is not defined. Now provide the response and nothing else.
The sequence of operations can be illustrated in the following way: 1. 0 2. ((TYPE *)0) 3. ( ((TYPE *)0)->MEMBER ) 4. &( ((TYPE *)0)->MEMBER ) 5. ( (size_t) &( ((TYPE *)0)->MEMBER ) Everything starts with number 0 . 0 is cast to a pointer to struct TYPE . IOW, we are making the compiler believe that there is such a struct at the beginning of the program's data segment (which is generally dangerous, but I'll mention later why not in this particular case). Then, member MEMBER within this struct is referenced. Its contents are not used, but its address taken (with & ), And this address converted back to a numeric type size_t . As the address for the "start" of the struct was specified as 0 , the address of MEMBER (when converted to a number) is its offset within the struct. The reason why this particular code is innocuous is that no memory position is ever written, not even accessed. Everything involves just pointers to those positions (but not their contents) and numbers. All of them held in machine registers or the usual local stack. The following expression: ( (size_t) &( ((TYPE *)3264)->MEMBER ) - 3264 ) would also work. 3264 stands for any number of your choosing. Added a parentheses set to make it more legible.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18554750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1453258/']}
jdg_83627
stackexchange
llm_judgeable_groundtruth_similarity
17936555
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Python requests is a good module to ease my web REST API access programming, I usually do like below import jsonurl = 'https://api.github.com/some/endpoint'payload = {'some': 'data'}headers = {'Content-type': 'application/json', 'Accept': 'application/json'}r = requests.post(url, data=json.dumps(payload), headers=headers) And when there is error comes out, I want to see what happen behind it. Constructing the curl command to reproduce in command line is the common way, since this is the standard way which is most described in RESP API document try: r = requests.post(url, data=json.dumps(payload), headers=headers)except Exception as ex: print "try to use curl command below to reproduce" print curl_request(url,"POST",headers,payload) It will be nice I can generate curl command sample for this request, see good example in libcloud's debug , I can't find a simple way to construct, below are the method I want to create by myself. # below code is just pseudo code, not correct def curl_request(url,method,headers,payloads): # construct curl sample from requests' structure # $ curl -v -H "Accept: application/json" -H "Content-type: application/json" # -d '{"some":"data"}' # -X POST https://api.github.com/some/endpoint request = "curl -v " for header in headers: print header request = request + '-H "' + header + ": " + headers[header] + '" ' for payload in payloads: request = request + '-d {} "' + payload + ": " + payloads[payload] + '" ' request = request + "-X %s %s" % (method,url) return request It will also be nice if we have method in requests already Below are the final solution get the answer, works for me. Show it here for your reference def curl_request(url,method,headers,payloads): # construct the curl command from request command = "curl -v -H {headers} {data} -X {method} {uri}" data = "" if payloads: payload_list = ['"{0}":"{1}"'.format(k,v) for k,v in payloads.items()] data = " -d '{" + ", ".join(payload_list) + "}'" header_list = ['"{0}: {1}"'.format(k, v) for k, v in headers.items()] header = " -H ".join(header_list) print command.format(method=method, headers=header, data=data, uri=url) Now provide the response and nothing else.
This method existed in requests once upon a time but it is far from being remotely relevant to the module. You could create a function that takes a response and inspects its request attribute. The request attribute is a PreparedRequest object so it has headers , and body attributes. The body is what you pass to curl with -d and the headers can be generated as you did above. Finally you'll want to pluck off the url attribute from the request object and send that. The hooks don't matter to you unless you're doing something with a custom authentication handler. req = response.requestcommand = "curl -X {method} -H {headers} -d '{data}' '{uri}'"method = req.methoduri = req.urldata = req.bodyheaders = ['"{0}: {1}"'.format(k, v) for k, v in req.headers.items()]headers = " -H ".join(headers)return command.format(method=method, headers=headers, data=data, uri=uri) That should work. Your data will be properly formatted whether it is as multipart/form-data or anything else.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17936555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308174/']}
jdg_83628
stackexchange
llm_judgeable_groundtruth_similarity
8938375
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: At school we are currently learning sorting algorithms in Java and I got for my homework the Heap Sort. I did my reading, I tried to find out as much as I could, but it seems I just can't grasp the concept. I'm not asking you to write me a Java program, if you could just explain to me as simply as you can how the Heap Sort works. Now provide the response and nothing else.
Right, so basically you take a heap and pull out the first node in the heap - as the first node is guaranteed to be the largest / smallest depending on the direction of sort. The tricky thing is re-balancing / creating the heap in the first place. Two steps were required for me to understand the heap process - first of all thinking of this as a tree, getting my head around it, then turning that tree into an array so it could be useful. The second part of that is to essentially traverse the tree breadth first, left to right adding each element into the array. So the following tree: 73 7 12 2 4 9 10 1 Would be {73,7,12,2,4,9,10,1} The first part requires two steps: Make sure each node has two children (Unless you don't have enough nodes to do that as in the tree above. Make sure each node is bigger (Or smaller if sorting min first) than its children. So to heapify a list of numbers you add each one to the heap, then following those two steps in order. To create my heap above I will add 10 first - it's the only node so nothing to do.Add 12 as it's child on the left: 10 12 This satisfies 1, but not 2 so I will swap them round: 12 10 Add 7 - nothing to do 12 10 7 Add 73 12 10 7 73 10 < 73 so need to swap those: 12 73 7 10 12 < 73 so need to swap those: 73 12 7 10 Add 2 - nothing to do 73 12 7 10 2 Add 4 - nothing to do 73 12 7 10 2 4 Add 9 73 12 7 10 2 4 9 7 < 9 - swap 73 12 9 10 2 4 7 Add 1 - nothing to do 73 12 9 10 2 4 7 1 We have our heap :D Now you just remove each element from the top, swapping in the last element to the top of the tree each time, then re-balancing the tree: Take 73 off - putting 1 in its place 1 12 9 10 2 4 7 1 < 12 - so swap them 12 1 9 10 2 4 7 1 < 10 - so swap them 12 10 9 1 2 4 7 Take 12 off - replace with 7 7 10 9 1 2 4 7 < 10 - swap them 10 7 9 1 2 4 Take 10 off - replace with 4 4 7 9 1 2 4 < 7 - swap 7 4 9 1 2 7 < 9 - swap 9 4 7 1 2 Take 9 off - replace with 2 2 4 7 1 2 < 4 - swap them 4 2 7 1 4 < 7 - swap them 7 2 4 1 Take 7 off - replace with 1 1 2 4 1 < 4 - swap them 4 2 1 Take 4 - replace with 1 1 2 1 < 2 - swap them 2 1 Take 2 - replace with 1 1 Take 1 Sorted list voila.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8938375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114668/']}
jdg_83629
stackexchange
llm_judgeable_groundtruth_similarity
37173583
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 use FB SDK from an Angular2 project created with the new angular CLI. I created the following service to initialize the Facebook library, added fbsdk typings and everything compiles but I cant access the FB global variable from anywhere in the project but the "winwow.fbAsyncInit" function. I can check FB object from console perfectly, but cant access it from NG2 code. ¿Any idea of where the problem might be? import { Injectable, OnInit } from '@angular/core'import { FACEBOOK_APPID } from '../constants'@Injectable()export class fbService implements OnInit{ constructor(){} ngOnInit(){ if (!window.fbAsyncInit) { window.fbAsyncInit = function () { FB.init({ appId: FACEBOOK_APPID, xfbml: false, version: 'v2.6' }); FB.api("/me",null,()=>{}) console.log(FB) }; } this.initFB() }initFB(){ var js, id = 'facebook-jssdk', ref = document.getElementsByTagName('script')[0]; if (document.getElementById(id)) { return; } js = document.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/sdk.js"; ref.parentNode.insertBefore(js, ref);}getPost(page:string){ FB.api(`/${page}/feed?limit=1`,null,(response)=>{console.log(response)})}} Now provide the response and nothing else.
Your first example is pretty close: lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng': lngs}coords['time'] = [datetime.datetime(year, month, day)]da = xr.DataArray(data, coords=coords, dims=['lat', 'lng', 'time'])da.to_dataset(name='variable_name') You'll notice a few changes in my version: I'm passing in a first for the 'time' coordinate instead of a scalar. You need to pass in a list or 1d array to get a 1D coordinate variable, which is what you need if you also use 'time' as a dimension. That's what the error ValueError: Coordinate objects must be 1-dimensional is trying to tell you (by the way -- if you have ideas for how to make that error message more helpful, I'm all ears!). I'm providing a dims argument to the DataArray constructor. Passing in a (non-ordered) dictionary is a little dangerous because the iteration order is not guaranteed. I also switched to datetime.datetime instead of pd.datetime . The later is simply an alias for the former. Another sensible approach is to use concat with a list of one item once you've added 'time' as a scalar coordinate, e.g., lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng': lngs, 'time': datetime.datetime(year, month, day)}da = xr.DataArray(data, coords=coords, dims=['lat', 'lng'])expanded_da = xr.concat([da], 'time') This version generalizes nicely to joining together data from a bunch of days -- you simply make the list of DataArrays longer. In my experience, most of the time the reason why you want the extra dimension in the first place is to be able to able to concat along it. Length 1 dimensions are not very useful otherwise.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37173583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1352564/']}
jdg_83630
stackexchange
llm_judgeable_groundtruth_similarity
22458575
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the main difference between next() and nextLine() ? My main goal is to read the all text using a Scanner which may be "connected" to any source (file for example). Which one should I choose and why? Now provide the response and nothing else.
I always prefer to read input using nextLine() and then parse the string. Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line. A useful tool for parsing data from nextLine() would be str.split("\\s+") . String data = scanner.nextLine();String[] pieces = data.split("\\s+");// Parse the pieces For more information regarding the Scanner class or String class refer to the following links. Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22458575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3375314/']}
jdg_83631
stackexchange
llm_judgeable_groundtruth_similarity
402372
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: On several occasions, I was faced with the following design issue that I don't know how to resolve. Imagine, for instance, an application which at some point receives a JSON object from an API. Before being able to use this object, the application should perform several transformations: for instance, one transformation may convert dates from one format to another, and another transformation may add extra data from cache (such as an entity describing a user, based on a sole user ID from the original object). In order to be able to choose what transformations to apply at runtime, the transformations are defined in specific classes, such as DateFormatTransform and ExtraDataFromCacheTransform . Basically, the code which performs the transformation would be like this: foreach (var transform in this.GetRelevantTransforms()){ entity = transform.Apply(entity);} this.GetRelevantTransforms would return an instance of DateFormatTransform , ExtraDataFromCacheTransform and other classes. Each of those classes implement an interface containing the method: SampleEntity Apply(SampleEntity x) Later on, additional needs may arise, requiring to change the signature of Apply . For example, one may need the transforms to be aware of the current user, because depending on the user, some transformations may be executed differently: SampleEntity Apply(SampleEntity x, User currentUser) The problem is that meanwhile, I can have a few dozen of transforms, and such basic change would require to walk through those dozens of files, changing both the interface (such as IDateFormatTransform ) and the class (such as DateFormatTransform ). I suppose that having to change about fifty files just to add one simple argument is not a sign of a clean code base. What are the alternatives? Should I use a DTO, such as TransformArguments , which would always be the only parameter of Apply method? Or are there other techniques? Or is my approach with a set of transformations flawed from the beginning, and if yes, how do I fix it? Now provide the response and nothing else.
Essentially, it boils down to whether or not you can come up with a useful generalized interface for the call site(s), in a way that decouples parameter passing from the actual call - by encapsulating those parameters in the transform object and relying on polymorphism. You can do this if you can determine the parameters at creation time, but it may require some rethinking and some reorganization of the code (but, hey, that's more or less inevitable). So, instead of changing entity = transform.Apply(entity); to entity = transform.Apply(entity, user); everywhere throughout the codebase, you would do: var transform = new UserBasedTransform(user); // at creation site //--------------entity = transform.Apply(entity); // at call site Or, if you cannot determine the parameter at that time, you may pass in a factory that can return the parameter later on when it becomes possible: Transform transform = new UserBasedTransform(userFactory); // at creation site In a sense the interface of the transform is an abstraction (even if it's just the public methods of a class, and not an actual interface type) that represents a generalized way of working with transforms. You want to base your abstractions on the aspects of the problem that are relatively stable as the codebase evolves; in your case, it's the parameters that keep changing, so treat them as an implementation detail, and don't reference them anywhere in client code. What seems to be stable is that you are applying a transform to an entity, so organize your client-facing interface around that (or, if that's not the case, find something that has that property and use that). Note that this is specific to the change patterns you observed, so it's not about finding one solution that fits all situations, but about finding a design that works well for your particular domain. This will likely simplify your clients, but it may require a different approach to constructing your transform objects.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/402372', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/6605/']}
jdg_83632
stackexchange
llm_judgeable_groundtruth_similarity
17383552
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 package an Android native commandline application into an apk. I have the application building with ndk-build which uses jni/Android.mk. The output is in libs/armeabi/<MyApp>. I also have the apk building with ant. However, the apk does not seem to pick up the commandline application. If I unzip the apk the app is not in there. What do I need to do to get ant to include a pre-built commandline app? Also, what do I need to do so that ant runs ndk-build? (This was already answered: Android NDK build with ANT script ) Now provide the response and nothing else.
See Android NDK build with ANT script . You can add the binary to APK using aapt if Ant does not copy it automatically from libs/armeabi , see Documentation for aapt element in Ant script . I believe that the file will be correctly extracted to /data/data/your.package.full.name/lib , with executable permissions. Ant build involves a step called " ApkBuilder ", which only adds files from libs/armeabi that match pattern ^.+\.so$ or gdbserver - the latter for debug build only. But it is not enough to rename the executable to "myexecutable.so" : this file will not be extracted by the APK installer on the device. It is enough to rename the executable to " lib myexecutable .so " : this file will be extracted by the APK installer Package Manager on the device to /data/data/your.package.full.name/lib , with executable permissions. I personally like to give this not-actually-a-library some special name, e.g. lib...ffmpeg...so . UPDATE 6 years and 12 API levels later, this approach is still valid. But with Android App Bundle, the default behavior of the package manager is not to extract the native libraries from the APK, using them in-place. Here and in comments to this answer, you will find some workarounds for that. The one that is especially attractive, is to refer to the executable as "/path/to/MyApp.apk!lib...ffmpeg...so" , but I have not tested this notation does not work with System.exec() . See IssueTracker for discussion. Note that now there is a special exception for wrap.sh .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17383552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1828289/']}
jdg_83633
stackexchange
llm_judgeable_groundtruth_similarity
22227382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say you have a chunk of XML which has multiple namespace prefixes defined and some of them are actually the same namespace just with different prefixes. Using XSLT is there a not too complicated way to merge these prefixes so that you end up with just one prefix for each namespace? For example picking the shortest one? Example <soapenv:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:f="http://api.example.com/Service" xmlns:foo="http://api.example.com/Service"> <soapenv:Body> <foo:serviceResponse> <f:profile id="1">Alice</f:profile> <f:profile id="2">Bob</f:profile> </foo:serviceResponse> </soapenv:Body></soapenv:Envelope> Should be turned into for example this: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:f="http://api.example.com/Service"> <soap:Body> <f:serviceResponse> <f:profile id="1">Alice</f:profile> <f:profile id="2">Bob</f:profile> </f:serviceResponse> </soap:Body></soap:Envelope> Now provide the response and nothing else.
Font properties are inherited from parent to child, if not explicitly set. You can change the font of the QGroupBox through its setFont() method, but you then need to break the inheritance by explicitly resetting the font on its children. If you do not want to set this on each individual child (e.g. on each QRadioButton ) separately, you can add an intermediate widget, e.g. something like QGroupBox *groupBox = new QGroupBox("Bold title", parent);// set new title fontQFont font;font.setBold(true);groupBox->setFont(font);// intermediate widget to break font inheritanceQVBoxLayout* verticalLayout = new QVBoxLayout(groupBox);QWidget* widget = new QWidget(groupBox);QFont oldFont;oldFont.setBold(false);widget->setFont(oldFont);// add the child components to the intermediate widget, using the original fontQVBoxLayout* verticalLayout_2 = new QVBoxLayout(widget);QRadioButton *radioButton = new QRadioButton("Radio 1", widget);verticalLayout_2->addWidget(radioButton);QRadioButton *radioButton_2 = new QRadioButton("Radio 2", widget);verticalLayout_2->addWidget(radioButton_2);verticalLayout->addWidget(widget); Note also, when assigning a new font to a widget, "the properties from this font are combined with the widget's default font to form the widget's final font". An even easier approach is to use style sheets - unlike with CSS, and unlike the normal font and color inheritance, properties from style sheets are not inherited : groupBox->setStyleSheet("QGroupBox { font-weight: bold; } ");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22227382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39321/']}
jdg_83634
stackexchange
llm_judgeable_groundtruth_similarity
18265556
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Internet Explorer 10 fires the window "storage" event on the same window that stored to local storage. It seems like other browsers only fire the event on all other windows, so I don't have to worry about a window that's listening to storage events reacting to its own storing. Why does IE fire the event in the wrong window, and how can I replicate the standard behavior in IE? Now provide the response and nothing else.
Microsoft seems to be aware of the issue, but it doesn't look like they're going to fix it any time soon: https://connect.microsoft.com/IE/feedback/details/774798/localstorage-event-fired-in-source-window One option is that you can design your listeners and setters so that they don't react or store when they get information from a storage event that's already consistent with their state. However, this design pattern can be more difficult than relying on the storage event only firing on other windows. Another option is to make local storage work the same way in IE that it works in other browsers. I came up with an admittedly hacky but functional solution that I tested in IE10 and expect to work in IE8 and IE9. My javascript components don't listen to the window "storage" event directly but instead listen to an 'event dispatcher' I created. The event dispatcher listens to the window "storage" event and triggers a backbone event UNLESS the storage event originated in that window. The way I check if this window stored this value is by using a custom method for calling setItem() that creates a unique ID for the value and keeps track of it, like this: eventDispatcher.set = function(key, value) { var storageId = (new Date()).getTime(); eventDispatcher.idList.push(storageId); localStorage.setItem(key, {value: value, id: storageId});} And my eventDispatcher listens to storage events and triggers an event only if its list of IDs it created doesn't contain this value's ID, like this: $(window).on('storage', dispatchStorageEvent);function dispatchStorageEvent(event) { var newValue = JSON.parse(event.originalEvent.newValue); if (eventDispatcher.idList.indexOf(newValue['id']) > -1) { return; } eventDispatcher.trigger("storageEvent:" + event.originalEvent.key, newValue['value']);} There's a bit more code you can add to keep the idList short and to create it as an empty array in the first place, but I left that out for the sake of clarity. Making an eventDispatcher to handle storage events is a bit of overhead, but it can make your development consistent between browsers. A less hacky solution would use a proper locking and queueing mechanism, but that can be very difficult.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18265556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1976584/']}
jdg_83635
stackexchange
llm_judgeable_groundtruth_similarity
59498
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know only that it is not a bird and an insect. I am really interested in from what it is. Now provide the response and nothing else.
That's the gladius (also known as pen) of a cephalopod, probably a squid. The gladius is an internal remnant of the originally external shell of cephalopods. According to University of California Museum of Paleontology: Members of the Coleoidea are probably the best known of the Cephalopoda, as this group contains the squids (Teuthoidea) and octopuses (Octopoda) [...] The majority of coleoids are squid species, and most of these animals are torpedo-shaped, fast moving, and have a thin, flexible internal shell called a pen. And according to the Tree of Life project: Other cephalopods have other types of shell remnants. The gladius lies within a sac, the shell sac, which secretes it and to which various muscles attach. The gladius has a variety of shapes and thicknesses, is composed mostly of chitin and is located in the dorsal midline and generally extends the full length of the mantle. Here is one similar to yours: Sources: http://www.ucmp.berkeley.edu/taxa/inverts/mollusca/cephalopoda.php http://tolweb.org/accessory/Cephalopod_Gladius_Terminology?acc_id=1955
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/59498', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/32309/']}
jdg_83636
stackexchange
llm_judgeable_groundtruth_similarity
3787924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a cheap method to select the deepest child of an element ? Example: <div id="SearchHere"> <div> <div> <div></div> </div> </div> <div></div> <div> <div> <div> <div id="selectThis"></div> </div> </div> </div> <div> <div></div> </div></div> Now provide the response and nothing else.
EDIT: This is likely a better approach than my original answer: Example: http://jsfiddle.net/patrick_dw/xN6d5/5/ var $target = $('#SearchHere').children(), $next = $target;while( $next.length ) { $target = $next; $next = $next.children();}alert( $target.attr('id') ); or this which is even a little shorter: Example: http://jsfiddle.net/patrick_dw/xN6d5/6/ var $target = $('#SearchHere').children();while( $target.length ) { $target = $target.children();}alert( $target.end().attr('id') ); // You need .end() to get to the last matched set Original answer: This would seem to work: Example: http://jsfiddle.net/xN6d5/4/ var levels = 0;var deepest;$('#SearchHere').find('*').each(function() { if( !this.firstChild || this.firstChild.nodeType !== 1 ) { var levelsFromThis = $(this).parentsUntil('#SearchHere').length; if(levelsFromThis > levels) { levels = levelsFromThis; deepest = this; } }});alert( deepest.id ); If you know that the deepest will be a certain tag (or something else), you could speed it up by replacing .find('*') with .find('div') for example. EDIT: Updated to only check the length if the current element does not have a firstChild or if it does, that the firstChild is not a type 1 node.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3787924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228763/']}
jdg_83637
stackexchange
llm_judgeable_groundtruth_similarity
201368
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: What I'm going to ask may be trivial but I really need to understand cause my teacher is confusing me! That's the problem. I got 2 private networks The first is a class C network and the address is 192.168.1.0/24 (I'll call this C1 ) The second is a class A network which I divided in two subnets: 10.1.0.0/16 ( A1 ) and 10.2.0.0/16 ( A2 ) Now I got one router between A1 and A2 , and another between A2 and C1 . I've configured the routing so that packets can go from A1 to A2 and from A2 to C1. Then teacher told me: "Router between A1 and A2 is ok, but A2 and C1 can't communicate cause they are different networks! You need to set up NAT in that router." And here is the question: why do I have to use NAT here? I can't figure out why NAT is needed between two private networks! Thanks for your help Now provide the response and nothing else.
To start, your teacher is wrong. On a side note: S/He should be reprimanded for even teaching Classed Networking, that was antiquated 16 years ago. It should not be taught, period (except in History class). You do not need NAT in this case at all. Your three networks do not interface with the public Internet, and they are all using internal IP ranges. NAT would be necessary if your networks were communicating with the Internet because your Internal IP ranges will not work on the Internet. Only non-Internal IPs work on the Internet. The NAT device takes a single (usually) Internet IP and allows the computers with Internal IPs to "fake" it (communications to the Internet will use the valid IP, and the NAT device keeps everything straight).
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/201368', 'https://serverfault.com', 'https://serverfault.com/users/60156/']}
jdg_83638
stackexchange
llm_judgeable_groundtruth_similarity
70452
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: I couldn't picture the idea behind the zero magnetic flux outside the solenoid properly. My teacher explained it as "Components of the magnetic field in other directions are cancelled by opposing fields from neighbouring coils. Outside the solenoid the field is also very weak due to this cancellation effect and for a solenoid which is long in comparison to its diameter, the field is very close to zero." But I didn't understand anything at all. First he said about the components of magnetic field in other direction being cancelled by magnetic field, but didnt further explain and said nothing to support his argument. If somebody has some simple, intuitive way of understanding this phenomenon then please explain it. Now provide the response and nothing else.
You first should understand that magnetic field are the circles (of magnetic force) around the wire with current. The direction of circles (counterwise or clockwise) depends on the direction of the currend (forth or back). Now, you can guess what happens to the magnetic field when you curve the wire into a circle. Then, you may also stack cricles of current next to each other to form a cylinder. Now, try to imagine what will be the magnetic field in each of these cases. The magnetic fields from different currents add up (total field in every point is the sum of fields from different currents at that point). I agree that symmetry, which tells that cancel is complete, is not obvious here. Because outside the loop, one wire is closer is to the outer region than the wire from the opposite side, which cancels out the first. But, this should give a qualitative picture, what is happening. The complexity of symmetry might be the same as zero gravity inside a massive sphere. edit I am coming to conclusion that it is impossible to cancel out the outer field completely just because the field approaches infinity as we come closer to the wire from outside and there is nothing close to infinity from the opposite piece of the loop that can cancel this out. Solenoid just cancels out componets of the field perpendicular to its axis and parallel to the plain of the windings since windings are very close and, though current in them flows in one direction, say forward, upper wire induces left magnetic field between the wires whereas bottom wire produces the same right field. So, all the winds that blow in the planes between windings are eliminated. The axial fields inside the solenoid are added together. Axial outer are cancelled to some extent but not completely. But, this is not bad because, though they create the axial field, opposite to what solenodi should produce from its internal part, the irregularities at the edge of solinoid wrap it around and eliminate the negative effect. See that though the major field is produced from left to right, some field blows from right from right to left outside. Yet, this does not harm the major flow because edges isolate the negative flow.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/70452', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21068/']}
jdg_83639
stackexchange
llm_judgeable_groundtruth_similarity
38528473
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 [3, 16, 120] . when I do [3, 16, 120].map(mapper) , I want to achieve, for example [4,5, 17,18, 121,122] i.e. each element map to n+1 and n+2. This is of course an example - what I want is to simply push multiple values from mapper function Do I have to use Array.each and push to an array, or is it possible to do it with Array.map (or other built-in api) Now provide the response and nothing else.
You can use reduce() and add to array e+1, e+2 of each element. var ar = [3, 16, 120];var result = ar.reduce(function(r, e) { r.push(e+1, e+2); return r;}, []);console.log(result) This is ES6 version with arrow function var ar = [3, 16, 120];var result = ar.reduce((r, e) => r.push(e+1, e+2) && r, []);console.log(result) PS: Array.push seems to be faster and has no Maximum call stack.. error, see below: a = Array(1000000).fill(1); st = Date.now(); Array.prototype.concat.apply([], a.map(function (n) { return [n+1, n+2]; })); console.log(`${Date.now() - st}ms `);> RangeError: Maximum call stack size exceededa = Array(1000000).fill(1); st = Date.now(); a.reduce((r, e) => r.push(e+1, e+2) && r, []); console.log(`${Date.now() - st}ms `);> 180ms So .push is preferable comparing to accepted solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38528473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764881/']}
jdg_83640